【问题标题】:Splitting string of integers and then put the numbers onto a int array Java拆分整数字符串,然后将数字放入 int 数组 Java
【发布时间】:2014-11-16 17:46:42
【问题描述】:

好的,所以我将一个数字列表作为字符串作为输入,我想用这些数字创建一个 int 数组。

import java.util.Scanner;



public class StringSplit
{
public static void main(String[] args)
{
int a;
int i = 0;

String s;

Scanner input = new Scanner(System.in);



System.out.println("This programs simulates a queue of customers at registers.");   
System.out.println("Enter the number of registers you want to simulate:"); 
a = input.nextInt();


while(a==0 || a <0){
System.out.println("0 registers or no registers is invalid. Enter again: ");   
a = input.nextInt();
}


 System.out.println("Enter how many customers enter per second.For example: 0 0 1 1 2 2 2 3 3.            
 Enter: ");     
  s = input.next();    
  String[] parts = s.split(" ");      
  System.out.println(parts[1]);       

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

  input.close();



}

}

如果我可以打印创建的整个数组,一切都会很棒,但由于某种原因,我得到了这个:

 Input:
 0 0 1 1 2 2 
 Output:
 0

就是这样。仅打印数组的第一个元素。我是否应该尝试手动打印和元素,例如部件 [1](就像我所做的那样,我得到了这个:

  Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
  at QueueSimulation.main(QueueSimulation.java:32)

为什么会这样?更重要的是我该如何解决?

【问题讨论】:

    标签: java arrays string split


    【解决方案1】:

    如果要读取一行,请使用:

    s = input.nextLine();  
    

    next() 返回值直到第一个空格。

    阅读更多here

    【讨论】:

    • 我应该这样做并且程序在 nextLine 出现后结束。我在更改为下一个之前使用它,所以至少程序不会停止......
    • @AggelosSfakianos 在您的代码中添加终止条件,例如如果用户类型退出,您将停止您的程序(意味着不要处理让 main 方法完成)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    相关资源
    最近更新 更多