开发者

How to get number from console in java?

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 run, why?

Can you explain?

    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();
      开发者_开发知识库  }


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

  • Java Tutorials - I/O - Scanning and Formatting

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

  • Java Tutorials/Enum
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