This question already has answers here:
What's the difference between next() and nextLine() methods from Scanner class?
                            
                                (14个回答)
                            
                    
                上个月关闭。
        

    

运行以下代码“线程“主”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:0”时出现错误
我想知道next()和nextLine()方法之间的区别。

        //Scanner
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int arr[] = new int[n];
        for(int i=0;i<n;i++){
            arr[i] = sc.nextInt();
        }
        int q=sc.nextInt();
        String str[] = new String[q];
        for(int i=0;i<q;i++)
        {
            str[i] = sc.nextLine();
        }
        sc.next();
        for(int i=0;i<q;i++){
            System.out.println(str[i]);
            if(str[i].charAt(0) == 'I' ){
               String s1[] = str[i].split("\\s+");`enter code here`
               System.out.println(s1[0]);`enter code here`
            int value = Integer.valueOf(s1[1]);
            arr[value]+= 1;
            }
            if(str[i].charAt(0) == 'U'){
                String aa ="aman 2";
                String s2[]= aa.split("\\s+");
                int pos = Integer.valueOf(s2[1]);
                int val = Integer.valueOf(s2[2]);
                arr[pos] = val;
            }
            if(str[i].equalsIgnoreCase("left"))
                {
                    int j = 0;
                    int tmp = arr[0];
                    for(j=0;j<n-1;j++){
                        arr[j]=arr[j+1];
                    }
                    arr[j]=tmp;
                }
            if(str[i].equalsIgnoreCase("right")){
                  int k = 0;
                    int temp = arr[0];
                    for(k=0;k<n-1;k++){
                        arr[k]=arr[k+1];
                    }
                    arr[k]=temp;
            }
            if(str[i].equals('?')){
                String s4[] = str[i].split("\\s+");
                int position = Integer.valueOf(s4[1]);
                System.out.println(arr[position]);
            }
        }

最佳答案

我认为问题在于以下几行:

if(str[i].charAt(0) == 'I' ){


如果str是空字符串,则无法获取第一个字符。您可以使用.isEmpty()测试String是否为空。

Scanner#nextLine()读取(如名称所示)InputStream(在您的情况下为System.in)的下一行。

Scanner#next()可以读取下一行,但也可以读取较少的内容。读取直到到达某些定界符。

您可以配置定界符。默认情况下,它按分隔符(如空格,换行符等)分割。

10-07 19:04
查看更多