用户输入以一次一个值填充数组 JAVA
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18711496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
User input to populate an array one value at a time JAVA
提问by user2727178
I am trying to figure out how to take input from a user and store it into an array. I cannot use an arrayList
(the easy way lol) but rather a standard array[5]
. I have looked on here and on google and because of the sheer amount of questions and responses I have yet to find a good answer. Using scanner to get input is not a problem. Storing the input in an array is not the problem. What i am having trouble with is that I need to store one input at a time.
我想弄清楚如何从用户那里获取输入并将其存储到数组中。我不能使用arrayList
(简单的方法,哈哈),而是使用标准的array[5]
. 我在这里和谷歌上都看过,由于问题和回复的数量太多,我还没有找到一个好的答案。使用扫描仪获取输入不是问题。将输入存储在数组中不是问题。我遇到的问题是我需要一次存储一个输入。
Currently I was using a for loop to gather information but it wants to gather the entire array at once.
目前我正在使用 for 循环来收集信息,但它想一次收集整个数组。
for (int i=0;i<5;i++)
array[i] = input.nextInt();
for (int i=0;i<array.length;i++)
System.out.println(array[i]+" ");
I have been messing around with it, but if i remove the first for loop, im not sure what to put in the array[] brackets. BlueJ just says that "array[] is not a statement"
我一直在弄乱它,但是如果我删除第一个 for 循环,我不确定在 array[] 括号中放什么。BlueJ 只是说“array[] 不是声明”
How can I accept just one value at a time and let the user determine if they want to do the next?
如何一次只接受一个值并让用户决定是否要执行下一个值?
This is for a homework assignment, but the homework assignment is about creating a console with commands of strings and this is a concept that i need to understand to complete the rest of the project which is working fine.
这是一个家庭作业,但家庭作业是关于创建一个带有字符串命令的控制台,这是我需要理解的概念才能完成项目的其余部分,该项目工作正常。
采纳答案by Ravi Thapliyal
Use this as a reference implementation. General pointers on how a simple console program can be designed. I'm using JDK 6 at the moment. If you're on JDK 7 you can use switch case
with strings instead of the if-else
.
将此用作参考实现。关于如何设计简单控制台程序的一般指示。我目前正在使用 JDK 6。如果您使用的是 JDK 7,则可以使用switch case
字符串而不是if-else
.
public class Stack {
int[] stack; // holds our list
int MAX_SIZE, size; /* size helps us print the current list avoiding to
print zer0es & the ints deleted from the list */
public Stack(int i) {
MAX_SIZE = i; // max size makes the length configurable
stack = new int[MAX_SIZE]; // intialize the list with zer0es
}
public static void main(String[] args) throws IOException {
new Stack(2).run(); // list of max length 2
}
private void run() {
Scanner scanner = new Scanner(System.in);
// enter an infinite loop
while (true) {
showMenu(); // show the menu/prompt after every operation
// scan user response; expect a 2nd parameter after a space " "
String[] resp = scanner.nextLine().split(" "); // like "add <n>"
// split the response so that resp[0] = add|list|delete|exit etc.
System.out.println(); // and resp[1] = <n> if provided
// process "add <n>"; check that "<n>" is provided
if ("add".equals(resp[0]) && resp.length == 2) {
if (size >= MAX_SIZE) { // if the list is full
System.out.print("Sorry, the list is full! ");
printList(); // print the list
continue; // skip the rest and show menu again
}
// throws exception if not an int; handle it
// if the list is NOT full; save resp[1] = <n>
// as int at "stack[size]" and do "size = size + 1"
stack[size++] = Integer.parseInt(resp[1]);
printList(); // print the list
// process "list"
} else if ("list".equals(resp[0])) {
printList(); // print the list
// process "delete"
} else if ("delete".equals(resp[0])) {
if (size == 0) { // if the list is empty
System.out.println("List is already empty!\n");
continue; // skip the rest and show menu again
}
// if the list is NOT empty just reduce the
size--; // size by 1 to delete the last element
printList(); // print the list
// process "exit"
} else if ("exit".equals(resp[0])) {
break; // from the loop; program ends
// if user types anything else
} else {
System.out.println("Invalid command!\n");
}
}
}
private void printList() {
System.out.print("List: {"); // print list prefix
// print only if any ints entered by user
if (size > 0) { // are available i.e. size > 0
int i = 0;
for (; i < size - 1; i++) {
System.out.print(stack[i] + ",");
}
System.out.print(stack[i]);
}
System.out.println("}\n"); // print list suffix
}
private void showMenu() {
System.out.println("Enter one of the following commands:");
// Check String#format() docs for how "%" format specifiers work
System.out.printf(" %-8s: %s\n", "add <n>", "to add n to the list");
System.out.printf(" %-8s: %s\n", "delete", "to delete the last number");
System.out.printf(" %-8s: %s\n", "list", "to list all the numbers");
System.out.printf(" %-8s: %s\n", "exit", "to terminate the program");
System.out.print("$ "); // acts as command prompt
}
}
Sample Run:
样品运行:
Enter one of the following commands:
add <n> : to add n to the list
delete : to delete the last number
list : to list all the numbers
exit : to terminate the program
$ list
List: {}
Enter one of the following commands:
add <n> : to add n to the list
delete : to delete the last number
list : to list all the numbers
exit : to terminate the program
$ add 1
List: {1}
Enter one of the following commands:
add <n> : to add n to the list
delete : to delete the last number
list : to list all the numbers
exit : to terminate the program
$ add 2
List: {1,2}
Enter one of the following commands:
add <n> : to add n to the list
delete : to delete the last number
list : to list all the numbers
exit : to terminate the program
$ add 3
Sorry, the list is full! List: {1,2}
Enter one of the following commands:
add <n> : to add n to the list
delete : to delete the last number
list : to list all the numbers
exit : to terminate the program
$ delete
List: {1}
Enter one of the following commands:
add <n> : to add n to the list
delete : to delete the last number
list : to list all the numbers
exit : to terminate the program
$ delete
List: {}
Enter one of the following commands:
add <n> : to add n to the list
delete : to delete the last number
list : to list all the numbers
exit : to terminate the program
$ delete
List is already empty!
Enter one of the following commands:
add <n> : to add n to the list
delete : to delete the last number
list : to list all the numbers
exit : to terminate the program
$ exit
(Truth be told: I was getting bored. So, I wrote it and thought might as well post it then.)
(说实话:我越来越无聊了。所以,我写了它,并认为最好在那时发布它。)
回答by Ruchira Gayan Ranaweera
How about this way?
这种方式怎么样?
Scanner sc=new Scanner(System.in);
int[] arr=new int[5];
int i=0;
while (i<arr.length){
System.out.println("Enter "+i+" index of array: ");
arr[i]=sc.nextInt();
i++;
}
回答by Ragavan
boolean c = true;
Scanner sc=new Scanner(System.in);
int arr[] = new int[5];
int i =0;
int y = 1;
while(c){
System.out.println("Enter "+i+" index of array: ");
arr[i]=sc.nextInt();
i++;
System.out.println("Want to enter more if yes press 1 or press 2 ");
y = sc.nextInt();
if(y==1)c=true;
else c=false;
}