0

I am having a hard time trying to get my while loop, to take in my string, and then loop back to he beginning to then accept the second input of the array that is defended above in the code by the user.

package week9assinment;
import java.util.Scanner;

import java.util.Comparator;
import java.util.Scanner;

public class InteractiveStringComparer {
    
    public static void main (String args[]) {
        
        Scanner scan = new Scanner(System.in);
        
        //Implement the scanner to take in the size of the array
        
        int ArrayLenght = 0;
        System.out.println("Enter it the size of the String Array: ");
        ArrayLenght = scan.nextInt();
        System.out.println("You have created a string array with the size of: " +  ArrayLenght);
        //Create a while loop to take in values of Strings from the user, add each string into the array created.
       String stringArray [] = new String [ArrayLenght];
       //System.out.println(stringArray.length);
       
       // add elements via scanner
       int ArrayElements = 0;
       String usersString;
      // System.out.println("Enther string: " +ArrayElements);
       while(ArrayElements < ArrayLenght + 1) {
           System.out.println("Enter a string to add to the array: ");
           usersString = scan.nextLine();
           stringArray[ArrayElements] = usersString;
           //System.out.println(stringArray[ArrayLenght]);
           ArrayElements ++;
           
           
       }
Tusk
  • 7
  • 1
  • 1
    Please look at [Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods](http://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo) – Hovercraft Full Of Eels Mar 06 '22 at 22:56
  • Add `scan.nextLine();` after `ArrayLenght = scan.nextInt();` to get rid of the dangling new line that's left in the `Scanner`s buffer – MadProgrammer Mar 06 '22 at 22:56
  • `while(ArrayElements < ArrayLenght + 1) {` is also going to cause a `ArrayIndexOutOfBoundsException`, use `while(ArrayElements < ArrayLenght) {` instead – MadProgrammer Mar 06 '22 at 22:57

0 Answers0