当前位置: 代码迷 >> J2EE >> 帮忙瞥一个小程序
  详细解决方案

帮忙瞥一个小程序

热度:175   发布时间:2016-04-22 02:54:34.0
帮忙看一个小程序
package one;

import java.util.Scanner;

public class Program{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("请输入数字A");
double A = scanner.nextDouble();
System.out.println("请选择运算符(+、-、*、/):");
String B = scanner.next();
System.out.println("请输入数字B");
double C = scanner.nextDouble();
double D = 0;
if(B == "+"){
D = A + C;
}
if(B == "-"){
D = A - C;
}
if(B == "*"){
D = A * C;
}
if(B == "/"){
D = A / C;
}
System.out.println("结果是:" + D);
}
}
大家帮忙看一下为什么结果总是0.0呢?

------解决方案--------------------
B=="+" 改成 B.equals("+")

其他一样的改一下
------解决方案--------------------
if(B == "+"){
D = A + C;
}
if(B == "-"){
D = A - C;
}
if(B == "*"){
D = A * C;
}
if(B == "/"){
D = A / C;
}
这些都没执行, if(B == "/"){
} String 类型的不用==号,用equals();
------解决方案--------------------
public class Program{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("请输入数字A");
double A = scanner.nextDouble();
System.out.println("请选择运算符(+、-、*、/):");
String B = scanner.next();
System.out.println("请输入数字B");
double C = scanner.nextDouble();
double D = 0;
if(B.equals("+")){
D = A + C;
}
if(B .equals("-")){
D = A - C;
}
if("*".equals(B)){
D = A * C;
}
if("/".equals(B)){
D = A / C;
}
System.out.println("结果是:" + D);
}
}

------解决方案--------------------
== 改成 equals 就好了
  相关解决方案