In this project, I was trying to create a calculator for simple math and more advance such as sin, cos, and the others. While I was writing the code I run into a problem with the if statement. The console wrote that :
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:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at basiccalculator.main(basiccalculator.java:14)
import java.util.Scanner;
public class basiccalculator {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
System.out.println("Do you want to use a simple calculator?" + "\n Please, answer with yes / no!");
String input = read.nextLine();
read.close();
if (input.equals("yes")) {
System.out.println("Enter two numbers: ");
Scanner scan1 = new Scanner(System.in);
double first = scan1.nextDouble();
double second = scan1.nextDouble();
System.out.print("Enter an operator (+, -, *, /): ");
char operator = scan1.next().charAt(0);
double result = 0.0;
switch (operator) {
case '+':
result = first + second;
break;
case '-':
result = first - second;
break;
case '*':
result = first * second;
break;
case '/':
result = first / second;
break;
default:
System.out.println("ERROR");
break;
}
System.out.println(first + " " + operator + " " + second + " = " + result);
scan1.close();
} else if (input.equals("no")) {
Scanner take = new Scanner(System.in);
System.out.println("Write the degree you want to calculate.");
double degree = take.nextDouble();
System.out.print("Enter an operator (sin, cos, tg, cotg): ");
String angle = take.next();
switch (angle) {
case "sin":
double radians = Math.toRadians(degree);
double sinValue = Math.sin(radians);
System.out.println("sin(" + degree + ") = " + sinValue);
break;
}
take.close();
}
}
}
So if somebody could help I will approach it! The problem I think is the if statement but I may be wrong. I am studying alone JAVA so I expect that there will be a lot of mistakes so please if you see some kind of simpler way or something please tell me .
Aucun commentaire:
Enregistrer un commentaire