0

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.

Currently I was using a for loop to gather information but it wants to gather the entire array at once.

    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"

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.

3
  • You can ask the user to input with a separator like input1,input2..N and after that you can store it into an array by splitting them.? Commented Sep 10, 2013 at 5:51
  • take the input as a string with values space delimiter and then split the string with respect to space and get the values in string array.... convert it to int array after that. This way you will get all the input in a single string hence rem0oving your one loop Commented Sep 10, 2013 at 5:52
  • With reference to your comment in Ruchira's post, Your teacher asked you to write a program to achieve the working concept of stack. There are lot of programs available on the internet. Make a try and come here if you need any clarifications with your code. Because it is not possible to write the whole code here. Commented Sep 10, 2013 at 6:08

3 Answers 3

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;

    }
Sign up to request clarification or add additional context in comments.

Comments

0

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.

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.)

2 Comments

I have mine working for everything that is asked, but it says to do it your way where "add n" is the command not "add" then prompt for a number the way mine does. also, mine prints the entire array in a list like { 1, 2, 3, 4, 5 } or { 1, 0, 0, 0, 0 } so i am having a time trying to not display the "empty" or 0 values. I would have to rewrite the way mine receives its commands for it to work that way, and i don't believe i fully understand where everything is comming from in yours. if you could break down what was happening so i could learn from it that was be fantastic
@user2727178 I've added in-line comments to the code so you can better understand the flow. I believe the addition should support both just "add" to then prompt the user for a number or directly "add n" to add "n" to the list. Processing "add n" to prompt for a number isn't very intuitive (in my opinion) but feel free to implement any way you like.
0

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

1 Comment

i need to be able to delete the last one added with another command. this way looks like it will still ask for all input at once

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.