Reputation: 39
My program accepts any number that I input even 1 million >.< but I only wanted to ask the user to input an angle in degrees between 0 to 180 and outputs the sine, cosine and tangent of that angle
here is my program :
import java.util.Scanner;
import java.text.DecimalFormat;
public class Mathematics
{
public static void main(String args[])
{
System.out.println("Enter an Angle ");
Scanner data = new Scanner(System.in);
int x;
x=data.nextInt();
double sinx = Math.sin( Math.toRadians(x) );
double cosx = Math.cos( Math.toRadians(x) );
double tanx = Math.tan( Math.toRadians(x) );
DecimalFormat format = new DecimalFormat("0.##");
System.out.println("Sine of a circle is " + format.format(sinx));
System.out.println("cosine of a circle is " + format.format(cosx));
System.out.println("tangent of a circle is " + format.format(tanx));
}
}
Upvotes: 0
Views: 2441
Reputation: 17945
Put the question in a loop. When the user enters a value that is outside your range, print an error message and request a different value. When the entered value is OK, then you can exit the loop. It is better to use a function to make things more readable:
public static int askForInt(String question, String error, int min, int max) {
while (true) {
System.out.print(question + " (an integer between " + min + " and " + max + "): ");
int read = new Scanner(System.in).nextInt();
if (read >= min && read <= max) {
return read;
} else {
System.out.println(error + " " + in + " is not a valid input. Try again.");
}
}
}
Call like this: x = askForInt("The angle", "Invalid angle", 0, 180);
Upvotes: 1
Reputation: 4075
Put this code after x=data.nextInt();
if( x < 0 || x > 180 )
{
throw new Exception("You have entered an invalid value");
}
This will cause your program to crash if the user inputs a number outside the range [0, 180]. If you wish to allow the user to try again, you would need to put the program into a loop, like so:
do
{
System.out.print("Enter a value in [0, 180]: ");
x = data.nextInt();
} while(x < 0 || x > 180);
This loop will continue until the user enters the desired values.
Upvotes: 3
Reputation: 5662
Instead of
x = data.nextInt();
write
do {
x = data.nextInt();
if (x < 0 || x > 180) {
System.out.println("Please enter number between 0-180");
}
} while (x < 0 || x > 180);
Upvotes: 2