为什么Java只跳过if语句?
这将显示“请输入您的姓名>>”,但无论我在那里输入什么,即使它是空的,它总是询问您是否希望启用亵渎过滤器。 它只是跳过了if循环,直到你真正输入一个名字,我不明白为什么为什么Java只跳过if语句?,java,Java,这将显示“请输入您的姓名>>”,但无论我在那里输入什么,即使它是空的,它总是询问您是否希望启用亵渎过滤器。 它只是跳过了if循环,直到你真正输入一个名字,我不明白为什么 另外,我知道我没有在标题中问这个问题,但我也不知道最终语句如何循环回“response=input.nextLine();”当有人没有输入“yes”或“no”时。如果你想让它永远循环,那么你需要使用while循环而不是If,例如: import java.util.Scanner; public class Box {
另外,我知道我没有在标题中问这个问题,但我也不知道最终语句如何循环回“response=input.nextLine();”当有人没有输入“yes”或“no”时。如果你想让它永远循环,那么你需要使用
while
循环而不是If
,例如:
import java.util.Scanner;
public class Box
{
public static void main(String[] args)
{
String empty = "";
String yes = "yes";
String no = "no";
String response;
String name;
Scanner input = new Scanner(System.in);
System.out.print("Please enter your name >>");
name = input.nextLine();
if(name.equals(empty))
{
System.out.println("You did not enter a name, please try again >>");
name = input.nextLine();
}
System.out.println("Would you like the profanity filter turned on?");
response = input.nextLine();
response = response.toLowerCase();
if(response.equals(yes) || response.equals(no))
{
if(response.equals(yes))
System.out.print("Profanity filter will be turned on.");
else
System.out.print("Profanity filter will not be turned on.");
}
else
System.out.print("Invalid response, please try again.");
}
}
这将一直要求用户输入名称,直到他输入一个非空的字符串System.out.println(“您想打开亵渎过滤器吗?”)代码>不在某些文件中,如果是的,无论你做什么,你都会得到它。也许你需要一些while循环来检查名字
Scanner input = new Scanner(System.in);
System.out.print("Please enter your name >>");
String name = input.nextLine();
while(name.isEmpty()){
System.out.println("You did not enter a name, please try again >>");
name = input.nextLine();
}