无法将所有输入都放入 Java 的字符串数组中。

huangapple go评论85阅读模式
英文:

unable to take all the inputs into string array in java

问题

我已经编写了一段代码用于在 Java 中接收字符串输入并存储在字符串数组中我的问题是当我将字符串数组的大小声明为3时它应该将三个字符串放入字符串数组中但它只将两个字符串放入字符串数组中并且不接受第三个字符串有谁可以帮我解决这个问题

**代码**

```java
import java.util.Scanner;
public class leet14 {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int n;
        System.out.println("输入字符串的长度:");
        n=sc.nextInt();
        String a[]=new String[n];
        System.out.println("输入字符串的值:");
        for(int i=0;i<a.length;i++){
            a[i]=sc.nextLine();
        }
        for(int j=0;j<a.length;j++){
            System.out.println(a[j]); 
        }
    }
}

输出

输入字符串的长度:
3
输入字符串的值:
one
two
three
one
two
three

<details>
<summary>英文:</summary>

I have written a code to take string inputs and store in a string array in java. My problem is that when I declare size of string array as 3 it has to take three strings into string array but it only takes two string into the string array and doesn&#39;t accept the third one. Can anyone help me to solve the problem?

**Code**

    import java.util.Scanner;
    public class leet14 {
        public static void main(String[] args) {
            Scanner sc=new Scanner(System.in);
            int n;
            System.out.println(&quot;enter length of string&quot;);
            n=sc.nextInt();
            String a[]=new String[n];
            System.out.println(&quot;enter string values&quot;);
            for(int i=0;i&lt;a.length;i++){
                a[i]=sc.nextLine();
            }
            for(int j=0;j&lt;a.length;j++){
               System.out.println(a[j]); 
            }
            }
    }
**output**

    enter length of string
    3
    enter string values
    one
    two
    
    one
    two



</details>


# 答案1
**得分**: 2

```java
你需要在从控制台开始读取输入字符串之前添加 `sc.nextLine()`。

import java.util.Scanner;
public class leet14 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n;
        System.out.println("输入字符串的长度");
        n = sc.nextInt();
        String a[] = new String[n];
        sc.nextLine();
        System.out.println("输入字符串的值");
        for (int i = 0; i < a.length; i++) {
            a[i] = sc.nextLine();
        }
        for (int j = 0; j < a.length; j++) {
            System.out.println(a[j]);
        }
    }
}

这样将会得到你想要的结果。

输入:

输入字符串的长度
3
输入字符串的值
one
two
three

输出:

one
two
three
英文:

You have to add sc.nextLine() before start reading input string from console.

import java.util.Scanner;
public class leet14 {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int n;
        System.out.println(&quot;enter length of string&quot;);
        n=sc.nextInt();
        String a[]=new String[n];
        sc.nextLine();
        System.out.println(&quot;enter string values&quot;);
        for(int i=0;i&lt;a.length;i++){
            a[i]=sc.nextLine();
        }
        for(int j=0;j&lt;a.length;j++){
           System.out.println(a[j]); 
        }
    }
}

This would give you the desired results.

input:

enter length of string
3
enter string values
one
two
three

output:

one
two
three

答案2

得分: 1

当你读取一个int并且想要读取一个完整的String时,你需要在Scanner内部移动指针到下一行。**附注:**在调试程序时很容易找到这个问题。

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    System.out.print("输入字符串的长度:");
    String[] arr = new String[scan.nextInt()];
    scan.nextLine();    // <-- 移动到下一行,准备读取完整的字符串

    System.out.println("输入字符串值:");

    for (int i = 0; i < arr.length; i++) {
        System.out.format("第 %d 行:", i + 1);
        arr[i] = scan.nextLine();
    }

    for (int j = 0; j < arr.length; j++)
        System.out.println(arr[j]);
}

输出:

输入字符串的长度:3
输入字符串值:
第 1 行:one one
第 2 行:two two
第 3 行:three three
one one
two two
three three
英文:

When you read an int and the want to read a full String, then you have to move a pointer inside Scanner to the next line. P.S. It is easy to find if you debug you program.

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    System.out.print(&quot;enter length of string: &quot;);
    String[] arr = new String[scan.nextInt()];
    scan.nextLine();    // &lt;-- move to the next line to be ready to read a whole string

    System.out.println(&quot;enter string values:&quot;);

    for (int i = 0; i &lt; arr.length; i++) {
        System.out.format(&quot;line %d: &quot;, i + 1);
        arr[i] = scan.nextLine();
    }

    for (int j = 0; j &lt; arr.length; j++)
        System.out.println(arr[j]);
}

Output:

enter length of string: 3
enter string values:
line 1: one one
line 2: two two
line 3: three three
one one
two two
three three

答案3

得分: 1

