gpt4 book ai didi

java - 从循环中获取数组元素

转载 作者:行者123 更新时间:2023-12-01 07:54:13 25 4
gpt4 key购买 nike

我试图从数组中获取一个元素并稍后在我的代码中使用它,但我的代码中有一些逻辑错误。我希望用户输入他或她需要清洁的日期,然后打印出清洁的日期。这是代码:

import java.util.Scanner;

public class arrayLoopTest {

public static void main(String[] args) {
Scanner scr = new Scanner(System.in);
String[] days = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };

int i = 0;
while (true) {
System.out.println("On what day should the cleaning be scheduled ? ");
String schedule = scr.nextLine();

for (i = 0; i < days.length; i++) {

if (days[i].equals(schedule)) {

System.out.println("Cleaning scheduled for " + schedule);

} else {
System.out.println("Invalid, You have to choose one of these days: \n " + days[i]);
}
}

}
}
}

控制台输出

On what day should the cleaning be scheduled ? 
Thursday
Invalid, You have to choose one of these days:
Monday
Invalid, You have to choose one of these days:
Tuesday
Invalid, You have to choose one of these days:
Wednesday
Cleaning scheduled for Thursday
Invalid, You have to choose one of these days:
Friday
Invalid, You have to choose one of these days:
Saturday
Invalid, You have to choose one of these days:
Sunday
On what day should the cleaning be scheduled ?

最佳答案

一个非常简单的方法是添加另一个变量:

String savedVar = ""; 
....
if (days[i].equals(schedule)) {
savedVar = schedule; //save your user input here
System.out.println("Cleaning scheduled for " + schedule);

} else {
System.out.println("Invalid, You have to choose one of these days: \n " + days[i]);
}

然后稍后在代码中使用savedVar。

关于java - 从循环中获取数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32363992/

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