我正在尝试创建一个简单的计算器,但为什么不打印出结果呢?
package SimpleCalc;
import java.util.Scanner;
public class SimpleCalc {
public static void main(String[] args) {
//String metod = "";
String minus, plus, multiplikation;
minus = "";
plus = "";
multiplikation = "";
int resultat;
Scanner sc = new Scanner(System.in);
System.out.println("Vad vill du använda? minus, plus, multiplikation?");
String svar1 = sc.nextLine();
//svar1 += metod;
System.out.println("Vilket tal?");
int nr1 = sc.nextInt();
System.out.println("Vilket tal vill du" + svar1 + "med?");
int nr2 = sc.nextInt();
if (svar1==minus) {
resultat = nr1 - nr2;
System.out.println(nr1 + svar1 + nr2 + "blirasd: " + resultat);
}
else if (svar1==plus) {
resultat = nr1 + nr2;
System.out.println(nr1 + svar1 + nr2 + "blir: " + resultat);
}
}
}
答案 0 :(得分:1)
您的操作字符串为空。还可以使用equals
来比较字符串。
package SimpleCalc;
import java.util.Scanner;
public class SimpleCalc {
public static void main(String[] args) {
//String metod = "";
String minus, plus, multiplikation;
minus = "-";
plus = "+";
multiplikation = "*";
int resultat;
Scanner sc = new Scanner(System.in);
System.out.println("Vad vill du använda? minus, plus, multiplikation?");
String svar1 = sc.nextLine();
//svar1 += metod;
System.out.println("Vilket tal?");
int nr1 = sc.nextInt();
System.out.println("Vilket tal vill du" + svar1 + "med?");
int nr2 = sc.nextInt();
if (svar1.equals(minus)) {
resultat = nr1 - nr2;
System.out.println(nr1 + svar1 + nr2 + "blirasd: " + resultat);
}
else if (svar1.equals(plus)) {
resultat = nr1 + nr2;
System.out.println(nr1 + svar1 + nr2 + "blir: " + resultat);
}
}
}
答案 1 :(得分:0)
将运算符符号放在变量中,如下所示:
minus = "-";
plus = "+";
multiplikation = "*";
此外,使用==
运算符无法比较java中的两个字符串。你必须等于方法。例如
使用if (svar1.equals(minus))
代替if (svar1==minus)
来比较两个字符串。