从用户获取字符串数组长度。但为什么跳过将第一个单词作为输入?

时间:2018-05-16 07:35:11

标签: java

在第一个循环中,它没有将第一个单词作为输入。当我没有从用户那里输入字符串长度时,它工作正常。查看未输入单词0的输出。

public class Stringinput {
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            System.out.println("How many words do you need to make the sentence: ");
            int n = in.nextInt();
            String[] names = new String[n];

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

                System.out.printf("Enter word no %d : ",i);
                names[i]= in.nextLine();
            }
            System.out.println("The sentence you made is: ");
            for (int i = 0; i < names.length; i++) {
                System.out.print(names[i]+" ");

            }
            System.out.println("");
        }
    }

这就是输出:

How many words do you need to make the sentence: 
4
Enter word no 0 : Enter word no 1 : My
Enter word no 2 : name
Enter word no 3 : is
The sentence you made is: 
 My name is 

建立成功(总时间:11秒)

3 个答案:

答案 0 :(得分:0)

使用.next()代替.nextLine(),因为Scanner.nextInt方法不使用上一个换行符字符,因此您只需要一个单词,而不是句子。

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

            System.out.printf("Enter word no %d : ",i);
            names[i]= in.next();
        }

输出:

How many words do you need to make the sentence: 
4
Enter word no 0 : my
Enter word no 1 : next
Enter word no 2 : r
Enter word no 3 : t
The sentence you made is: 
my next r t 

答案 1 :(得分:0)

nextInt()不会消耗在该号码后输入的换行符号,因此您的第一个nextLine()会这样,所以您需要这样做

public class Stringinput {
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            System.out.println("How many words do you need to make the sentence: ");
            int n = in.nextInt();
            in.nextLine(); // consume leftover new line here
            String[] names = new String[n];

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

                System.out.printf("Enter word no %d : ",i);
                names[i]= in.nextLine();
            }
            System.out.println("The sentence you made is: ");
            for (int i = 0; i < names.length; i++) {
                System.out.print(names[i]+" ");

            }
            System.out.println("");
        }
    }

答案 2 :(得分:0)

Scanner.nextInt()方法不使用输入的换行符,因此它转到下一个Scanner.nextLine。如果在next()方法

之后使用nextline,则类似

只需在循环前添加一个虚拟scanner.nextLine()并继续。