gpt4 book ai didi

java - 确保输入不为空

转载 作者:行者123 更新时间:2023-12-02 00:30:38 25 4
gpt4 key购买 nike

所以下面我有一个问题,我无法理解为什么它不起作用。java 代码的第一 block 完全按照我想要的方式工作(例如,将工资金额设置为任意值,如果不在范围内,则会出现错误并重复最初的问题。)

我的问题是在第二个代码块中,我假设再次创建 boolean 值并模拟上面的代码来检查我的输入是否为==“”,如果没有像以前一样冲洗并重复,但事实并非如此?我写得一模一样(当然改变了值),但我根本无法让 t 发挥作用。如果有人可以帮助或指出我正确的道路,我会很感激:)

//第一 block ......

boolean salaryState = false;
while (salaryState == false){
System.out.print("Salary: ");
salary = (input.nextDouble());
if(salary >= 45000 && salary <= 49999) { //if salary amount in this range
this.coachCategory = "Junior"; //then set coaches category to this
salaryState = true;
}
else if(salary >= 50000 && salary <= 59999) { //if salary amount in this range
this.coachCategory = "Youth"; //then set coaches category to this
salaryState = true;
}
else if(salary >= 60000 && salary <= 70000) { //if salary amount in this range
this.coachCategory = "Senior"; //then set coaches category to this
salaryState = true;
}
else { //if invalid salary amount then print error

if (salary <= 45000 && salary >= 70000);
System.out.println("ERROR: Salary range needs to be within 45 000 - 70 000.");

//第二 block ...

         boolean isName = false;
while (isName == false) {
System.out.print("Name: ");
name = (input.nextLine());
if(name != "") {
this.name = name;
isName = true;
}
else {
if(name == "");
System.out.println("ERROR: Please enter a name.");
}

最佳答案

替换

名称 != ""与 "name.length()>0"

您的解决方案将会起作用。

这是完整的解决方案:

import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
String heroname;
Scanner input = new Scanner(System.in);
System.out.println("Hello World");
String name;
boolean isName = false;
while(isName==false){
System.out.println("Name: ");
name = (input.nextLine());
if(name.length()>0){
heroname = name;
isName = true;
}else{
System.out.println("Try Again");

}
}
}

}

关于java - 确保输入不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58021163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com