0

I was building a program that sorts an array of integers in Java for my college project. The following program compiles perfectly but then the Scanner keeps on running without terminating. I think it happens because of s.next() method being called which sends the cursor to the next line each time input is received. I tried typing EOF to close scanner but it didn't work. Note that no sorting is being carried out as I could not get past accepting input from the user

    import java.util.Scanner;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.LinkedHashSet;
    import java.util.Collections;


    public class SortInt {
    static List<String> arraylist = new ArrayList<String>();
    public static void main (String[] args) {
    int i,n;

    Scanner s = new Scanner(System.in);

    System.out.println("How many elements do you want to sort?");
    n = s.nextInt();

    System.out.println("Enter an ArrayList to sort +n+ numbers");

    for(i=0; i<n; i++){

    while (s.hasNext()) {

        arraylist.add(s.next());
    }  
    }




 System.out.println("Before:");
    System.out.println("ArrayList contains: "+arraylist);

    }

    }
  • What's the for loop needed for? – Submersed Feb 19 '18 at 02:20
  • I am new to coding in Java. The while loop was making Scanner loop indefinitely. I tried typing EOF but the loop didn't terminate. So I added for so that the loop may stop executing after n iterations (it didn't though) – Antariksh Pratham Feb 19 '18 at 10:18

0 Answers0