Geneticwarrior
Geneticwarrior

Reputation: 47

storing multiple user inputs into an integer array

So here's what i'm trying to do. Have user input numbers, store them in an array, then print all those numbers out on one line. I must use a method/function as well. I think i have done quite well so far, it shows no errors in eclipse. What im stuck on is storing their input into an array. i want them to keep inputting numbers one at a time until they're satisifed and type 'quit'. i just havent read about how to store things in an array despite looking around, particularly storing more than one thing, progressively. here is my code so far, and thank you in advance for any help!

import java.util.Scanner;

public class intarray {

public static void main(String[] args) {
    System.out.println("Enter a number then hit enter. You may then enter another number or end by typing quit.");
    String x;
    Scanner input = new Scanner(System.in);
    while (true)  {
       x=input.next();
       if (x.equalsIgnoreCase("quit")) {break;}
       if (x.equals(null)) throw new Error("You entered nothing. Try again.");
       int stringLength = x.trim().length();
       if (stringLength == 0) throw new Error("Seems you only entered spaces. Try again.");
        isNum(x);
        int goingintoarray = Integer.parseInt(x);



        int array[];

    }
  }

public static String isNum(String t) {


    int user=Integer.parseInt(t);
    String convertback = Integer.toString(user);
    return convertback;
}

}

Upvotes: 2

Views: 3969

Answers (3)

Jarvis.Wu
Jarvis.Wu

Reputation: 1

import java.util.Scanner;

public class intarray {

public static int initSize = 5;

public static void main(String[] args) {
    System.out.println("Enter a number then hit enter. You may then enter another number or end by typing quit.");

    int array[] = new int[initSize];
    int pos = 0;
    int maxSize = initSize; 

    String x = null;
    Scanner input = new Scanner(System.in);

    while (true) {
        x = input.next();

        if (x.equalsIgnoreCase("quit")) {
            break;
        }

        //input empty string, java io can filter. So , x impossible "null" or null.
        //if (x.equals(null))
        //  throw new Error("You entered nothing. Try again.");

        int stringLength = x.trim().length();

        if (stringLength == 0)
            throw new Error("Seems you only entered spaces. Try again.");

        Integer numX = isNum(x);

        // if the array is full, extend it
        if(pos == maxSize){
            int[] newArray = new int[2 * maxSize];
            System.arraycopy(array, 0, newArray, 0, maxSize);
            array = newArray;
            maxSize = array.length;
        }

        if(null == numX) 
            System.out.println(x + " isn't a number."); //choose notify or throw error  
        else
            array[pos++] = numX;

    }

    printArray(array, pos);

}

public static Integer isNum(String t) {
    try {
        return Integer.parseInt(t);
    } catch (NumberFormatException e) {
        return null;
    }
}

public static void printArray(int[] array, int pos) {
    if(null == array || array.length == 0 || pos <= 0)
        return ;
    for(int i = 0 ; i < pos; i++)
        System.out.print(array[i] + " ");
}

}

Upvotes: 0

Mateusz Dymczyk
Mateusz Dymczyk

Reputation: 15141

Since you don't know how many elements there will be an array is a bad idea since you will have to resize it quite often as new elements appear (copying arrays is expensive!) or instantiate a large enough array at the beginning (which is a waste and still doesn't protect you in 100% from having to resize it eventually).

Instead using Java's List (preferably LinkedList) sounds like a good idea since you can add elements dynamically without resizing the data structure.

List<Integer> numbers = new LinkedList<>();
while(true) {
  // something
  numbers.add(goingintoarray);
  // something
}

Be careful of other implementations - for instance ArrayList uses an array (d'uh ;-) ) to store the elements so you would have the same problem but the resizing part would be taken care of for you by the implementation.

@Edit: by convention classes in Java are written using CamelCase starting with an uppercase letter.

Upvotes: 1

Isuru Gunawardana
Isuru Gunawardana

Reputation: 2887

ArrayList<Integer> inputs = new ArrayList<Integer>();    
while (true)  {
      Scanner input = new Scanner(System.in);
      x=input.next();
      if (x.equalsIgnoreCase("quit")) {break;}
      if (x.equals(null)) throw new Error("You entered nothing. Try again.");
      int stringLength = x.trim().length();
      if (stringLength == 0) throw new Error("Seems you only entered spaces. Try again.");

      inputs.add(Integer.parseInt(x));

    }

You don't want the isNum method since it gives same exception here if it gets wrong input for x.

Upvotes: 0

Related Questions