What's wrong with my loop? Keep getting NoSuchElementException - java

I keep getting a NoSuchElement Exception at the line maze[r][c]=scan.next();. How can I resolve that?
try {
Scanner scan = new Scanner(f);
String infoLine = scan.nextLine();
int rows=0;
int columns=0;
for(int i = 0; i<infoLine.length();i++){
if(Character.isDigit(infoLine.charAt(i))==true){
rows = (int)infoLine.charAt(i);
columns = (int)infoLine.charAt(i+1);
break;
}
}
String [][] maze = new String[rows][columns];
int r = 0;
while(scan.hasNextLine()==true && r<rows){
for(int c = 0; c<columns;c++){
maze[r][c]=scan.next();
}
r++;
}
return maze;
} catch (FileNotFoundException e) {
e.printStackTrace();
}

Look at this part of your code:
while(scan.hasNextLine()==true && r<rows){ // 1
for(int c = 0; c<columns;c++){ // 2
maze[r][c]=scan.next(); // 3
} // 4
r++; // 5
} // 6
In line 1 you are checking to make sure that scan has another line available. But in line 3, you read that line - inside the 2:4 loop. So if there are more than 1 columns, you will be asking for the next scan more than once - and you only checked to see if there was one next line. So on the second column, if you're at the end of scan, you try to read from scan even though it's run out.
Try this:
try {
Scanner scan = new Scanner(f);
String infoLine = scan.nextLine();
int rows = 0;
int columns = 0;
for (int i = 0; i < infoLine.length();i++) {
if (Character.isDigit(infoLine.charAt(i))) {
rows = Character.digit(infoLine.charAt(i), 10);
columns = Character.digit(infoLine.charAt(i + 1), 10);
break;
}
}
String [][] maze = new String[rows][columns];
int r = 0;
while(scan.hasNextLine() && r < rows) {
int c = 0;
while(scan.hasNextLine() && c < columns) {
maze[r][c]=scan.next();
c++
}
r++;
}
return maze;
} catch (FileNotFoundException e) {
e.printStackTrace();
}

Related

How to read "Vertically" from data sets such as CSV

