从空格分隔的整数列表创建一个数组 [英] creating an array from a list of space separated integers

查看:179
本文介绍了从空格分隔的整数列表创建一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个Java程序,可以接受号的列表,每一个空格分开(例如:1 2 3 5 69 3124124等...),然后把这些数字到一个数组中,并检查重复。整个事情工作正常,除了这个方法是给我找麻烦:

I am trying to make a java program which can accept a list of numbers, each separated by a whitespace (Ex: 1 2 3 5 69 3124124 etc...) which then puts these numbers into an array and checks for duplicates. The whole thing works fine except for this method which is giving me trouble:

public static List returnArray(){
System.out.println("type numbers here: ");
    while(sc.hasNextInt()){
        list.add(sc.nextInt());
    }
    return list;

SC是的ArrayList

"sc" is the arraylist

它工作正常,除了程序来了解它的完成是给定的输入对我来说是增加一个字母或东西到最后的唯一途径,所以1 2 3的输入没有做任何事情,但1输入2 3 R结果[1 2 3]。任何想法如何写这个,使其知道要停止服用后输入多个空格,并在年底不会需要一些其他的角色?

It works fine except the only way for the program to understand it's finished being given input is for me to add a letter or something to the end, so an input of 1 2 3 doesn't do anything but an input of 1 2 3 r results in [1 2 3]. Any ideas how to write this so that it will know to stop taking input after more than one blank space and not need some other character at the end?

推荐答案

您可以在一整行扫描(只有一行)首先使用 scan.readLine(),并解析该字符串代替。

You can scan in a whole line (ONLY ONE LINE) first using scan.readLine(), and parse THAT string instead.

基本上,读取一行(字符串),并使用空间(拆分()函数),然后为每个之一,它解析成整数,并将其添加到ArrayList列表分裂它。在结束返回列表。

Basically, read a line (as a string), and split it up using spaces (split(" ") function), then for each one, parse it into an integer and add it to the arraylist list. Return list at the end.

eg:
public static List returnArray() {
    System.out.println("Type numbers here: ");
    String input = sc.readLine();
    String[] x = input.split(" ");
    for (String y : x) {
        Int tempInt = Integer.parseInt(y);
        list.add(tempInt);
    }
    return list;
}

这篇关于从空格分隔的整数列表创建一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