存储在Java中的多个值,而无需使用数组 [英] Storing multiple values in Java without using arrays
问题描述
5次拿用户的输入,将它们存储在一个变量,并在最后显示所有5个值。我如何在Java中做到这一点?如果不使用数组,集合或数据库。只有像字符串单个变量
和 INT
。
Take user input for 5 times, store them in a variable and display all 5 values in last. How can I do this in Java? Without using arrays, collections or database. Only single variable like String
and int
.
输出应该是这样的。
https://drive.google.com/file/d/ 0B1OL94dWwAF4cDVyWG91SVZjRk0 /看法?PLI = 1
推荐答案
这似乎是一个不必要的无用功,但我离题...
This seems like a needless exercise in futility, but I digress...
如果你想将它们存储在一个单一的字符串,可以做到像这样:
If you want to store them in a single string, you can do it like so:
Scanner in = new Scanner(System.in);
String storageString = "";
while(in.hasNext()){
storageString += in.next() + ";";
}
如果你再输入富酒吧巴兹
storageString将包含 foo的;酒吧;巴兹;
。 ( in.next()
读取输入的字符串的空间,而 in.hasNext()
在返回false该行的末尾)
if you then input foo bar baz
storageString will contain foo;bar;baz;
. (in.next()
will read the input strings to the spaces, and in.hasNext()
returns false at the end of the line)
随着越来越多的字符串被输入时,它们被附加到storageString变量。要检索的字符串,可以使用的 String.split(字符串正则表达式)
。使用这像这样完成的:
As more strings are input, they are appended to the storageString variable. To retrieve the strings, you can use String.split(String regex)
. Using this is done like so:
String[] strings = storageString.split(";");
在字符串
此处检索从storageString变量上面应该有值数组 [富,酒吧,巴兹 ]
。
the strings
array which is retrieved here from the storageString variable above should have the value ["foo", "bar", "baz"]
.
我希望这有助于。使用字符串作为存储,因为JVM创建一个新的对象,每一个字符串追加到它的时间不是最佳的。为了解决这个问题,使用的StringBuilder 。
I hope this helps. Using a string as storage is not optimal because JVM creates a new object every time a string is appended onto it. To get around this, use StringBuilder.
*编辑:我原本说的字符串值
阵列将 [富,酒吧,巴兹 ]
。这是错误的。 javadoc的国家,因此尾随空字符串不包含所得数组中。
* I originally had said the value of the strings
array would be ["foo", "bar", "baz", ""]
. This is wrong. The javadoc states 'Trailing empty strings are therefore not included in the resulting array'.
这篇关于存储在Java中的多个值,而无需使用数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!