I was trying to read a file.dat that contains many commands which are the character at the front of each line. But somehow the code that I wrote seems to skip or not recognize some of the character at the front of some line.
This is the file(original):
p 10 1 100
p 23 1 50
p 12 2 275
d 1
s 1
p 14 2 1050
d 3
x 4
p 37 2 25
p 41 1 500
d 2
s 2
q
This is the result:
got p!
x, y, z of p command are: 10, 1, 100
got p!
x, y, z of p command are: 23, 1, 50
got p!
x, y, z of p command are: 12, 2, 275
command not found
got p!
x, y, z of p command are: 14, 2, 1050
command not found
got p!
x, y, z of p command are: 37, 2, 25
got p!
x, y, z of p command are: 41, 1, 500
got s
x of s command is: 2
java.util.NoSuchElementException
Process finished with exit code 0
However, the results that came out would bring another error when I tried to edit the file a bit(just swap 2 lines)
Here is the edited file:
d 3
p 10 1 100
p 23 1 50
p 12 2 275
s 1
d 1
p 14 2 1050
x 4
p 37 2 25
p 41 1 500
d 2
s 2
q
The result of the edited file:
command not found
command not found
command not found
got s
x of s command is: 1
command not found
command not found
got p!
x, y, z of p command are: 37, 2, 25
got p!
x, y, z of p command are: 41, 1, 500
got s
x of s command is: 2
java.util.NoSuchElementException
Process finished with exit code 0
And this is the code that I wrote:
import java.io.File;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class test3 {
public static void main(String[] args) throws Exception {
File file = new File("file.dat");
try {
Scanner input = new Scanner(file);
while (input.hasNext()) {
if ("p".equals(input.next())) {
System.out.println("got p!");
String x = input.next();
String y = input.next();
String z = input.next();
//I put this print and variables x,y,z here for debug but also to implemented it later on
System.out.println("x, y, z of p command are: " + x + ", " + y + ", " + z);
} else if ("d".equals(input.next())) {
System.out.println("got d!");
String x = input.next();
System.out.println("x of d command: " + x);
} else if ("s".equals(input.next())) { //This is the show status operation from 's' command
System.out.println("got s");
String x = input.next();
System.out.println("x of s command is: " + x);
} else if ("q".equals(input.next())) {
System.out.println("got q");
} else {
System.out.println("command not found");
}
}
} catch (NoSuchElementException e) {
System.out.print(e);
}
}
}
I am thankful for any solutions that will come from you all