Populating Array from File input - java

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("\\.");

Related

Java ; can not convert String Matrix to Double Matrix : Errorjava.lang.NumberFormatException

I've tried to solve this issue 3 days ago but nothing happens. I hope you can find a solution:
i'm making an application to read a txt file of numbers after that, i captured the data into a String Matrix and to operate them i need to convert it to a double matrix. but an error appear:
Errorjava.lang.NumberFormatException: For input string: "0,95768412 0,770070937"
. ive tried to replace the comma (.) for (.) but nothin happen.
Here a thumbnail of the file info:
0,620966467 0,397670717
0,144506398 0,86070719
0,344924707 0,49886148
0,568299164 0,407224505
0,55644466 0,580297755
0,940100947 0,920269925
0,45667026 0,253952562
0,046970841 0,04214613
0,548769197 0,114155205
0,220420195 0,035404045
0,804653981 0,371228693
0,688345818 0,575313752
0,54377148 0,891464466
i post the code for you can see the program.
try {
BufferedReader br = new BufferedReader(new FileReader("src\\numerosAleatorios.txt"));
//String matriz[][] = new String[99][1];
double matriz[][] = new double[99][2];
int numlineas = 0;
while (((Linea = br.readLine()) != null)) {
String a[] = Linea.split(" ");
for (int i = 0; i < a.length; i++) {
matriz[numlineas][i] = Double.parseDouble(a[i]);
}
numlineas++;
}
//double matrizDoble[][]= new double [99][1];
System.out.println("MATRIZ");
System.out.println("------------------------------");
for (int filas = 0; filas < matriz.length; filas++) {
for (int colum = 0; colum < matriz[filas].length; colum++) {
//matrizDoble[filas][colum]= Double.valueOf(matriz[filas][colum]).doubleValue();
System.out.print(matriz[filas][colum] + "\n");
}
}
System.out.println("\n Numero de parejas: "+numlineas);
} catch (Exception ex) {
System.out.println("Error"+ex);
}
Thanks for answer.!
I have tried your code with replacing ',' with '.' and it works fine for me.
String Linea;
try {
BufferedReader br = new BufferedReader(new FileReader("src\\numerosAleatorios.txt"));
// String matriz[][] = new String[99][1];
double matriz[][] = new double[99][2];
int numlineas = 0;
while (((Linea = br.readLine()) != null)) {
String a[] = Linea.split(" ");
for (int i = 0; i < a.length; i++) {
matriz[numlineas][i] = Double.parseDouble(a[i]);
}
numlineas++;
}
// double matrizDoble[][]= new double [99][1];
System.out.println("MATRIZ");
System.out.println("------------------------------");
for (int filas = 0; filas < matriz.length; filas++) {
for (int colum = 0; colum < matriz[filas].length; colum++) {
System.out.print(matriz[filas][colum] + "\n");
}
}
System.out.println("\n Numero de parejas: " + numlineas);
} catch (Exception ex) {
System.out.println("Error" + ex);
}
1) Split your String by white space:
String a[] = Linea.split("\\s+");
2) Replace "," with "." :
matriz[numlineas][i] = Double.parseDouble(a[i].replace(",", "."));
You're using String.split() with a "space"; however, your stacktrace shows a "tab" between the numbers. No space is found in the string, so it doesn't split. It then tries to parse both numbers in the string at once: "0.620966467 0.397670717" which fails.

Exception in thread "main" java.util.NoSuchElementException at java.util.StringTokenizer.nextToken(Unknown Source)

I don't know why it keeps saying this Error in Title
My question is "why my StringTokenizer Not working ?" Though it works in the first input "when user input X" ,
but at "a[i] = Integer.parseInt(st.nextToken());" it doesn't work.
The program function is to declare a group which is a no of friends and those friends give each other money and in the end we see from 0 how each one of them have got benefited "+sign result "MONEY"" or if he loses ie: that he gives more than he recieves so it's "-sign Result"money""
package test2;
/*
ID: toti5821
TASK: gift1
LANG: JAVA
*/
import java.util.*;
import java.io.*;
import java.util.StringTokenizer;
public class test2 {
public static void main(String[]args) throws IOException{
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new FileWriter("gift1.out"));
Scanner scan = new Scanner(System.in);
StringTokenizer st = new StringTokenizer(f.readLine());
int x = Integer.parseInt(st.nextToken());
HashMap<String,Integer> nameandmoney = new HashMap<String, Integer>();
for(int i=0;i < x;i++){
String name = f.readLine();
nameandmoney.put(name, 0);
}
for(int i=0;i<=x;i++) {
String thisname = f.readLine();
int size = 2;
int[] a= new int[size];
for (int j = 0; j < size; j++) {
a[i] = Integer.parseInt(st.nextToken());
}
System.out.println(a[1]);
nameandmoney.put(thisname,nameandmoney.get(thisname) - a[0]);
int leftover =a[0]%a[1];
nameandmoney.put(thisname,nameandmoney.get(thisname) + leftover);
int gift1 = a[0]/a[1];
if(a[1]==0) {
gift1=0;
}
for(int k=0;k<a[1];k++) {
String reciever = f.readLine();
nameandmoney.put(reciever,nameandmoney.get(reciever) - gift1);
}
} for(String names: nameandmoney.keySet()) {
out.println(names+" "+nameandmoney.get(names));
} } }

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.

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);
}

What's wrong with my loop? Keep getting NoSuchElementException

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();
}

Categories

Resources