java:单独循环用户输入

时间:2015-07-21 03:45:48

标签: java

我有一个程序告诉用户输入三个ints并将每个转换成一个字符串。 I.e 1 = 1; ...等。这里的问题是为每个用户输入定义ints。我如何只使用一个输入来获取它并将其循环以获取另一个输入,考虑分离输入,以便我们可以在此处的每个短语中单独使用它。

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. ");

}} 

1 个答案:

答案 0 :(得分:2)

也许这就是你想要做的事情

注意:

您错过了输入号码的范围检查。如果您尝试访问数组ArrayIndexOutOfBoundException以获取超过10的索引

,则会抛出i
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));

    }
}