尝试用Java编写一个简单的计算器,但是当我尝试编译它时,我一直遇到错误。不确定这是编码还是我在编译时所做的事情。任何帮助,将不胜感激!
import java.util.Scanner;
class simple calculator { // simple calculator
public static void main(String args[]){
System.out.println("My simple calculator\n");
Scanner bucky= new Scanner(System.in);
double fnum,snum,ans;
System.out.print("Enter the first and second " +
"number : ");
a=bucky.nextFloat(); //assign the numbers
b=bucky.nextDouble(); // to respective variable
System.out.println("What operation u want to " +
"perform");
String operation;
operation=bucky.next();
switch(operation) {
case "+":
ans=a + b;
System.out.print("Sum of the two inputs = ");
System.out.print(ans);
break;
case "-":
ans=a - b;
System.out.print("Subtraction of the two inputs = ");
System.out.print(ans);
break;
case "*":
ans=a * b;
System.out.print("Multiplication of the two inputs = ");
System.out.print(ans);
break;
case "/":
ans=a / b;
System.out.print("Division of the two inputs = ");
System.out.print(ans);
break;
default : System.out.println("Give a proper operation " +
"symbol ");
break; // not required
}
}
}
答案 0 :(得分:0)
两个编译错误:
class simple calculator
不是有效的,因为"计算器"不是一个公认的令牌。尝试:class SimpleCalculator
。同时将其公开并更改要匹配的文件的名称。 (SimpleCalculator.java)。 a
和b
,但没有给出类型。使用float a = ...
和double b = ...
。那个是浮动而另一个是双重奇怪,但是按下...... 需要注意的其他新问题:
bucky
。这是资源泄漏,在更大的应用程序中可能是一个主要的错误。在您阅读bucky.close()
operation = bucky.next()
bucky
完全没有告诉我它是什么或它的用途。尝试使用描述性变量名称。 (唯一的主要例外是循环索引的单字母名称等)。 fnum
和snum
是您声明但从不使用的局部变量。也许摆脱它们?以下是您编辑的代码:
import java.util.Scanner;
public class SimpleCalculator { // simple calculator
public static void main(String args[]){
System.out.println("My simple calculator\n");
Scanner bucky= new Scanner(System.in);
double ans;
System.out.print("Enter the first and second " +
"number : ");
float a=bucky.nextFloat(); //assign the numbers
double b=bucky.nextDouble(); // to respective variable
System.out.println("What operation u want to " +
"perform");
String operation;
operation=bucky.next();
bucky.close();
switch(operation) {
case "+":
ans=a + b;
System.out.print("Sum of the two inputs = ");
System.out.print(ans);
break;
case "-":
ans=a - b;
System.out.print("Subtraction of the two inputs = ");
System.out.print(ans);
break;
case "*":
ans=a * b;
System.out.print("Multiplication of the two inputs = ");
System.out.print(ans);
break;
case "/":
ans=a / b;
System.out.print("Division of the two inputs = ");
System.out.print(ans);
break;
default : System.out.println("Give a proper operation " +
"symbol ");
break; // not required
}
}
}
我能够毫无困难地在终端编译它。