0

I am writing some pretty basic java code. The idea is to use a loop to write up to 20 numbers into an array. I want to exit the loop when there are no values left. Right now, my code will write to the array, but I cannot get it to exit the loop without entering a non-integer value. I have read some other posts, but they tend to use string methods, which would make my code kind of bulky. I feel like there is a simple solution to this, but I can't seem to figure it out....

import java.util.Scanner;

public class getArray{

   public static void main (String[] args){

   Scanner scnr = new Scanner(System.in);

   int[]newArray = new int[20];
   int newArraySize = 0;   

   while (scnr.hasNextInt()){
      newArray[newArraySize] = scnr.nextInt();
      newArraySize += 1;
      continue;
      }

   for (int i = 0; i < newArraySize; i++){
   System.out.println("The " + i + " input is " + newArray[i]);
   } 
 }
}
4
  • How about adding this? while (scnr.hasNextInt() && newArraySize < 20) Commented Oct 10, 2020 at 21:23
  • Do you need to give input everytime or can you give all the int at one like; 12 19 37 38 16 ? Commented Oct 10, 2020 at 21:44
  • The problem is that it is easy to tell when a file ends, but you have to do something special to end System.in. To let the program know that the input is finished, type a control-d at the beginning of a new line. Then the Scanner#nextLine will return null. Commented Oct 10, 2020 at 22:24
  • @andersen The input can be given all at one time Commented Oct 11, 2020 at 13:09

5 Answers 5

2

And yet another alternative. Allows for single numerical entry or white-space delimited multiple numerical entry, for example:

--> 1
--> 2
--> 10 11 12 13 14 15 16
--> 20
--> 21

Enter nothing to end data entry and view array contents:

Scanner scnr = new Scanner(System.in);
List<Integer> valuesList = new ArrayList<>();
    
System.out.println("Enter all the  Integer values you would like");
System.out.println("stored into your int[] array.  You can enter");
System.out.println("them either singular or multiple values on a");
System.out.println("single line spaced apart with a single white"); 
System.out.println("space. To stop numerical entry and view your");
System.out.println("array contents just enter nothing.");
System.out.println("============================================");
System.out.println();
            
String inputLine = "";
while (inputLine.isEmpty()) {
    System.out.print("Enter a numerical value: --> ");
    inputLine = scnr.nextLine().trim();
    // If nothing is supplied then end the 'data entry' loop.
    if (inputLine.isEmpty()) {
        break;
    }
    //Is it a string line with multiple numerical values?
    if (inputLine.contains(" ") && inputLine.replace(" ", "").matches("\\d+")) {
        String[] values = inputLine.split("\\s+");
        for (String vals : values) {
            valuesList.add(Integer.valueOf(vals));
        }
    }
    //Is it a string line with a single numerical value?
    else if (inputLine.matches("\\d+")) {
        valuesList.add(Integer.valueOf(inputLine));
    }
    // If entry is none of the above...
    else {
        System.err.println("Invalid numerical data supplied (" + inputLine + ")! Try again...");
    }
    inputLine = "";
}
System.out.println("============================================");
System.out.println();
    
// Convert List<Integer> to int[]...
int[] newArray = new int[valuesList.size()];
for (int i=0; i < valuesList.size(); i++) {
    newArray[i] = valuesList.get(i);
}
    
    
// Display the int[] Array
for (int i = 0; i < newArray.length; i++) {
    System.out.println("The " + i + " input is " + newArray[i]);
}
Sign up to request clarification or add additional context in comments.

Comments

2

If I understand correctly, then you want the input of numbers to be limited to the size of the array?

public static void main(String[] args) {

    Scanner scnr = new Scanner(System.in);
    int[] newArray = new int[20];
    int newArraySize = 0;

    while (newArraySize < newArray.length && scnr.hasNextInt()) {
        newArray[newArraySize] = scnr.nextInt();
        newArraySize++;
    }

    for (int i = 0; i < newArraySize; i++) {
        System.out.println("The " + i + " input is " + newArray[i]);
    }
}

Comments

1

Your while loop condition should be as long as newArraySize is less than the actual size. Here is a fix with some modifications:

Scanner scnr = new Scanner(System.in);

int[]newArray = new int[20];
int newArraySize = 0;   

while (newArraySize < newArray.length){
    try {
        newArray[newArraySize] = scnr.nextInt();
        newArraySize++;
    }catch(Exception e){
        scnr.nextLine();
    }
}

for (int i = 0; i < newArraySize; i++){
    System.out.println("The " + i + " input is " + newArray[i]);
} 

1 Comment

That works if I use all 20 spaces. Is there a way I could stop at the end of a line?
0

A solution using Java Stream API:

Scanner sc = new Scanner(System.in);
System.out.println("Input 20 numbers: ");

int[] arr = IntStream.generate(sc::nextInt) // create infinite stream generating values supplied by method `nextInt` of the scanner instance 
                     .limit(20)   // take only 20 values from stream
                     .toArray();  // put them into array

System.out.println(Arrays.toString(arr)); // print array contents at once

Also, there's a utility method Arrays.setAll allowing to set array values via IntUnaryOperator:

int[] arr = new int[20];
Arrays.setAll(arr, (x) -> sc.nextInt());

1 Comment

Not downvoting this; however I would like to offer my opinion: While this might work (haven't tested), I think, just using streams, because they are streams, is not the best way in terms of coding, in general. Fancy and smarty things are cool, sometimes, but the readability here is dead for me.. and going with the vanilla, old-school, basic loop is something I would have preferred over this solution.
0

While loop should have condition for Array Length, kindly try below code which will stop taking inputs after 21st input and array elements will be displayed.

import java.util.Scanner;

public class AarrayScanner {
    public static void main(String args[]) {
        Scanner scnr = new Scanner(System.in);
        int[] newArray = new int[20];
        int newArraySize = 0;
        while (scnr.hasNextInt() && newArraySize < newArray.length) {
            newArray[newArraySize] = scnr.nextInt();
            newArraySize++;
        }

        for (int i = 0; i < newArraySize; i++) {
            System.out.println("The " + i + " input is " + newArray[i]);
        }
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.