【问题标题】:User input to populate an array one value at a time JAVA用户输入以一次填充一个值 JAVA
【发布时间】:2013-09-10 05:47:12
【问题描述】:

我试图弄清楚如何从用户那里获取输入并将其存储到数组中。我不能使用arrayList(简单的方法哈哈),而是使用标准的array[5]。我在这里和谷歌上看过,由于问题和回复的数量庞大,我还没有找到一个好的答案。使用扫描仪获取输入不是问题。将输入存储在数组中不是问题。我遇到的问题是我需要一次存储一个输入。

目前我正在使用 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]+" ");

我一直在搞乱它,但如果我删除第一个 for 循环,我不确定在 array[] 括号中放入什么。 BlueJ 只是说“array[] 不是语句”

如何一次只接受一个值并让用户确定他们是否要执行下一个?

这是一个家庭作业,但家庭作业是关于创建一个带有字符串命令的控制台,这是我需要理解的概念才能完成项目的其余部分,它工作正常。

【问题讨论】:

  • 您可以要求用户输入一个分隔符,例如 input1,input2..N,然后您可以通过拆分它们将其存储到一个数组中。?
  • 将输入作为带有值空格分隔符的字符串,然后根据空格分割字符串并获取字符串数组中的值....之后将其转换为 int 数组。这样,您将在一个字符串中获取所有输入,从而消除您的一个循环
  • 参考您在Ruchira的帖子中的评论,您的老师要求您编写一个程序来实现堆栈的工作概念。互联网上有很多可用的程序。如果您需要对代码进行任何说明,请尝试并来到这里。因为这里不可能写完整的代码。

标签: java arrays input


【解决方案1】:
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;

    }

【讨论】:

    【解决方案2】:

    将此作为参考实现。关于如何设计简单控制台程序的一般指示。我目前正在使用 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
        }
    }
    

    样本运行

    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
    

    (说实话:我越来越无聊了。所以,我写了它,并认为不妨把它贴出来。)

    【讨论】:

    • 我让我的所有工作都被问到,但它说按照你的方式做,其中“添加 n”是命令而不是“添加”,然后像我的那样提示输入一个数字。另外,我的将整个数组打印在 { 1, 2, 3, 4, 5 } 或 { 1, 0, 0, 0, 0 } 这样的列表中,所以我有时间尝试不显示“空”或 0价值观。我必须重写我的接收命令的方式才能以这种方式工作,而且我不相信我完全理解你的一切来自哪里。如果你能分解正在发生的事情,那么我可以从中吸取教训,那太棒了
    • @user2727178 我在代码中添加了内联 cmets,以便您更好地理解流程。我相信添加应该支持仅“添加”然后提示用户输入数字或直接“添加 n”以将“n”添加到列表中。处理“添加 n”以提示输入数字不是很直观(在我看来),但可以随意实现任何您喜欢的方式。
    【解决方案3】:

    这样怎么样?

       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++;
       }
    

    【讨论】:

    • 我需要能够删除用另一个命令添加的最后一个。这种方式看起来仍然会一次要求所有输入
    猜你喜欢
    • 1970-01-01
    • 2020-03-26
    • 2022-10-12
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 2017-03-22
    相关资源
    最近更新 更多