java—我已经使用用户输入指定了数组的大小,但是我的for循环只接受大小为1的输入

z0qdvdin  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(273)

我已经使用用户输入指定了数组的大小,但是我的for循环只接受大小为1的输入。

import java.util.*;
        public class Main{
            public static void main(String args[]){
                Scanner sc = new Scanner(System.in);
                int time=sc.nextInt();
                String input[]=new String[time];
                for(int i=0;i<time;i++) 
                {
                input[i]=sc.nextLine();
                }
                for(int i=0;i<time;i++) 
                {   
                int len=input[i].length();
                if(len>4)
                {
                    System.out.println(input[i].charAt(0)+ Integer.toString(len-2)+input[i].charAt(len-1));
                }
                else
                    System.out.println(input[i]);
            }
        }
        }

我改变了我的代码,它工作得很好

int time=sc.nextInt();

具有

int time=Integer.parseInt(sc.nextLine());

但我不知道这背后的原因。谁能给我解释一下吗

ppcbkaq5

ppcbkaq51#

这个 Scanner.nextInt() 方法将输入的下一个标记扫描为 int ,不是排队。例如,如果你给出一个 int 输入,然后按enter键,则只需 int ,而不是回车。
如果您给出如下示例输入:

2 xyz //hit enter and give the next input
abc

你会看到 nextInt() 将采取 2 作为该行和即将到来的 Scanner.nextLine() 将考虑 xyz 作为第一个输入,在下一次迭代中,正如我们给出的 `` ,它将被视为第二个。所有这些时间,您的代码都在工作,但您无法看到,因为它将空字符串作为第一个输入,这是由于前一行的回车。
但是, Scanner.nextLine() 将整行与回车符一起作为输入,然后将int解析为整数,这样,就可以为数组的字符串输入获取下一行。
希望一切都清楚。

b91juud3

b91juud32#

问题出在 nextLine() 第一部分中使用的方法 for 环因为该方法将扫描器推进到下一行并返回被跳过的输入,所以它有点“吃掉”您的一个循环迭代,并最终允许您输入 time - 1 数组中的元素,而不是 time 元素的数量。如果你只是使用 sc.next() 相反,该程序工作得非常好,因此您不需要使用

int time=Integer.parseInt(sc.nextLine());

因为(在我看来)它可能比仅仅替换更复杂 nextLine() 具有 next() . 代码如下:

import java.util.*;
        public class Main{
            public static void main(String args[]){
                Scanner sc = new Scanner(System.in);
                int time = sc.nextInt();
                String input[] = new String[time];
                for(int i = 0;i < time;i++) 
                {
                   input[i] = sc.next();
                }
                for(int i = 0;i < time;i++) 
                {   
                   int len = input[i].length();
                   if(len > 4)
                   {
                      System.out.println(input[i].charAt(0) + Integer.toString(len - 2) + input[i].charAt(len - 1));
                   }
                   else
                      System.out.println(input[i]);
                }
                sc.close();
            }
        }

相关问题