爪哇 - 如何阅读用空格分隔的整数到一个数组 [英] Java - How to read integers seperated by a space into an array

查看:118
本文介绍了爪哇 - 如何阅读用空格分隔的整数到一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的项目遇到麻烦,因为我不能得到正确的开始,这是读取一行从用户空间分隔的整数和值放入数组中。

I am having trouble with my project because I can't get the beginning correct, which is to read a line of integers separated by a space from the user and place the values into an array.

    System.out.println("Enter the elements seperated by spaces: ");
    String input = sc.next();
    StringTokenizer strToken = new StringTokenizer(input);
    int count = strToken.countTokens();
    //Reads in the numbers to the array
    System.out.println("Count: " + count);
    int[] arr = new int[count];

    for(int x = 0;x < count;x++){
        arr[x] = Integer.parseInt((String)strToken.nextElement());
    }

这是我有什么,它似乎只因为当计数初始化,将其设置为1由于某种原因读取数组中的第一个元素。

This is what I have, and it only seems to read the first element in the array because when count is initialized, it is set to 1 for some reason.

谁能帮我?它会更好做这种不同的方式?

Can anyone help me? Would it be better to do this a different way?

推荐答案

有必要让你的code的工作只是一个微小的改变。在错误的是在这一行:

There is only a tiny change necessary to make your code work. The error is in this line:

String input = sc.next();

作为的问题在我的评论中指出,它只能读取的下一个标记。请参阅<一个href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next%28\">documentation.

如果你把它替换为

String input = sc.nextLine();

它会做你想要它做的事情,因为<一href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine%28%29\"><$c$c>nextLine()消耗输入的整条生产线。

it will do what you want it to do, because nextLine() consumes the whole line of input.

这篇关于爪哇 - 如何阅读用空格分隔的整数到一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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