【问题标题】:Scanner's function .nextLine() wont accept input inside a for loop? [duplicate]扫描仪函数 .nextLine() 不接受 for 循环内的输入? [复制]
【发布时间】:2017-05-22 00:31:18
【问题描述】:

我需要让用户在变量n 中输入数组的大小,然后创建一个字符串的单维数组并用句子填充它。我还需要确保每个句子都以句号结尾(.)。所以这就是我所拥有的:

import java.util.*;
class encryption{
        void main(){
                Scanner sc=new Scanner(System.in);
                System.out.println("Enter the number of sentences to be encrypted");
                int n=sc.nextInt();
                String[] a=new String[n];
                System.out.println("Enter the sentences");

                for(int i=0; i<n; i++){
                    a[i]=sc.nextLine();
                    while(a[i].charAt(a[i].length()-1)!='.'){
                        a[i]=sc.nextLine();                                                
                    }
                    if(i%2==0){
                        a[i]=rev(a[i]);
                    }
                    else{
                        a[i]=frwd(a[i]);
                    }

                }
                for(int i=0; i<n; i++){
                    System.out.println(a[i]);
                }
            }

输入后,我将使用函数rev(...)frwd(...) 处理字符串,然后打印更改后的字符串。

它编译得很好,但是在执行时,第一个 for 循环中的第一行 a[i]=sc.nextLine(); 似乎不起作用。它给了我一个直接的indexOutOfBounds 错误,这意味着它直接进入了while 循环。

我怎样才能让它在那里接受输入?

【问题讨论】:

  • 您可以添加一个额外的sc.nextLine() 来使用最后一个换行符。您可能会发现阅读 this 很有帮助。
  • @HardikModha 解决了它!

标签: java arrays string for-loop while-loop


【解决方案1】:

取变量n中的句子数后, 写这行代码:

int n=sc.nextInt();
sc.nextLine();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多