如何在 Java 中为字符串变量编写“if”语句?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4976782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 08:54:13  来源:igfitidea点击:

How can I write an "if" statement for a string variable in Java?

javastring

提问by g3n3rallyl0st

This is what I have so far and I have the problem written as a comment on the line I need help with. Any further suggestions would be welcome too. I just need it to end the program when the user enters "stop" as the employee name. Thanks in advance.

这就是我到目前为止所拥有的,并且我将问题写在我需要帮助的行上作为评论。任何进一步的建议也将受到欢迎。当用户输入“停止”作为员工姓名时,我只需要它来结束程序。提前致谢。

package payroll_program_2;
import java.util.Scanner;

        public class Main {
            public static void main(String[] args) {

            Scanner input = new Scanner( System.in );
            float hours;                                            
            float rate;                                            
            String name;
            float total_pay;


        System.out.println("Please enter employee name");         
            name = input.next();
                if (stop)               //THIS IS WHAT I NEED HELP WITH. I DO NOT KNOW HOW TO WRITE
                    end program             //IT CORRECTLY, SO I JUST TYPED WHAT I NEED IT TO DO.
                {

                }
        System.out.println("Please enter hourly rate");              
            rate = input.nextFloat();                               
            if (rate <0)                                            
                {                                                     
                    System.out.printf("Pay rate cannot be negative");   

                }
        System.out.println("Please enter hours worked");            
            hours = input.nextFloat();                                
             if (hours <0)
                {
                    System.out.printf("Hours cannot be negative");

                }
        System.out.println("Employee's total pay for this week");   
            total_pay = hours*rate;                                   

        System.out.printf("The total pay for %s is $%.2f\n", name, total_pay);        

}

回答by Sam Dufel

if (name.equals("stop")) {  
  return;  
}