gpt4 book ai didi

java :loop user inputs individually

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

我有一个程序,它告诉用户输入三个int并将每个整数转换为字符串。 即 1 = 1 ; ...等等。这里的问题是为每个用户输入定义int。我怎样才能只用一个输入来获取它并循环它以获取另一个输入,考虑到单独的输入,这样我们就可以在下面的每个短语中单独使用它。

public static void main(String[] args) {

String[] i = { "zero" , "one" , "two" , "three" , "four" ,
"five", "six", "seven" , "eight" , "nine" , "ten" };

Scanner in = new Scanner(System.in);

System.out.println("I have ..... Networking books, ..... Database books, and ..... Programming books. ");

String text = "" , text1 = "", text2 = "" ;
// loop i/p and using it in every phrase seperatellty

for (int a = 1; a <= 1; a++) {
int word = in.nextInt();
int word1 = in.nextInt();
int word2 = in.nextInt();

text = i[word];
text1 = i[word1];
text2 = i[word2];
}

System.out.println("I have " + text + " Networking books, "
+ text1 + " Database books, and "
+ text2 +" Programming books. ");

}}

最佳答案

也许这就是你想要做的

注意:

您错过了输入号码的范围检查。如果您尝试访问索引大于 10 的数组 i,这将抛出 ArrayIndexOutOfBoundException

import java.util.*;
class UserInputReader {

private static final int EXPECTED_NUM_COUNT = 3;

public static void main(String[] args) {
String [] i = { "zero" , "one" , "two" , "three" , "four" ,
"five", "six", "seven" , "eight" , "nine" , "ten" };

Scanner in = new Scanner (System.in);
String[] words = new String[EXPECTED_NUM_COUNT];

int numCount = 0;
while(numCount < 3) {
System.out.println("Enter the number");
int num = in.nextInt();
if (num >= 0 && num <= 10) {
words[numCount] = i[num];
numCount++;
} else {
System.out.println("Enter no is invalid. Try again entering a number between 0 - 10");
}
}

System.out.println("Entered nums " + Arrays.toString(words));

}
}

关于java :loop user inputs individually,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31530000/

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