0

我的程序接受我输入的任何数字,甚至是 100 万 >.< 但我只想要求用户输入 0 到 180 度之间的角度,并输出该角度的正弦、余弦和正切

这是我的程序:

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));

  }
}
4

3 回答 3

3

将此代码放在后面x=data.nextInt();

if( x < 0 || x > 180 )
{
    throw new Exception("You have entered an invalid value");
}

如果用户输入超出范围 [0, 180] 的数字,这将导致您的程序崩溃。如果您希望允许用户重试,则需要将程序放入循环中,如下所示:

do
{
    System.out.print("Enter a value in [0, 180]: ");
    x = data.nextInt();
} while(x < 0 || x > 180);

这个循环将一直持续到用户输入所需的值。

于 2012-12-02T11:16:07.420 回答
2

代替

x = data.nextInt();

do {
    x = data.nextInt();
    if (x < 0 || x > 180) {
        System.out.println("Please enter number between 0-180");
    }
} while (x < 0 || x > 180);
于 2012-12-02T11:18:13.317 回答
1

把问题放在一个循环中。当用户输入的值超出您的范围时,打印一条错误消息并请求不同的值。当输入的值OK后,可以退出循环了。最好使用函数来使内容更具可读性:

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.");
       }
    }
}

像这样调用:x = askForInt("The angle", "Invalid angle", 0, 180);

于 2012-12-02T11:21:29.697 回答