tags:

views:

46

answers:

1

Hi this is my method that will be called if I want to get a number from user. but if the user also enter a right number just the "else" part will be run ,why? please help me tahnsk.

    public static int chooseTheTypeOfSorting() {
    System.out.println("Enter 0 for merge sorting OR enter 1 for bubble sorting");
    int numberFromConsole = 0;
    try {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        String s = br.readLine();
        DecimalFormat df = new DecimalFormat();
        Number n = df.parse(s);
        numberFromConsole = n.intValue();

    } catch (ParseException ex) {
        Logger.getLogger(DoublyLinkedList.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(DoublyLinkedList.class.getName()).log(Level.SEVERE, null, ex);
    }
    return numberFromConsole;
}

and in my main method:

 public static void main(String[] args) {
    int i = 0;
    i = getRandomNumber(10, 10000);
    int p = chooseTheTypeOfSorting();
    DoublyLinkedList list = new DoublyLinkedList();
    for (int j = 0; j < i; j++) {
        list.add(j, getRandomNumber(10, 10000));

        if (p == 0) {
           //do something....
        }
        if (p == 1) {
            //do something.....
        } else {
            System.out.println("write the correct number ");
            chooseTheTypeOfSorting();
        }
+1  A: 

The problem is you're missing an else

    if (p == 0) {
        //do something....
    } else if (p == 1) { // you're missing the else here
        //do something.....
    } else {
        System.out.println("write the correct number ");
        chooseTheTypeOfSorting();
    }

On reading number from console

Use java.util.Scanner

Scanner sc = new Scanner(System.in);
int num = sc.nextInt();

The documentation has more examples.

Note also that you can set the delimiter, and it also has many hasNextXXX methods that you can use to check against InputMismatchException.

See also


Design consideration

You may consider having the helper method filter out "bad" input, so that once you get the type of sorting, it's guaranteed to be valid.

You may also consider using an enum:

enum SortMode {
   BUBBLE_SORT, QUICK_SORT, BOGO_SORT;
}

See also

polygenelubricants
you had an extra `{` after the `else` which shouldn't have been there, I edited it.
Jesper
I have changed it but it is like before: public static int chooseTheTypeOfSorting() { System.out.println("Enter 0 for merge sorting OR enter 1 for bubble sorting"); int numberFromConsole = 0; Scanner sc = new Scanner(System.in); numberFromConsole = sc.nextInt(); return numberFromConsole; }
Johanna
@Johanna: did you add the missing `else` also?
polygenelubricants
Oops ,know I see thanks !!!
Johanna