简体   繁体   中英

User Input Validation Errors (Java)

package javahistogramtwo;

import java.util.Scanner;

public class JavaHistogramTwo {

    public static void main(String[] args) {
        int sum = 0;
        int count = 0;
        int mark = 0;
        int largest = 0, smallest = 0;
        int rangeOne = 0, rangeTwo = 0, rangeThree = 0, rangeFour = 0;

        System.out.println("Enter marks, -1 to finish: ");
        Scanner in = new Scanner(System.in);

// Enter range validation
        {
            {                
                 while (!in.hasNextInt()) {
                    System.out.println("Input not valid");
                    in.next();
                }

                while (mark != -1) {
                    mark = in.nextInt();

                    while (mark <= -2 || mark >= 101){
                    System.out.println("Error: Enter Valid Input Type: "
                                + "Numbers from 0 - 100 for Marks. Or -1 to finish.");
                    in.nextInt();
                }


                    if (mark != -1) {
                        sum = sum + mark;
                        count++;

                        if (count == 1) {
                            largest = mark;
                            smallest = mark;

                        } else {
                            if (mark > largest) {
                                largest = mark;
                            }
                            if (mark < smallest) {
                                smallest = mark;
                            }
                        }
                    }

                    if (mark >= 0 && mark <= 29) {
                        rangeOne++;
                    } else if (mark >= 30 && mark <= 39) {
                        rangeTwo++;
                    } else if (mark >= 40 && mark <= 69) {
                        rangeThree++;
                    } else if (mark >= 70 && mark <= 100) {
                        rangeFour++;
                    }
                }
            }



            System.out.print("0-29: ");
            for (int i = 0; i < rangeOne; i++) {
                System.out.print("*");
            }

            System.out.println();
            System.out.print("30-39: ");
            for (int i = 0; i < rangeTwo; i++) {
                System.out.print("*");
            }

            System.out.println();
            System.out.print("40-69: ");
            for (int i = 0; i < rangeThree; i++) {
                System.out.print("*");
            }

            System.out.println();
            System.out.print("70-100: ");
            for (int i = 0; i < rangeFour; i++) {
                System.out.print("*");
            }

            System.out.println("");
            if (count > 0) {
                System.out.println("Largest mark is: " + largest);
            } else {
                System.out.println("No data");
            }
            if (count > 0) {
                System.out.println("Smallest mark is: " + smallest);
            } else {
                System.out.println("No data");
            }
            if (count > 0) {
                double average = sum / count;
                System.out.println("Average marks: " + average);
            } else {
                System.out.println("No data");
            }

            if (count > 0) {
                System.out.println(rangeOne + rangeTwo + rangeThree + rangeFour
                        + " Total Number of Students");
            } else {
                System.out.println("No data");
            }

            {
//                if (mark >= rangeThree || mark <= rangeFour)
                System.out.println(rangeThree + rangeFour + " Number of Student Passed"
                        + " - (40 Marks or Above)");

//                else {
//            System.out.println("No data"); 
//        }

            }
        }
    }
}

Hello.

I am running into two problems when it comes to my code.

The first being that when integers are entered and then a non-integer is entered, instead of displaying an error and allowing the user to continue, the program will crash. With this, if I enter a non-integer, then integers, it will work, until I enter a second non-integer. Once again, the program crashes in this case.


Example

  • a
  • 101
  • -2
  • a (Crash happens here)

Or

  • 101
  • a (Crash happens here)

The second problem being, that the smallest and largest numbers display correctly. However, I want the highest possible to be 100, if say 102 is entered, the number shouldn't be displayed. However, if I enter 102, the number does display. This is the same for smallest, where the smallest possible number is 0, if say -3 is entered, the number shouldn't display. However, if I enter -3, the number does display.


Example

  • 0 (Want this to display as lowest)
  • 20
  • 30
  • -5 (Will display has lowest)
  • 6
  • 100 (Want this to display as highest)
  • 78
  • 106 (Will display has highest)

  • Lowest is -5 (Want it to be 0)
  • Highest is 106 (Want it to be 100

Help is appreciated.

Thanks. :)

You can avoid such exceptions by carefully handling them. What you can do is put the code or your logic in try block and in the catch block you can do something like:

catch(NumberFormatException nfe) {
   System.out.println("Please enter only numbers");
   in = sc.nextInt();
}

That'd be helpful to handle the alphabets as well in your code.

In your code, you are not assigning mark any value. It should be mark = nextInt(); right after Scanner initialization.

Coming to your problems : 1) Yes, only integers are expected to be fed by the user. If anything other than integers are provided then java.util.InputMismatchException will be throw which you should handle in try{<your code>} catch(InputMismatchException)

block.

2) Code formatting - move all of your business logic which calculates smallest and greatest numbers to a private method.

private void printSmallestAndLargestNumber(int marks)

And avoid using so many if, else conditions. Its difficult to read.

The behavior which you are explaining in problem 2), I am getting worse than that. Please correct your code and make sure that you ran it with the input set you are providing.

For your first problem, just move the first while condition at this position (after the second while condition)

while (mark != -1) {
         while (!in.hasNextInt()) {
                        System.out.println("Input not valid");
                        in.next();
                    }
         mark = in.nextInt();

For the second problem is due to your if condition for largest and smallest value. your code:

if (count == 1) {
                            largest = mark;
                            smallest = mark;

                        } else {
                            if (mark > largest) {
                                largest = mark;
                            }
                            if (mark < smallest) {
                                smallest = mark;
                            }
                        }

In the else section, you must add an if to check if the value is between 0 - 100 and the result is:

   if (count == 1) {
                                largest = mark;
                                smallest = mark;

                            } else {
                                if(mark >= 0 && mark <= 100){
                                    if (mark > largest) {
                                        largest = mark;
                                    }
                                    if (mark < smallest) {
                                        smallest = mark;
                                    }
                                }
                            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM