【问题标题】:Trying to break up a string into list试图将字符串分解为列表
【发布时间】:2016-01-30 04:12:30
【问题描述】:

我正在尝试将字符串转换为列表。我通过用户输入获取字符串,但是每当我运行我的代码时,它都会给我这个:

输入一个数字:java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match valid=false][need input=false][source closed=false][skipped=false] [组分隔符=\,][小数分隔符=.][正前缀=][负前缀=\Q-\E][正后缀=][负后缀=][NaN字符串=\Q�\E][无穷大字符串=\Q∞\E]

这是我的代码

public class ch3_15 {
  public static void main(String[] args) {

    int compNum, user_hund, user_ten, user_one, comp_hund, comp_ten, comp_one;
    String s;

    //user input
    System.out.print("Enter a number: ");
    Scanner input1 = new Scanner(System.in);
    s = input1.toString();

    //generating random number
    compNum = (int) Math.random() * 1000;

    System.out.println(s);

    //finding the hundreds, tens, and ones place of the user number
    List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));       

  }
}

【问题讨论】:

  • 它给出了什么错误?

标签: java arrays


【解决方案1】:

这不是错误。这是您使用后的预期行为

Scanner input1 = new Scanner(System.in);
s = input1.toString();
...
System.out.println(s);

toString() 返回表示调用此方法的对象的字符串(在本例中为 Scanner 实例)。

如果您想使用该扫描仪从用户那里读取行,您应该编写

s = input1.nextLine();
//         ^^^^^^^^

【讨论】:

    【解决方案2】:

    您的问题是您没有从控制台读取下一个字符串,而是将扫描仪转换为字符串,然后打印。 你要使用的是Scanner.nextLine(),而不是toString()

    另外,这不是运行时错误,而只是错误的输出。

    【讨论】:

      【解决方案3】:

      您应该使用scanner.nextLine() 来阅读使用输入的下一行。 您当前的代码正在打印扫描仪对象的 toString() 方法,这不是运行时错误,而是预期的行为。

      //user input
      System.out.print("Enter a number: ");
      Scanner input1 = new Scanner(System.in);
      s = input1.nextLine();
      

      【讨论】:

        【解决方案4】:

        你没有从你当前的路线前进;在这种情况下使用的方法是 Scanner 类中的 nextLine();所以代码会是这样的:

        System.out.print("Enter a number: ");
        Scanner input1 = new Scanner(System.in);
        s = input1.nextLine();
        String aux = s.toString(); // To return the string representation from the sc
        

        nextLine() 来自 Java API 7 的方法 => 此方法返回当前行的其余部分,不包括末尾的任何行分隔符。位置设置为下一行的开头。**/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-04-09
          • 2015-11-01
          • 1970-01-01
          • 1970-01-01
          • 2019-04-16
          • 2021-09-29
          • 2012-04-07
          • 1970-01-01
          相关资源
          最近更新 更多