在 Java 中存储多个值而不使用数组
Storing multiple values in Java without using arrays
接受用户输入 5 次,将它们存储在一个变量中,并在最后显示所有 5 个值。我如何在 Java 中执行此操作?不使用数组、集合或数据库。只有单个变量,如 String
和 int
.
输出应如下所示
https://drive.google.com/file/d/0B1OL94dWwAF4cDVyWG91SVZjRk0/view?pli=1
为什么不使用 Stringbuilder 或 StringBuffer,继续在输入文本后附加一些定界符。
使用简单的字符串对象并将其与用户提供的新值连接起来。
String myString = "";
// while reading from input
myString += providedValue;
public static void main(String[] args) {
String s = "";
Scanner in = new Scanner(System.in);
for(int i=0;i<5;i++){
s += in.nextLine();
}
System.out.println(s);
}
这似乎是徒劳的不必要的练习,但我离题了...
如果你想将它们存储在一个字符串中,你可以这样做:
Scanner in = new Scanner(System.in);
String storageString = "";
while(in.hasNext()){
storageString += in.next() + ";";
}
如果您随后输入 foo bar baz
,storageString 将包含 foo;bar;baz;
。 (in.next()
会把输入的字符串读入空格,in.hasNext()
returns行尾为false)
随着输入的字符串越来越多,它们会附加到 storageString 变量中。要检索字符串,您可以使用 String.split(String regex)
。像这样使用它:
String[] strings = storageString.split(";");
从上面的 storageString 变量中检索到的 strings
数组的值应该是 ["foo", "bar", "baz"]
.
希望对您有所帮助。使用字符串作为存储并不是最佳选择,因为每次将字符串附加到它时,JVM 都会创建一个新对象。要解决此问题,请使用 StringBuilder.
*编辑:我最初说过 strings
数组的值是 ["foo", "bar", "baz", ""]
。这是错误的。 javadoc 声明 'Trailing empty strings are therefore not included in the resulting array'.
接受用户输入 5 次,将它们存储在一个变量中,并在最后显示所有 5 个值。我如何在 Java 中执行此操作?不使用数组、集合或数据库。只有单个变量,如 String
和 int
.
输出应如下所示
https://drive.google.com/file/d/0B1OL94dWwAF4cDVyWG91SVZjRk0/view?pli=1
为什么不使用 Stringbuilder 或 StringBuffer,继续在输入文本后附加一些定界符。
使用简单的字符串对象并将其与用户提供的新值连接起来。
String myString = "";
// while reading from input
myString += providedValue;
public static void main(String[] args) {
String s = "";
Scanner in = new Scanner(System.in);
for(int i=0;i<5;i++){
s += in.nextLine();
}
System.out.println(s);
}
这似乎是徒劳的不必要的练习,但我离题了...
如果你想将它们存储在一个字符串中,你可以这样做:
Scanner in = new Scanner(System.in);
String storageString = "";
while(in.hasNext()){
storageString += in.next() + ";";
}
如果您随后输入 foo bar baz
,storageString 将包含 foo;bar;baz;
。 (in.next()
会把输入的字符串读入空格,in.hasNext()
returns行尾为false)
随着输入的字符串越来越多,它们会附加到 storageString 变量中。要检索字符串,您可以使用 String.split(String regex)
。像这样使用它:
String[] strings = storageString.split(";");
从上面的 storageString 变量中检索到的 strings
数组的值应该是 ["foo", "bar", "baz"]
.
希望对您有所帮助。使用字符串作为存储并不是最佳选择,因为每次将字符串附加到它时,JVM 都会创建一个新对象。要解决此问题,请使用 StringBuilder.
*编辑:我最初说过 strings
数组的值是 ["foo", "bar", "baz", ""]
。这是错误的。 javadoc 声明 'Trailing empty strings are therefore not included in the resulting array'.