List<String[]> method Adding always same values - java

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

Related

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

How to add columns and give result in separate variable

I have a text file of format
aaaaa 128321 123465
bbbbb 242343 424354
ccccc 784849 989434
I would like to add values in 2nd column and 3rd column into separate variables.
I am new to Java
Thank you.
Below is code that i used but i want the sum:
File f = new File("SampleInput.txt");
try{
ArrayList<String> lines = get_arraylist_from_file(f);
for(int x =1; x < lines.size(); x++){
System.out.println(lines.get(x));
}
}catch(Exception e){System.out.println("File not found!!!!");}
}
public static ArrayList<String> get_arraylist_from_file(File f)
throws FileNotFoundException {
Scanner s;
ArrayList<String> list = new ArrayList<String>();
s = new Scanner(f);
while (s.hasNext()) {
list.add(s.next());
}
s.close();
return list;
}
String line = lines.get(x);
String[] columns = line.split("\\s+"); // \\s+ is regex that splits string by 1 or more white-characters
String first = columns[0];
String second = columns[1];
String third = columns[2];
Try this.
ArrayList<String> lines = get_arraylist_from_file(f);
int sum1 = 0, sum2 = 0;
for(int x = 0 ; x < lines.size(); x += 3){
sum1 += Integer.parseInt(lines.get(x + 1));
sum2 += Integer.parseInt(lines.get(x + 2));
}
System.out.println("sum1=" + sum1 + " sum2=" + sum2);

insert values into integer array from List of type string

I want the values printed in line 5 to be inserted into an integer array.
The file contains both integer values and String values.
****I am still in learning process****
Sorry i changed the question a bit.
Thank you
File f = new File("SampleInput.txt");
try{
ArrayList<String> lines = get_arraylist_from_file(f);
for(int x =23; x < lines.size(); x++){
System.out.println(lines.get(x));
**enter code here**
}
}
catch(Exception e){
System.out.println("File not found!!!!");
}
}
public static ArrayList<String> get_arraylist_from_file(File f)
throws FileNotFoundException {
Scanner s;
ArrayList<String> list = new ArrayList<String>();
s = new Scanner(f);
while (s.hasNext()) {
list.add(s.next());
}
s.close();
return list;
}
List<Integer> numList = new ArrayList<>();
File f = new File("SampleInput.txt");
try{
ArrayList<String> lines = get_arraylist_from_file(f);
for(int x =23; x < lines.size(); x++){
System.out.println(lines.get(x));
**enter code here**
numList.add(Integer.parseInt(lines.get(x)));
}
}
I'm guessing you want something like this,
try{
ArrayList<String> lines = get_arraylist_from_file(f);
ArrayList<int> intLines = new ArrayList();
for (int x = 23; x < lines.size(); x++) {
System.out.println(lines.get(x));
intLines.add(Integer.parseInt(lines.get(x)));
}
}
Easier to use an ArrayList of Integers as follows
List<Integer> list = new ArrayList<Integer>();
File f = new File("SampleInput.txt");
try{
ArrayList<String> lines = get_arraylist_from_file(f);
for(int x =23; x < lines.size(); x++){
System.out.println(lines.get(x));
list.add(Integer.parseInt(lines.get(x)));
}
}
catch(Exception e){
System.out.println("File not found!!!!");
}
}
You have to create an int array outside of the loop of the appropriate size, and then just parse the strings and add them to the array in the loop:
ArrayList<String> lines = get_arraylist_from_file(f);
int[] intArray = new int[lines.size-23];
for(int x =23; x < lines.size(); x++){
System.out.println(lines.get(x));
//**enter code here**
String line = lines.get(x);
intArray[x-23] = Integer.parseInt(line);
}

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