Click here to Skip to main content
15,914,452 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have input file include these elements:
1,3,1
2,1,4
3,4,2
4,0,6
5,2,3

and I want to read this input file to get an output in my code so I did this main code:
public static void main(String[] args) throws IOException {
		File File = new File("C:/Users/Princ/Downloads/testdata1 for SRTF.txt");
		Scanner s = new Scanner(File);
		int n = 5;
		int a;
		int b;
		int c;
		String data;

		SJF ob = new SJF();
		Process1 proc[] = new Process1[n];
		while (s.hasNextLine()) {

			for (int i = 0; n > i; i++) {

				a = Integer.parseInt(s.nextLine());
				b = Integer.parseInt(s.nextLine());

				c = Integer.parseInt(s.nextLine());

				proc[i] = new Process1(a, b, c);

			}

			ob.findavgTime(proc, n);
		}
	}

and then I get this error:-
Exception in thread "main" java.lang.NumberFormatException: For input string: "1,3,1"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
	at java.base/java.lang.Integer.parseInt(Integer.java:652)
	at java.base/java.lang.Integer.parseInt(Integer.java:770)
	at SJF.main(SJF.java:125)


What I have tried:

What should I fix in my code and what's wrong?
Posted
Updated 4-May-22 16:15pm

This line:
Java
a = Integer.parseInt(s.nextLine());

is reading the 3 numbers + comma as a string. So s.nextLine() is reading "1,3,1" as a whole string. This is what the compiler error message is telling you:
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)


You need to store as string, then split the string into 3 integer values. You can read more about it here: Split() String method in Java with examples - GeeksforGeeks[^]
 
Share this answer
 
v3
In addition of solution-1, change your for logic logic with split method:
Java
for (int i = 0; n > i; i++) {
	String fileLine = s.nextLine();
	// split method will return an array of values on the basis of ','
	String[] parts = fileLine.split(",");
	int part1 = parts[0]; // 1
	int part2 = parts[1]; // 3
	int part3 = parts[2]; // 1

	a = Integer.parseInt(part1);
	b = Integer.parseInt(part2);
	c = Integer.parseInt(part3);

	proc[i] = new Process1(a, b, c);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900