line" int yes = Integer.parseInt(sc.nextLine());"导致我的计算器出现问题。我在eclipse上很新,所以任何纠正代码的建议都会很棒。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your first number");
int nr1 = Integer.parseInt(sc.nextLine());
System.out.println("Enter your second number");
int nr2 = Integer.parseInt(sc.nextLine());
System.out.println("Enter your sign (+ , - , /, *)");
int yes = Integer.parseInt(sc.nextLine());
int ans =0;
int j = 0;
int reset =j;
java.lang.String anvin = sc.nextLine();
if(anvin.equalsIgnoreCase("+")) {
ans = nr1 + nr2;
}
else if(anvin.equalsIgnoreCase("-")) {
ans = nr1 - nr2;
}
else if(anvin.equalsIgnoreCase("*")) {
ans = nr1 * nr2;
}
else if(anvin.equalsIgnoreCase("/")) {
ans = nr1 / nr2;
System.out.println(ans);
}
if(anvin.equalsIgnoreCase("yes")) {
return;
}
}
}
答案 0 :(得分:1)
尝试替换您输入数字的其中一行。
String anvin = sc.nextLine();
带
int anvinNumbers = sc.nextInt(); //for example
它可能无法回答为什么你的文本解析不起作用,但希望是一个解决方案。
重构代码
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in); //scanner object created
int ans = 0;
//Inputs
System.out.println("Enter your first number");
int nr1 = sc.nextInt();
System.out.println("Enter your second number");
int nr2 = sc.nextInt();
System.out.println("Enter your sign (+ , - , /, *)");
String anvin = sc.nextLine();
if(anvin.equalsIgnoreCase("+")) {
ans = nr1 + nr2;
}
else if(anvin.equalsIgnoreCase("-")) {
ans = nr1 - nr2;
}
else if(anvin.equalsIgnoreCase("*")) {
ans = nr1 * nr2;
}
else if(anvin.equalsIgnoreCase("/")) {
ans = nr1 / nr2;
}
System.out.println(ans);
}
}
}