gpt4 book ai didi

java - java中的else循环

转载 作者:行者123 更新时间:2023-11-30 06:15:33 25 4
gpt4 key购买 nike

所以我正在制作一个java程序,它会询问用户“你好吗”,如果不满足if和if else语句中的条件,那么它应该循环,但我不知道如何实现循环以使得当用户没有输入两个 if 语句中的任何内容时,它应该重复代码

这是我的代码

import java.util.Scanner;

public class simplechatbot {

private static Scanner scanner;

public static void main(String args[]) {

scanner = new Scanner(System.in);

System.out.print("What is your name");
String greeting = scanner.nextLine();
System.out.print("Hi" + " " + greeting + ", ");

System.out.print("How are you");
String howareyou = scanner.nextLine();

if (howareyou.equalsIgnoreCase("good")) {
System.out.print("Thats good to hear!");
} else if (howareyou.equalsIgnoreCase("not good")) {
System.out.print("Unfortunate");
} else {
/*
this is where I want to put the loop that goes back to asking the user
"how are you" until they say something which matches the criteria
*/
}
}
}

最佳答案

永远使用 while true 循环,除非满足其中一个中断条件:

import java.util.Scanner;

public class SimpleChatBot {

public static void main(String args[]) {
try (Scanner scanner = new Scanner(System.in)) {
while (true) {
System.out.print("What is your name");
String greeting = scanner.nextLine();
System.out.print("Hi" + " " + greeting + ", ");

System.out.print("How are you");
String howareyou = scanner.nextLine();
if (howareyou.equalsIgnoreCase("good")) {
System.out.print("Thats good to hear!");
break;
} else if (howareyou.equalsIgnoreCase("not good")) {
System.out.print("Unfortunate");
break;
}
}
}
}
}

关于java - java中的else循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49287113/

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