我有一个基本的问候语程序,应该根据用户的输入提出响应。我试图用for循环来完成它;但是,每当用户回复"坏"或者"你"存储在不同数组中的值,控制台多次打印出相同的响应。怎么会遇到这个问题? 我在这里是一个菜鸟,在java中。 如果以前已经回答过这个答案我很抱歉。我搜索但无法找到。 谢谢你的时间。
import java.util.Scanner;
public class Greeter {
public static void main(String[] args) {
String[] greetings = { "well", "good", "great", "awesome", "fabulous" };
String[] bad_greetings = { "bad", "awful" };
String[] responses = { "you", "yourself" };
System.out.println("Hello there, how are you?");
String response;
Scanner scan = new Scanner(System.in);
response = scan.nextLine();
for (String greeting : greetings) {
if (response.contains(greeting)) {
System.out.println("Well, good for you!");
}
for (String b_greet : bad_greetings) {
if (response.contains(b_greet)) {
System.out.println("At least you have me.");
}
}
for (String reply : responses) {
if (response.contains(reply)) {
System.out.println("I'm well, thank you.");
// } else {
// System.out.println("Let's move on then.");
// }
}
}
}
}
}
答案 0 :(得分:0)
改变主要()。你的问题是你有第一个循环的错误}我建议你打破循环(或者代替break
使用函数中的return;
)因为如果你已经找到你的话就不需要运行所有循环答案。
public static void main(String[] args) {
String[] greetings = {"well", "good", "great", "awesome", "fabulous"};
String[] bad_greetings = {"bad", "awful"};
String[] responses = {"you", "yourself"};
System.out.println("Hello there, how are you?");
String response;
Scanner scan = new Scanner(System.in);
response = scan.nextLine();
for (String greeting : greetings) {
if (response.contains(greeting)) {
System.out.println("Well, good for you!");
break;//return;
}
}
for (String b_greet : bad_greetings) {
if (response.contains(b_greet)) {
System.out.println("At least you have me.");
break;//return;
}
}
for (String reply : responses) {
if (response.contains(reply)) {
System.out.println("I'm well, thank you.");
break;//return;
// } else {
// System.out.println("Let's move on then.");
// }
}
}
}
答案 1 :(得分:0)
挤奶女工的回答是正确的。要进一步详细说明他的回答是你要打印你的回复5次(你的“问候”数组中每个项目一个)。
我可以想出三个解决问题的方法:
选项3将是最干净的:)你可以动态转换它或者只是从一个列表开始。好像你的程序可以从列表开始。
答案 2 :(得分:0)
您可以尝试以下
public static void main(String[] args) {
String[] greetings = {"well", "good", "great", "awesome", "fabulous"};
String[] bad_greetings = {"bad", "awful"};
String[] responses = {"you", "yourself"};
System.out.println("Hello there, how are you?");
String response;
Scanner scan = new Scanner(System.in);
response = scan.nextLine();
if(Arrays.asList(greetings).contains(response)){
System.out.println("Well, good for you!");
break;//return;
}
if(Arrays.asList(bad_greetings).contains(response)){
System.out.println("At least you have me.");
break;//return;
}
if(Arrays.asList(responses).contains(response)){
System.out.println("I'm well, thank you.");
break;//return;
}
// } else {
// System.out.println("Let's move on then.");
// }
}