[英]How do I have a program create its own variables to match (up to an infinite) amount of user inputs?
[英]How do I have a program create its own variables with Java?
我想首先說,如果這是常識,請原諒我並有耐心。 我對Java有些新意。 我正在嘗試編寫一個程序,它將在一種緩沖區中存儲許多變量值。 我想知道是否有辦法讓程序“創建”自己的變量,並將它們分配給值。 以下是我要避免的示例:
package test;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
int inputCacheNumber = 0;
//Text File:
String userInputCache1 = null;
String userInputCache2 = null;
String userInputCache3 = null;
String userInputCache4 = null;
//Program
while (true) {
Scanner scan = new Scanner(System.in);
System.out.println("User Input: ");
String userInput;
userInput = scan.nextLine();
// This would be in the text file
if (inputCacheNumber == 0) {
userInputCache1 = userInput;
inputCacheNumber++;
System.out.println(userInputCache1);
} else if (inputCacheNumber == 1) {
userInputCache2 = userInput;
inputCacheNumber++;
} else if (inputCacheNumber == 2) {
userInputCache3 = userInput;
inputCacheNumber++;
} else if (inputCacheNumber == 3) {
userInputCache4 = userInput;
inputCacheNumber++;
}
// And so on
}
}
}
所以只是為了總結一下,我想知道程序是否有辦法將無限數量的用戶輸入值設置為String值。 我想知道是否有一種方法可以避免預定義它可能需要的所有變量。 感謝您的閱讀,以及您的耐心和幫助! 〜萊恩
您可以使用Array List
數據結構。
ArrayList類擴展了AbstractList並實現了List接口。 ArrayList支持可根據需要增長的動態數組。
例如:
List<String> userInputCache = new ArrayList<>();
當你想將每個輸入添加到你的數組中時
if (inputCacheNumber == 0) {
userInputCache.add(userInput); // <----- here
inputCacheNumber++;
}
如果要遍歷數組列表,可以執行以下操作:
for (int i = 0; i < userInputCache.size(); i++) {
System.out.println(" your user input is " + userInputCache.get(i));
}
或者你可以使用enhanced for loop
for(String st : userInputCache) {
System.out.println("Your user input is " + st);
}
注意:最好將您的Scanner
放在try catch block with resource
這樣您就不會擔心它是否在最后關閉。
例如:
try(Scanner input = new Scanner(System.in)) {
/*
**whatever code you have you put here**
Good point for MadProgrammer:
Just beware of it, that's all. A lot of people have multiple stages in their
programs which may require them to create a new Scanner AFTER the try-block
*/
} catch(Exception e) {
}
有關ArrayList的更多信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.