1
import java.util.Arrays;
import java.util.Scanner;

public class Sort {

    public static void main(String[] args) {
        String temp = "";
        String a ="";

        String[] New;

        Scanner keyboard = new Scanner(System.in);
        //String s1 = new String(keyboard.nextLine());

        System.out.println("Please write your elements.");

        while(keyboard.hasNext()){          
            String currentString = keyboard.next();
            if(currentString.equals(" ")){
                System.out.println("Bye");
            }
            a += (currentString.charAt(0) + "").toUpperCase() + currentString.substring(1).toLowerCase()+",";
        }
        a = a.substring(0, a.length()-1);

        New = a.split(",");
        System.out.println("Your elements are" + Arrays.toString(New) + ".");

        for (int x = 1; x < New.length; x++) {
            for (int y = 0; y < New.length - x; y++) {
                if (New[y].compareTo(New[y + 1]) > 0) {
                    temp = New[y];
                    New[y] = New[y + 1];
                    New[y + 1] = temp;

                }
            }

        } for(int i=0;i<New.length;i++){
            System.out.println(New[i]);
        }
        /*System.out.println("In alphabethical order form is:");
        System.out.println(Arrays.toString(New));*/

    }
}

hasnext in infinite loop ı have already search stackowerflow but answers cant fix the error.please help me.Here my codesPlease write your elements.

ıf ı press space and enter ı have a problem .

Bye Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.String.substring(Unknown Source) at aa.Sort.main(Sort.java:38)

BerkE
  • 21
  • 2
  • You should check the answers given here . Specially the one given by @niiraj874u. – Rossina DiFuoco Feb 17 '16 at 19:20
  • java.util.Scanner[delimiters=\p{javaWhitespace}+][position=17][match valid=true][need input=false][source closed=false][skipped=false][group separator=\.][decimal separator=\,][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q?\E][infinity string=\Q?\E] what is this ? – BerkE Feb 17 '16 at 19:28
  • this codes output are:banana apple -->banana apple so loop never ends – BerkE Feb 17 '16 at 19:38

2 Answers2

1

Couple of things. You should use hasNextLine() and nextLine() instead of hasNext() and next().

After changing that, your while loop never ends, because you just print Bye and continue looping. Add a break statement after you print Bye.

if(currentString.equals(" ")){
    System.out.println("Bye");
    break;
}
jheimbouch
  • 929
  • 8
  • 19
0

Reading from console is different from reading file. Reading from Console the program expects a Stream and it will wait for further Input.

When testing from file (still with System.in for the Scanner, using Java Program ) the hasNext() will return false at the end of the file as no further Input can be done.