For some reason, my loop never ends, despite specifically assigning the value read by the scanner by the user. When user types 0, it goes on
public static void InseretToDB() throws IOException {
IO init = new IO();
Scanner scan = init.getScanner();
BufferedWriter bWriter = init.getWriter();
int j;
do {
System.out.println("Name");
String name = scan.nextLine();
bWriter.write(name);
bWriter.write(" ");
System.out.println("Ocuppation");
String occupation = scan.nextLine();
bWriter.write(occupation);
bWriter.newLine();
System.out.println(" Input 1 to continue, 0 to end");
j = (int) Integer.parseInt(scan.nextLine());
} while (j != 0);
}
The loop did end when I typed 0, but I changed the program to the following
Scanner scan = new Scanner(System.in);
BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(System.out));
Hope this helps,
Initalize the scanner as
Scanner scan = new Scanner(System.in);
Replace current code from
j = (int) Integer.parseInt(scan.nextLine());
To
try{
j = scan.nextInt();
}catch(Exception e){
j = -1;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.