So my issue right now is that I'm really unsure of how to read data "vertically". As an example:
A B C D E F
1 4 1 3 5 8
2 3 1 3 6 4
3 2 1 3 7 5
4 1 1 3 7 4
I have to manipulate this data in a few ways. I'm pretty fine with anything on the same line although I'm clueless as to how to compare items from the same column. One objective I am trying to achieve is to re-write this with only attributes that have more than one domain. So in this instance, C, D, and all the numbers below them should be omitted.
public void dataProcessing(){
File file = new File("insertFilePathHere");
try {
Scanner input = new Scanner(file);
//Please ignore these, they are more relevant to the actual data set
String titles = input.nextLine();
String types = input.nextLine();
int i = 0;
while (input.hasNext()){
String line = input.nextLine();
//This is refering to a line that is incomplete, they are to be removed
if (line.contains("?")){
continue;
}
//For printing what i have back into a table to check results
String[] row = line.split(" ");
for(String index : row){
System.out.printf("%10s", index);
}
System.out.println();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I'd solve the problem this way:
use a 2D Array (new XXX[][])
read/scan the file LineByLine (two for/while-loops)
write those lines into the array
and then you should be able to work with that array
It should look something like this (I'm sorry if there are any wrong Functions or Errors because I'm coding this without an IDE with SyntaxHighlighting or IntelliSense - there shouldn't be any Errors though):
char[][] arr = new char[rows][cols];
Scanner scanCol = new Scanner(file);
//if you know the #rows and #cols
for(int col = 0; x < cols; x++) {
Scanner scanRow = new Scanner(scanCol.nextLine());
for(int row = 0; y < rows; y++) {
//incase an Exception comes up
try {
char currChar = scanRow.next().charAt(row);
arr[col][row] = currChar;
} catch (Exception e) { //you could also write IndexOutOfBoundsException e
break;
}
}
}
//if you only know the #cols
for(int col = 0; x < cols; x++) {
Scanner scanRow = new Scanner(scanCol.nextLine());
int row = 0;
while(true) { //unfortunately there's no function called hasNextChar()
try {
char currChar = scanRow.next().charAt(row);
arr[col][row] = currChar;
} catch (Exception e) { //you could also write IndexOutOfBoundsException e
break;
}
row++;
}
}
//the top one but in a cleaner way if inline ifs work in while-Loops
int totalRows = 0;
for(int col = 0; x < cols; x++) {
Scanner scanRow = new Scanner(scanCol.nextLine());
int row = 0;
while(row=0?true:(row < totalRows)) {
try {
char currChar = scanRow.next().charAt(row);
arr[col][row] = currChar;
} catch (Exception e) { //you could also write IndexOutOfBoundsException e
break;
}
row++;
}
totalRows = row;
}
//if you just know the file exists ;)
while(scanCol.hasNextLine()) {
Scanner scanRow = new Scanner(scanCol.nextLine());
int row = 0;
while(true) {
try {
char currChar = scanRow.next().charAt(row);
arr[col][row] = currChar;
} catch (Exception e) { //you could also write IndexOutOfBoundsException e
break;
}
row++;
}
}
//to find out how many cols and rows there are
scanCol = new Scanner(file);
int cols = 0;
while(scan.hasNextLine()) {
cols++;
scan.nextLine();
}
scanRow = new Scanner(new Scanner(file).nextLine());
while(true) {
try {
scanRow.nextChar();
rows++;
} catch (Exception e) {
break;
}
}
Please feel free to correct me or ask questions about my solution!

JAVA :Unable to view println after the while loop

I'm unable to view the println after exiting the "For" and "While" loop.
What am i doing wrong?
Assignment is : to Extract doubles from a txt file that has the numbers split by a "," . once i have the data do some calculations and display it. I've done all except the displaying. which I'm having some difficulty in.
try {
FileInputStream ofile = new FileInputStream("Sales Analysis.txt");
DataInputStream in = new DataInputStream(ofile);
BufferedReader Rreader = new BufferedReader( new InputStreamReader(in));
String Filedata ;
String read;
double[] TotalWeekSales = new double [7];
double[] DailyAverage = new double [7];
double TotalSales = 0;
double[] amount= new double [7];
double AverageSales = 0;
int Topsale = -1 ; // Position of Highest Week Sale
int LowestSale= -1; // Lowest Week Sale
while ((Filedata= Rreader.readLine()) != null) {
String[] Splitt = Filedata.split(",");
//double amount[] =new double [10];
for (int i = 0; i<Filedata.length(); i++)
{
read = Splitt[i];
amount[i] = Double.parseDouble(read);
TotalWeekSales[i] = amount[i];
DailyAverage[i]= (amount[i]/7);
TotalSales += amount[i];
System.out.println("\nWeek: "+(i+1));
System.out.println("\nAmount : $"+amount[i]);
}
};
/********* This part below doesn't Print ***********/
AverageSales = (TotalSales/7);
System.out.println("\nTotal Average Sales: $"+AverageSales);
} catch (Exception e) {
// TODO: handle exception
}
}
}
for (int i = 0; i<Filedata.length(); i++)
should be:
for (int i = 0; i < Splitt.length; i++)
there might be other bugs as well.
Note: it's difficult to read the code since it's not indented properly.

Populating Array from File input

I'm working on a pokemon battle simulator, (basically pokemonshowdown gen1), trying to automate making the pokemon array, but running into a Scanner problem. File is formatted as: Name.Type1.Type2.hp.attack.defense.special.speed.list of learnable moves. So:
Aerodactyl.Flying.Rock.80.105.65.60.130.Agility,Bide,Bite,Double-Edge,Double Team,Dragon Rage,Fire Blast,Fly,Hyper Beam,Mimic,Rage,Razor Wind,Reflect,Rest,Sky Attack,Substitute,Supersonic,Swift,Take Down,Toxic,Wing Attack.
I've gotten a method working for both my typeArray and moveArray but for some reason using basically the same loop the scanner is returning empty tokens instead of what's in the file.
Exception:
0 Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at Controller.initPokemonArray(Controller.java:169)
at Controller.<init>(Controller.java:29)
at Driver.main(Driver.java:15)
Here's the whole method, it's throwing the error at the parseInt call for hp.
private Pokemon[] initPokemonArray() {
Pokemon[] pokemonArray = new Pokemon[83];
try {
Scanner inputScan = new Scanner(new File("src/pokemon")).useDelimiter(".");
String name = "";
Type type1 = typeArray[0];
String inputType1 = "";
Type type2 = typeArray[0];
String inputType2 = "";
int hp = 0;
int atk = 0;
int def = 0;
int spc = 0;
int spe = 0;
String[] lm = {};
Move[] learnableMoves;
int counter = 0;
while (counter < 83) {
System.out.print(counter);
if (inputScan.hasNextLine()) {
name = inputScan.next();
System.out.println(name+" ");
//System.out.print("name");
inputType1 = inputScan.next();
for (int i = 0;i < 16;i++)
if (inputType1.equals(typeArray[i].toString()))
type1 = typeArray[i];
System.out.println(type1.toString()+" ");
inputType2 = inputScan.next();
for (int i = 0;i < 16;i++)
if (inputType2.equals(typeArray[i].toString()))
type2 = typeArray[i];
System.out.println(type2.toString()+" ");
hp = Integer.parseInt(inputScan.next());
System.out.println(hp+" ");
atk = Integer.parseInt(inputScan.next());
System.out.println(atk+" ");
def = Integer.parseInt(inputScan.next());
System.out.println(def+" ");
spc = Integer.parseInt(inputScan.next());
System.out.println(spc+" ");
spe = Integer.parseInt(inputScan.next());
System.out.println(spe+" ");
lm = inputScan.next().split(",");
System.out.println();
}
//TODO move this to private helper method
learnableMoves = new Move[lm.length];
for (int i = 0;i < 160;i++) {
for (int j = 0;j < lm.length;j++) {
if (lm[j] == moveArray[i].getName())
learnableMoves[j] = moveArray[i];
}
}
pokemonArray[counter] = new Pokemon(name,type1,type2,hp,atk,def,spc,spe,learnableMoves);
counter++;
}
inputScan.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return pokemonArray;
}
DISCLAIMER: this is a project for my java 2 course and also my first post on here so I don't know exactly what I'm supposed to do so just letting it be known down here.
The useDelimiter() method takes the passed String as regex value.https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#useDelimiter-java.lang.String-. A period has a specific meaning in regex. To get the specific character "." use this.
Scanner inputScan = new Scanner(new File("src/pokemon")).useDelimiter("\\.");

List<String[]> method Adding always same values

In my Java Project, i want to read values from txt file to List method.Values seems like;
1 kjhjhhkj 788
4 klkkld3 732
89 jksdsdsd 23
Number of row changable. I have tried this codes and getting same values in all indexes.
What can i do?
String[] dizi = new String[3];
List<String[]> listOfLists = new ArrayList<String[]>();
File f = new File("input.txt");
try {
Scanner s = new Scanner(f);
while (s.hasNextLine()) {
int i = 0;
while (s.hasNext() && i < 3) {
dizi[i] = s.next();
i++;
}
listOfLists.add(dizi);
}
} catch (FileNotFoundException e) {
System.out.println("Dosyaya ba?lanmaya çal???l?rken hata olu?tu");
}
int q = listOfLists.size();
for (int z = 0; z < q; z++) {
for (int k = 0; k < 3; k++) {
System.out.print(listOfLists.get(z)[k] + " ");
}
}
String [] dizi = new String [3];
dizi is a global variable getting overridden eveytime in the loop. Thats why you are getting same values at all indexes
Make a new instance everytime before adding to the list.
You put the same reference to the list, create a new array in while loop.
while (s.hasNextLine()){
String[] dizi = new String[3]; //new array
int i = 0;
while (s.hasNext() && i < 3)
{
dizi[i] = s.next();
i++;
}
listOfLists.add(dizi);
}

Getting a NullPointerException - how to remove it?

I'm new in programming.
array [row][col] = line.charAt(col);
^ this the line is where I'm getting NullPointerException in my code. How to remove it?
Scanner in = null;
try {
in = new Scanner(new FileReader("C:\\Documents and Settings\\UserXP\\My Documents\\src\\file.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line="";
ArrayList<String>arrayList=new ArrayList<String>();
while((line=in.nextLine())!=null) {
arrayList.add(line);
char [][] array = new char [2337][];
for (int row = 0; row<arrayList.size(); row++)
for(int col = 0; col<line.length(); col++) {
array [row][col] = line.charAt(col);
System.out.print(""+ array[row][col]);
}
System.out.println("");
}
//Close the input stream
in.close();
You're never allocating any memory for the second dimension of your array:
char [][] array = new char [2337][];
Gives you 2337 char[]s but all of them are null.
You'll need
array[row] = new char[line.length()];
before the column loop.
EDIT (clarify where to insert):
for (int row = 0; row<arrayList.size(); row++) {
array[row] = new char[line.length()];
for(int col = 0; col<line.length(); col++) {
array [row][col] = line.charAt(col);
System.out.print(""+ array[row][col]);
}
}
Note also, as your logic appears inefficient, as you're recreating rows every time you're adding a line.

Categories

Resources