【问题标题】:While statement ends no matter what the input is [duplicate]无论输入是什么,while语句都会结束[重复]
【发布时间】:2014-05-08 05:16:53
【问题描述】:

下面是我的代码,基本上我希望程序做的是每次按回车键时循环while语句,然后当“q”提交到控制台时,我希望程序结束。我做错了什么?有了这段代码,它只运行一次,如果我改变了

if (moreEmps != "q") break; 

if (moreEmps == "q") break;

那么无论输入什么它都会继续。有人可以引导我朝着正确的方向前进吗?谢谢!

    import java.text.NumberFormat;
    java.util.Scanner;
    /**
    * Input a number of hours and calculate the pay at $10.00 per hour
    * Pay time and one half for any hours over 40.
    */
    public class PayCalc
    {
    public static void main (String[] args)
    {
    // Declare constants to be used in payroll calculation
    final double RATE = 10.00;     // hourly rate
    final int REGULAR_HOURS = 40; // hours paid at regular rate

    double pay = 0.0;
    Scanner input = new Scanner (System.in);

    System.out.println("Employee Payroll Program");
    System.out.println("Press enter to begin.");

    String moreEmps = "";

    while (moreEmps != input.nextLine())
    {
         System.out.print("Enter employee name: ");
         String employee = input.next();
         System.out.print("Enter hours worked:  ");
         int hours = input.nextInt();

         if (hours > REGULAR_HOURS)

            pay = RATE * REGULAR_HOURS + (hours - REGULAR_HOURS) * RATE * 1.5;

         else
            pay = hours * RATE;

         NumberFormat formit = NumberFormat.getCurrencyInstance();
         System.out.println();
         System.out.print("Total Pay for "); 
         System.out.print(employee);
         System.out.println(" : " + formit.format(pay));

         System.out.println("Any more employees?");
         System.out.println("Press enter to input another employee's information, or q to quit.");
         moreEmps = input.next();
         moreEmps.toLowerCase();  

         if (moreEmps != "q") break;
    } 


}
}

【问题讨论】:

  • 您注意到问题似乎出在条件中,这意味着您正在比较字符串。你试过搜索“how Strings in Java should be compared”吗?
  • 谢谢!很抱歉转发,我没有想到他们被比较的方式是问题

标签: java if-statement while-loop java.util.scanner break


【解决方案1】:

您需要比较字符串,使用equals()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-23
    • 2016-07-02
    • 2021-02-26
    • 2019-02-05
    • 1970-01-01
    • 2020-06-03
    相关资源
    最近更新 更多