Parse int is messing up my file scanning Im basically trying to read the first number in this txt document and use that as the number to implement within a for loop. My code runs well without including it but I want to use this to continue with this small project.
{
int i=0;
while(inFile.hasNextLine()){
String line = inFile.nextLine();
//int num = Integer.parseInt(line);
if(line.toLowerCase().equals("basketball")){
AllSports.add(new Basketball(i));
}
if(line.toLowerCase().equals("football")){
AllSports.add(new Football(i));
}
for(Sports obj:AllSports){
obj.Score_Med();
obj.Score_Med();
}
i ;
}
}
I commented the parseInt line, ive also tried .nextInt and it still gives me an error. My txt file currently looks like this:
3 Basketball Basketball Football
and the error im getting is
File name?:
input.txt
Exception in thread "main" java.lang.NumberFormatException: For input string: "Basketball"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:665)
at java.base/java.lang.Integer.parseInt(Integer.java:781)
at Sport_Runner.main(Sport_Runner.java:24)
My txt fiel:
3
Basketball
Basketball
Football
Line 24 is where the parseInt line is.
CodePudding user response:
As a general rule of thumb, everything inside the whileLoop
will be running more than once; your input only has one number, so if you're calling parseInt
on nextLine
inside your loop, you can expect to be parsing multiple lines.
Basically, you need to be doing that outside of your loop. Also I would probably use the int as the condition of the loop (for rather than while), though assuming no sneaky input it should be equivalent.
CodePudding user response:
You read from file with inFile.hasNextLine()
command. You wrote your txt file is 3 Basketball Basketball Football
. Actually this is just 1 line. You should enter new lines to your your txt file and it should be look like this :
3
Basketball
Basketball
Football
NOTE : I strongly suggest you do not leave any space for number lines.
First you will get 3, then you will get Basketball...
Also you the easiest way to parse a number among values that is not number is to use try catch block. Because ussually you can not know which line index is number or string.