2012-12-02 42 views
0

我的程序可以接受任何我输入的数字,甚至是100万。 < 但我只是想要求用户输入在0°至180和输出 这个角度询问用户在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)); 

    } 
} 
+1

它可能是,但[没关系](http://meta.stackexchange.com/questions/ 10811 /如何问及答案作业 - 问题) –

+0

很可能如此,但OP已经做出了相当大的努力来回答这个问题,并且正在寻求单一问题上的帮助...... – ose

+0

是的,这是一项家庭作业问题和问题是这样的 “练习4. Trigonometry.java 编写一个程序,要求用户输入一个介于0和180之间的角度,并输出 该角度的正弦,余弦和正切,四舍五入至小数点后两位。“ 是的,我是一个学生和新编程.... –

回答

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

这个循环将继续下去,直到用户输入所需的值。

+0

非常感谢先生.... –

+0

我认为'抛出新的IllegalArgumentException(..'会更适合这种情况。 –

+0

也许,但后来值x不是任何参数,它是用户输入... – ose

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

非常感谢你的先生... –

+1

如果有效,请接受他的回答。 –

+0

不挑剔,但此代码不必要地复杂(if语句是多余的) – ose

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

+0

你是从无效的方法返回... – ose

+0

非常感谢先生... –

+0

@ ose - 谢谢,修正 – tucuxi