我建议您查看一下这段代码另外尽量不要使用像 n 这样的变量名这可以真正提高可读性并帮助您找出问题

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int inputCount = 0;
        System.out.println("输入字符串的长度");
        try {
            inputCount = sc.nextInt();
        } catch (Exception e) {
            System.out.println("请输入整数");
            System.exit(1);
        }
        String a[] = new String[inputCount];
        System.out.println("输入字符串值");

        for (int i = 0; i < a.length; i++) {
            a[i] = sc.next();
        }
        for (int j = 0; j < a.length; j++) {
            System.out.println(a[j]);
        }
    }
}
英文:

I would suggest to take a look at this code, also, try not to use value names such as n, it could really improve readability and help you to see the problem.

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
	
    Scanner sc=new Scanner(System.in);
    int inputCount=0;
    System.out.println(&quot;enter length of string&quot;);
    try{
		inputCount=sc.nextInt();
	}catch(Exception  e){
		System.out.println(&quot;int please&quot;);
		System.exit(1);
	}
    String a[]=new String[inputCount];
    System.out.println(&quot;enter string values&quot;);
    
    for(int i=0;i&lt;a.length;i++){
        a[i]=sc.next();
    }
    for(int j=0;j&lt;a.length;j++){
       System.out.println(a[j]); 
    }
  }
}

答案4

得分: 1

要获得您想要的过程,请将 a[i]=sc.nextLine(); 简单更改为 a[i]=sc.next();。除非您的字符串输入中带有空格,否则这应该可以正常工作;否则请在您的 for 循环之前加入 sc.nextLine();

问题出在这里:

nextInt(); 期望并保存输入的第一个单词作为 int,否则将抛出错误,但它不会跳出当前行。

所以当您运行 n=sc.nextInt(); 并输入:

输入字符串的长度
3

3 被保存到 n,但系统光标仍然停留在其后面,像这样:3|

注意:输出流和输入流是不同的,因此运行 System.out.println("输入字符串值:"); 并不会影响输入流的光标位置,即使光标停在了数字 3 后面:

输入字符串的长度
3|
输入字符串值:

a[i]=sc.nextLine(); 期望并保存光标后的句子,否则会换行。但如果光标已经在新行上,它会给您输入新句子的机会(然后在您希望时保存它),然后移动到新行。

因此,由于在光标后没有句子 3|,它会换到下一行,并在 i = 0 时将换行命令 "\n" 赋给 a[0]

现在,光标位于新行上,可以选择输入新句子,当 i = 1 时将其存储到 a[1],然后移动到下一行,当 i = 2 时,执行相同的过程。

然后,String[] a 的内容显示如下:

输入字符串的长度
3|   // 在 nextInt() 之后,当 i=0 时,由于光标不在开头,它会换行,a[0] = "n"
输入字符串值
|one // 当 i=1 时,由于是第一个,它会给予输入的机会,并将其保存到 a[1]
|two  // 当 i=2 时,由于是第一个,它会给予输入的机会,并将其保存到 a[2]
     // a[0] 被显示
one  // a[1] 被显示
two  // a[2] 被显示

我很高兴就这个问题提供我的看法,谢谢您。

英文:

To get your desired process, please simply change a[i]=sc.nextLine(); to a[i]=sc.next(); .Unless your string input has spaces in them, this should work fine, else place sc.nextLine(); before your for loop

this is how I see the problem;

nextInt(); expects and stores the first word of input as int, else an error is thrown, however, it doesn't break out of the current line.

So when you run n=sc.nextInt(); and gave the input

enter length of string
3

3 was saved to n but the system cursor still stays behind it like so, 3|,

N.B: the output stream is different from the input stream, so it doesn't matter that,System.out.println(&quot;enter string values&quot;);is run, the cursor for the input stream still stays behind 3;

enter length of string
3|
enter string values

a[i]=sc.nextLine() expects and stores the sentence after the cursor, else it breaks to the next line. But if the cursor is already on a new line, it gives the chance to enter a new sentence (then stores it if you want) and moves over to a new line.

so as there is no sentence after the cursor 3|, it breaks to the next line and assigns the break line (newline) command &quot;\n&quot; to a[0] in the for loop when i = 0,

so, since the cursor is now on a new line, it gives the option to enter a new sentence and stores it to a[1] when enter is tapped for i = 1 and moves to the next line, the same process is executed for when i = 2

then the contents of String[] a is displayed as follows;

enter length of string
3|   //after, nextInt() when i=0, since the cursor is not the first, it breaks the line, a[0] = &quot;n&quot; 
enter string values
|one //when  i=1, since it&#39;s the firstit gives chance for input, and stores to a[1]
|two  //when  i=1, since it&#39;s the firstit gives chance for input, and stores to a[1]
     //a[0] is displayed
one  //a[1] is displayed
two  //a[2] is displayed

I had fun giving my opinion on this, Thank You.

huangapple
  • 本文由 发表于 2020年9月9日 13:02:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/63805052.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定