I've got some problems in java with putting scanner after an output, in a while loop. the scanner scans which method to go and then when it comes back to the start of the loop reset the variable.
I've already tried this and failed to find any understandable solution (I'm really new to java, and it is hard for me), or to solve it myself. here is the full code (i know the code is not so efficient):
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int con = 1;
System.out.println("Hey!,welcome to my games!");
Scanner scanner = new Scanner(System.in);
String game;
while (con == 1) {
System.out.println(
"Here Some games i have(Enter the text for the one you want):\nto stop=0\n1)calculator=1\n2)!Soon! Random numbers");
game = scanner.nextLine();
calculator();
scanner.reset();
System.out.println(game);
// if(game.equals("0")) {
// con=0;
// }
// else if(game.equals("1")) {
// System.out.println("Welcome Back!");
// }
// else {
// System.out.println("There is a mistake in your text");
// }
}
scanner.close();
}
static void calculator() {
int num1, num2, con = 1, stop = 1;
String op, ad = "add", su = "sub", mul = "multi", di = "div";
Scanner af = new Scanner(System.in);
while (con == 1) {
stop = 1;
System.out.println("Write number 1");
num1 = af.nextInt();
System.out.println("Write number 2");
num2 = af.nextInt();
System.out.println(
"Write an operation (one of these):\nAddition=add\nSubtraction=sub\nMultiplication=multi\nDivision=div");
op = af.next();
op = op.toLowerCase();
int minus = num1 - num2;
int plus = num1 + num2;
if (op.equals(ad)) {
System.out.println("The Operation is:Addition\n" + num1 + "+" + num2 + "=" + plus);
} else if (op.equals(su)) {
System.out.println("The Operation is:Subtraction\n" + num1 + "-" + num2 + "=" + minus);
} else if (op.equals(mul)) {
System.out.println("The Operation is:Multiplication\n" + num1 + "*" + num2 + "=" + num1 * num2);
} else if (op.equals(di)) {
System.out.println("The Operation is:Division\n" + num1 + "/" + num2 + "=" + num1 / num2);
} else {
System.out.println("Um,Did you make a mistake in your text?\nDo you want the calculator again?");
String yn = af.next();
yn = yn.toLowerCase();
if (yn.equals("yes") || yn.equals("yep")) {
stop = 0;
}
}
if (stop == 1) {
con = 0;
}
}
af.close();
}
}
as you can see, I tried myself to solve it and even put a comment on some of the code, but when it runs to the method and comes back, it fails because the scanner thinks there is something to scan before I wrote something. here is the exception-
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at Main.main(Main.java:12)