I just learned some java, and tried to make a simple calculator. When I got a scanner to input the total numbers the user needs, it worked fine. It was when I used another scanner to get the numbers that broke the code. It gave me these errors:
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Unknown Source)
at java.base/java.util.Scanner.next(Unknown Source)
at java.base/java.util.Scanner.nextDouble(Unknown Source)
at test2.calculator2.input(calculator2.java:45)
at test2.calculator2.main(calculator2.java:128)
Code:
package test2;
import java.util.Scanner;
public class calculator2 {
public static int cNum, cOp;
public static double num[], tNums, output;
public static String op[];
public static void input() {
boolean isInputting, invalidTNum, invalidOp;
isInputting = true;
invalidTNum = true;
invalidOp = true;
cNum = 1;
cOp = 1;
Scanner tNumInput = new Scanner(System.in);
System.out.println("Please input a number larger or equal to 2.");
System.out.println("How many numbers would you like?");
tNums = tNumInput.nextDouble();
while(invalidTNum) {
if(tNums < 2) {
invalidTNum = true;
System.out.println("Please input a number larger or equal to 2.");
System.out.println("How many numbers would you like?");
tNums = tNumInput.nextDouble();
} else {
invalidTNum = false;
tNumInput.close();
}
}
num = new double[(int)tNums];
op = new String[(int)tNums --];
System.out.println("Please input number.");
Scanner numInput = new Scanner(System.in);
41: num[cNum] = numInput.nextDouble();
cNum ++;
while(isInputting) {
if(cNum >= tNums) {
isInputting = false;
} else {
isInputting = true;
}
while(invalidOp) {
System.out.printf("Please input operation. (+,-,*,/)");
Scanner opInput = new Scanner(System.in);
op[cOp] = opInput.nextLine();
switch(op[cOp]) {
case"+":
case"-":
case"*":
case"/":
invalidOp = false;
default:
invalidOp = true;
System.out.println("Your operation is invalid.");
}
}
System.out.printf("Please input number.");
num[cNum] = numInput.nextDouble();
cOp ++;
cNum ++;
invalidOp = true;
}
}
public static void count() {
boolean isCounting = true;
double awnswer;
cNum = 1;
cOp = 1;
awnswer = num[cNum];
cNum ++;
while(isCounting) {
if(cNum >= tNums) {
isCounting = false;
} else {
isCounting = true;
}
switch(op[cOp]) {
case"+":
awnswer += num[cNum];
break;
case"-":
awnswer -= num[cNum];
break;
case"*":
awnswer *= num[cNum];
break;
case"/":
awnswer /= num[cNum];
break;
default:
break;
}
cNum ++;
cOp ++;
}
output = awnswer;
}
public static void main(String args[]) {
boolean reuse = true;
while(reuse) {
128: input();
count();
System.out.println(output);
}
}
}
Just to say, I really only just started on java, I'm really bad at it, so forgive me if I made some idiotic mistakes.