hi for my programming class we have to write an average calculator program in any langauge we want. I did mine in Java and im fairly new to programming. the problem with my code is how can I improve it to make sure user's incorrect input ruins program. for example if a user types in letters instead of numbers. here is my code.

`import java.util.Scanner;
import java.text.DecimalFormat;

public class Average
{
    public static void main(String[]args)
    {
        int count = 0;
        int total = 0;
        final int stopValue = 0;
        int number;

        Scanner scan = new Scanner(System.in);

        System.out.println("You can enter numbers here and enter zero to finish");

        System.out.print("enter the number: ");
        number = scan.nextInt();

        while(number != stopValue)
        {
            total += number;
            count++;

            System.out.print("enter the number: ");
            number = scan.nextInt();

        }

        if(count !=0 )
        {
            DecimalFormat twoDP = new DecimalFormat("##.00");
            System.out.println("\nThe Average is "+ twoDP.format((double)(total)/count));
        }
        else
        {
            System.out.println("\nNo numbers entered");
        }
    }
}
    `

Recommended Answers

All 5 Replies

The Scanner class has several methods that can be used to test what the user has entered. Their names begin with has..... You could use some of them to test for valid input and issue an error message and ask for new input of the correct type after clearing the current input with a call to nextLine().

Since every number is divisible by 1, you can try doing a hidden division :-

boolean isANumber;
try {
if((userInput % 1) ==0) {
isANumber=true;
}
}
catch(NumberFormatException e) {
System.out.println("This is not a number");
}

if(isANumber) {
//further code which will be executed only if it is a number
}

???? What datatype is the variable: userInput?

is userInput supposed to be int or String? - either way this won't work!

oops! sorry guys!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.