2015-07-12 106 views
0

当我运行我的代码时,它会正常工作,直到它提出问题“您想要使用哪种操作(sum,subst,multi,div)”。无论用户选择什么,我的程序都没有回应!这个非常简单的代码有什么问题

这是怎么发生的?

import java.util.Scanner; 
import java.io.*; 

public class three3 { 
    public static void main (String[] args) { 
     int x; 
     int y; 
     int opera; 
     String oper; 

     Scanner in = new Scanner (System.in); 
     System.out.println(" write the first number "); 
     x = in.nextInt(); 

     System.out.println(" write the second number "); 
     y = in.nextInt(); 

     System.out.println(" which operation do you want to use from (sum , subst , multi , div)"); 
     oper = in.nextLine(); 

     if (oper == "sum") { 
      opera=x+y; 
      System.out.println(" the sum of two numbers is " + opera); 
     } 

     if (oper == "subst") { 
      opera = x - y; 
      System.out.println(" the subtraction of two numbers is " + opera); 
     } 

     if (oper == "multi") { 
      opera = x * y; 
      System.out.println(" the multi of two numbers is " + opera); 
     } 

     if (oper == "div") { 
      opera = x/y; 
      System.out.println(" the division of two numbers is " + opera); 
     } 
    } 
} 

回答

3

因为没有这些if-clause被执行。 您在比较Strings==这是错误的。改为使用oper.equals("sum")。请参阅this question以供参考。对你的结论是总是使用equalsStrings

+1

这不是正确的答案 – gurghet

+1

@gurghet我错过了胡安的回答中的错误,但是我正在接受的观点仍然是意外行为的一个原因。 – runDOSrun

+0

没有*错误的*回应。有*没有*回复 – gurghet

0

加上其他人的观点,你也应该考虑使用else if{}else{}声明,这样你可以捕获无效输入。

2

您需要在最后一次致电in.nextInt()后立即致电in.nextLine()原因是只要求下一个整数不会消耗输入中的整行,因此您需要跳到下一个换行符在输入中通过调用in.nextLine()

int y = in.nextInt(); 
in.nextLine(); 

这几乎是每一个有你需要调用一个不消耗整条生产线的方法,后得到一个新的行时间来完成,例如,当你调用nextBoolean()

另外如,则不检查与==运算符的字符串是否相等,而是使用.equals()字符串方法。

+0

这是正确的答案 – gurghet

1

问题在于,in.nextLine()消耗了在输入int后单击Enter键时隐式插入的\ n。这意味着该程序不会期望来自用户的任何其他输入。为了解决这个问题,你可以消耗与in.nextLine()新的放线之前,诠释你的实际变量,像这样:

System.out.println(" write the second number "); 
y=in.nextInt(); 

System.out.println(" which operation do you want to use from (sum , subst , multi , div)"); 

in.nextLine(); //New line consuming the \n 

oper=in.nextLine(); 

if(oper.equals("sum")){//replace == by .equals 
    opera=x+y; 
} 

除此之外,和runDOSrun说,你应该从a==ba.equals(b)替换字符串的比较

+0

这也是对的 – gurghet

相关问题