Sorry to bother with a nullpointerexception question but this should be relatively easy and I don´t understand what´s causing it.
Basically there is a database called "andmebaas.txt" where all the data is separated by "###" and it should separate the information and display the ones I have requested (m2ng[0].nimi and m2ng[10].nimi)
import java.io.*;
import java.util.*;
public class kt_5_1 {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner1 = new Scanner(new File("andmebaas.txt"));
Scanner scanner2 = new Scanner(new File("andmebaas.txt"));
int n;
for(n = 0; scanner1.hasNext(); n++) {scanner1.nextLine();}
m2ngud m2ng[] = new m2ngud[n];
for (int c = 0; scanner2.hasNext(); c++) {
String wholeLine = scanner2.nextLine();
String[] line = wholeLine.split("###");
m2ng[c].nimi = line[0]; //this is line 17.
scanner2.nextLine();
}
System.out.println(m2ng[0].nimi);
System.out.println(m2ng[10].nimi);
}
}
public class m2ngud {
String nimi, kuup2ev, tootja, zanr, hinne;
}
the error:
Exception in thread "main" java.lang.NullPointerException
at kt_5_1.main(kt_5_1.java:17)
Thanks for all your answers in advance!
by
m2ngud m2ng[] = new m2ngud[n];
you allocated references, all of them are still referring to null, you need to initialize each element, like
m2ng[c] = new m2ng();
m2ng[c].nimi = line[0]; //this is line 17.
before accessing them
m2ng[c].nimi = line[0];
Before this, first create an object of m2ng class than access nimi variable of that m2ng class.
m2ng[c] = new m2ng();
Related
Hey I just started learning how to code. I am using netbeans and I want to transfer some data from a txt.file into an array in java. This might be a really simple fix but i just cant see whats wrong
This is the data in the txt.file:
58_hello_sad_happy
685_dhejdho_sahdfihsf_hasfi
544654_fhokdf_dasfjisod_fhdihds
This is the code I am using however smthg is wrong with the last line of code:
int points = 0;
String name = "";
String a = "";
String b = "";
public void ReadFiles() throws FileNotFoundException{
try (Scanner input = new Scanner(new File("questions.txt"))) {
String data;
while(input.hasNextLine()){
data = input.nextLine();
String[] Questions = data.split("_");
points = Integer.parseInt(Questions[0]);
name= Questions[1];
a = Questions[2];
b = Questions[3];
}
System.out.println(Arrays.toString(Questions));
}
}
This is the error I am getting:
error: cannot find symbol
System.out.println(Arrays.toString(Questions));
Thx soooo much guys.
You can also use the below code if you just want to print the data:
Files.readAllLines(Paths.get("questions.txt")).forEach(line -> {
System.out.println(Arrays.toString(line.split("_")));
});
Output is :
[58, hello, sad, happy]
[685, dhejdho, sahdfihsf, hasfi]
[544654, fhokdf, dasfjisod, fhdihds]
The correct version of your code should be like the below (you must access the variable Question in the declared scope by moving println into end of while loop) :
// definitions...
public void ReadFiles() throws FileNotFoundException{
try (Scanner input = new Scanner(new File("questions.txt"))) {
String data;
while(input.hasNextLine()){
data = input.nextLine();
String[] Questions = data.split("_");
points = Integer.parseInt(Questions[0]);
name= Questions[1];
a = Questions[2];
b = Questions[3];
System.out.println(Arrays.toString(Questions));
}
}
}
I'm designing a program to split data stored in a text file into two separate files based on the label of that data.
Here is a small version of that data.
0,1,2,normal.
5,5,5,strange.
2,1,3,normal.
I use a class to store each line as a sample. The class parses the line to store the last value as the label. I encapsulated each line as an object, because I intend to add features later.
Here is code for the Sample class
import java.util.Scanner;
public class Sample {
String[]str_vals = new String[3];
String label;
Sample(Scanner line) {
for (int i=0; i<3; i++) {
str_vals[i] = line.next();
}
label = line.next();
}
String getValsForCSV() {
StringBuilder retval = new StringBuilder();
for (int i=0; i<3; i++) {
retval.append(str_vals[i]).append(",");
}
retval.append(label).append(".");
return retval+"";
}
String getLabel() {
return label;
}
}
Below is the code in question. My Separator class.
import java.io.*;
import java.util.Scanner;
public class Separator {
public static final String DATAFILE = "src/etc/test.txt";
public static void main(String[] args) throws FileNotFoundException {
runData();
}
public static void runData() throws FileNotFoundException {
try (Scanner in = new Scanner(new File(DATAFILE))) {
// kddcup file uses '.\n' at end of each line
// setting this as delimiter which will consume the period
in.useDelimiter("[.]\r\n|[.]\n|\n");
Sample curr;
while(in.hasNext()) {
// line will hold all fields for a single sample
Scanner line = new Scanner(in.next());
line.useDelimiter(", *");
curr = new Sample(line);
try (
PrintWriter positive = new PrintWriter(new File(DATAFILE+"-pos"));
PrintWriter negative = new PrintWriter(new File(DATAFILE+"-neg"));
) {
if (curr.getLabel().equals("normal")) {
positive.println("GOOD");
} else {
negative.println("BAD");
}
}
}
}
}
}
This issue that I am experiencing is that the code only saves the last Sample seen to its respective file. So with above data the test.txt-neg will be empty and test.txt-pos will have a single line GOOD; it does not have two GOOD's as expected.
If I modify the test.txt data to include only the first two lines, then the files states are reversed (i.e. test.txt-neg has BAD and test.txt-pos is empty). Could someone please explain to me what is going on, and how to fix this error?
Because the error was pointed out in a comment. I wanted to give credit to KevinO and Elliott Frisch for the solution.
As mentioned, I'm creating a new PrintWriter each time and creating the PrintWriter in it's default mode of overwriting a file. As a result it always saves both files based on a single sample.
To correct this error, I have pulled out the instantiations of the PrintWriter to be in the try-with-resource block of the Scanner object
import java.io.*;
import java.util.Scanner;
public class Separator {
public static final String DATAFILE = "src/etc/test.txt";
public static void main(String[] args) throws FileNotFoundException {
runData();
}
public static void runData() throws FileNotFoundException {
try (
Scanner in = new Scanner(new File(DATAFILE));
PrintWriter positive = new PrintWriter(new File(DATAFILE+"-pos"));
PrintWriter negative = new PrintWriter(new File(DATAFILE+"-neg"));
) {
// kddcup file uses '.\n' at end of each line
// setting this as delimiter which will consume the period
in.useDelimiter("[.]\r\n|[.]\n|\n");
Sample curr;
while(in.hasNext()) {
// line will hold all fields for a single sample
Scanner line = new Scanner(in.next());
line.useDelimiter(", *");
curr = new Sample(line);
if (curr.getLabel().equals("normal")) {
positive.println("GOOD");
} else {
negative.println("BAD");
}
}
}
}
}
This is a project i'm working on at college, everything seems good except in the game class which initializes the game. Here is a snippet
public class Game{
private Player player;
private World world;
private ArrayList<NonPlayableFighter> weakFoes;
private ArrayList<NonPlayableFighter> strongFoes;
private ArrayList<Attack> attacks;
private ArrayList<Dragon> dragons;
public Game() throws IOException{
player = new Player("");
world = new World();
weakFoes = new ArrayList<NonPlayableFighter>();
strongFoes = new ArrayList<NonPlayableFighter>();
attacks = new ArrayList<Attack>();
dragons = new ArrayList<Dragon>();
loadAttacks ("Database-Attacks_20309.csv");
loadFoes ("Database-Foes_20311.csv");
loadDragons ("Database-Dragons_20310.csv");
}
after that follows some getters and the 4 method i am supposed to implement.
These methods are loadCSV(String filePath),loadAttacks(String filePath),loadFoes(String filePath),loadDragons(String filePath)
I have created loadCSV(String filePath) such that it returns an ArrayList of String[] here:
private ArrayList<String[]> loadCSV(String filePath) throws IOException{
String currentLine = "";
ArrayList<String[]> result = new ArrayList<String[]>();
FileReader fileReader = new FileReader(filePath);
BufferedReader br = new BufferedReader(fileReader);
currentLine = br.readLine();
while (currentLine != null){
String[] split = currentLine.split(",");
result.add(split);
}
br.close();
return result;
}
Then i would like to load some attacks, foes, and dragons and inserting them in the appropriate ArrayList.
I applied loadAttacks(String filePath) here:
private void loadAttacks(String filePath) throws IOException{
ArrayList<String[]> allAttacks = loadCSV(filePath);
for(int i = 0; i < allAttacks.size(); i++){
String[] current = allAttacks.get(i);
Attack temp = null;
switch(current[0]){
case "SA": temp = new SuperAttack(current[1],
Integer.parseInt(current[2]));
break;
case "UA": temp = new UltimateAttack(current[1],
Integer.parseInt(current[2]));
break;
case "MC": temp = new MaximumCharge();
break;
case "SS": temp = new SuperSaiyan();
break;
}
attacks.add(temp);
}
}
I wrote it such that it takes the ArrayList returned from loadCSV(String filePath) and searches in each String[] within the ArrayList on the first String using a switch thus creating the appropriate attack and adding it to attacks.
Then i would like to read another CSV for the Foes and the CSV file is structured such that in the first line there are some attributes the second line some attacks of type SuperAttack and the third line holds some attacks of type Ultimate attack. Also within each foe there is a boolean attribute that determines if it is a Strong or Weak Foe thus putting it in the right Arraylist. Here is the code for loadFoes(String filePath):
private void loadFoes(String filePath) throws IOException{
ArrayList<String[]> allFoes = loadCSV(filePath);
for(int i = 0; i < allFoes.size(); i += 3){
String[] current = allFoes.get(i);
String[] supers = allFoes.get(i+1);
String[] ultimates = allFoes.get(i+2);
ArrayList<SuperAttack> superAttacks = new ArrayList<SuperAttack>();
ArrayList<UltimateAttack> ultimateAttacks = new ArrayList<UltimateAttack>();
NonPlayableFighter temp = null;
for(int j = 0; i < supers.length; j++){
int index = attacks.indexOf(supers[j]);
if(index != -1){
superAttacks.add((SuperAttack)attacks.get(index));
}
else break;
}
for(int j = 0; i < ultimates.length; j++){
int index = attacks.indexOf(ultimates[j]);
if(index != -1){
ultimateAttacks.add((UltimateAttack)attacks.get(index));
}
else break;
}
if(current[7].equalsIgnoreCase("True")){
temp = new NonPlayableFighter(current[0], Integer.parseInt(current[1]),
Integer.parseInt(current[2]), Integer.parseInt(current[3]),
Integer.parseInt(current[4]), Integer.parseInt(current[5]),
Integer.parseInt(current[6]), true, superAttacks, ultimateAttacks);
strongFoes.add(temp);
}
else{
temp = new NonPlayableFighter(current[0], Integer.parseInt(current[1]),
Integer.parseInt(current[2]), Integer.parseInt(current[3]),
Integer.parseInt(current[4]), Integer.parseInt(current[5]),
Integer.parseInt(current[6]), false, superAttacks, ultimateAttacks);
weakFoes.add(temp);
}
}
}
First i get the first three String[] in the ArrayList returned from loadCSV(String filePath and made 2 loops to check if the attacks are within the previously loaded attacks CSV then i check for the attribute that determines if it is a strong or weak and accordingly creating a new NonPlayableFighter and adding it to the appropriate list.
Running the jUnit4 tests for this assignment it gives me a Compilation Error: Unhandled exception type IOException. And generally speaking does the code have any notable problems ?
It's better to reuse already exist CSV file readers for Java (e.g. CVSReader) if isn't a part of you task.
That makes a lot of code. I'll answer to your Compilation Error.
While reading a file you have to pu your code in a try catch in order to avoid this kind of error. In your loadCSV method you have to set up a try catch block.
Please refer to this site for complete tutorial.
try (BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")))
{
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
String[] split = currentLine.split(",");
result.add(split);
}
} catch (IOException e) {
e.printStackTrace();
}
To make it short, code that access to files have to be in a try catch to avoid IO Exception, or be in a method that throws the exception (but then it has to be catched elsewhere).
In that code you have a good example of a try-with-resource, very good way to manage your ressource and memory.
loadCSV(String filePath) is a infinite loop isn't it? And as for the IOException it as #RPresle suggested a try/catch would do the trick around the BufferedReader.
I know there are many questions about reading text files here but I have gone through all of them and I think I'm having some difficulty with syntax or SOMETHING because nothing that I've been trying has been working at all.
What I'm attempting to do is this:
1) read a text file inputed by user
2) copy each individual line into an array, so each line is its own element in the array
I feel like I am very close but for some reason I can't figure out exactly how to get it to work!
Here is the relevant code I have right now:
I keep getting out of bounds exceptions in three locations which I've marked off.
Been working on this for quite a while not sure what to do next! Any ideas?
import java.io.IOException;
import java.util.Scanner;
public class FindWords {
public static void main (String args[]) throws IOException{
FindWords d = new Dictionary();
((Dictionary) d).dictionary(); //********* out of bounds here
}
/**
* Validates and returns the dictionary inputed by the user.
*
* #param
* #return the location of the dictionary
*/
public static String getDict(){
///////////////////ASK FOR DICTIONARY////////////////////
System.out.println("Please input your dictionary file");
//initiate input scanner
Scanner in = new Scanner(System.in);
// input by user
String dictionary = in.nextLine();
System.out.println("Sys.print: " + dictionary);
//make sure there is a dictionary file
if (dictionary.length() == 0){
throw new IllegalArgumentException("You must enter a dictionary");
}
else return dictionary;
}
}
which calls on the class Dictionary:
import java.io.*;
public class Dictionary extends FindWords{
public void dictionary () throws IOException{
String dict = getDict();
String[] a = readFile(dict); //********** out of bounds here
int i = 0;
while(a[i] != null){
System.out.println(a[i]);
i++;
}
}
public static String[] readFile(String input) throws IOException{
//read file
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(input)));
System.out.println ();
int count = 0;
String[] array = new String[count];
try{
while (br.readLine() != null){
array[count] = br.readLine(); //********out of bounds here
count++;
}
br.close();
}
catch (IOException e){
}
return array;
}
}
Thank you for looking!
Edit: Just fyi: I have my .txt file in the parent project folder.
Have you tried this?:
List<String> lines = Files.readAllLines(Paths.get("/path/to/my/file.txt"));
and then transform your list to an array if you want:
String[] myLines = lines.toArray(new String[lines.size()]);
You start with an array size of zero...
int count = 0;
String[] array = new String[count];
Several issues here :
In Java, you can't expand arrays, i.e you have to know their length in advance when you instantiate them. Hence the ArrayOutOfBoundException. To make this easy, I suggest that you use an ArrayList instead.
In your while loop, you're making 2 calls to br.readLine(), so basically you're skipping one line out of 2.
You are initializing a zero-length array, hence the exception on the first iteration:
int count = 0;
String[] array = new String[count];
Since you probably don't know the expected size, work with a List instead:
List<String> list = new ArrayList<>();
String thisLine = null;
try{
while ((thisLine = br.readLine()) != null) {
list.add(thisLine);
}
}
You can get the total size afterwards by:
list.size();
Or even better, go with morganos solution and use Files.readAllLines().
I'm trying to make a simple highscore system for a minesweeper game. However i keep getting a file not found exception, and i've tried to use the full path for the file aswell.
package minesweeper;
import java.io.*;
import java.util.*;
public class Highscore{
public static void submitHighscore(String difficulty) throws IOException{
int easy = 99999;
int normal = 99999;
int hard = 99999;
//int newScore = (int) MinesweeperView.getTime();
int newScore = 10;
File f = new File("Highscores.dat");
if (!f.exists()){
f.createNewFile();
}
Scanner input = new Scanner(f);
PrintStream output = new PrintStream(f);
if (input.hasNextInt()){
easy = input.nextInt();
normal = input.nextInt();
hard = input.nextInt();
}
output.flush();
if(difficulty.equals("easy")){
if (easy > newScore){
easy = newScore;
}
}else if (difficulty.equals("normal")){
if (normal > newScore){
normal = newScore;
}
}else if (difficulty.equals("hard")){
if (hard > newScore){
hard = newScore;
}
}
output.println(easy);
output.println(normal);
output.println(hard);
}
//temporary main method used for debugging
public static void main(String[] args) throws IOException {
submitHighscore("easy");
}
}
You don't reveal on which line of code the exception is emitted. (Note: not posting all information you have about the problem reduces your chances of getting useful answers.)
However, my hunch is that it comes from the second call shown below, in which case the problem lies in trying to open the file twice:
Scanner input = new Scanner(f);
PrintStream output = new PrintStream(f);
Have you checked that the file exists and you have access rights for it?
Have you tried this?
if(f.isFile())
System.out.println("Yes, we have a file");
if(f.canWrite())
System.out.println("Yes, we have can write to the file");