Java基础计算器

时间:2016-09-12 04:44:59

标签: java

我需要构建这个程序,找到三角形的缺失面,但我不断收到错误消息。这是我的代码:

import java.util.Scanner;

public class MissingSide  {

  static java.util.Scanner userInput = new Scanner(System.in);

  public static void main(String[] args) {

    System.out.print("What is the first side, other than the hypotenuse?");

    if (userInput.hasNextInt()) {
      int firstsideGiven = userInput.nextInt();
    } else {
      System.out.println("Enter something acceptable");
    }
    System.out.println("What is the hypotenuse?");

    if (userInput.hasNextInt()) {
      int hypotenuseGiven = userInput.nextInt();
    } else {
      System.out.print("Really?");
    }
    System.out.print("Your missing side value is: " + 
    System.out.print((Math.pow(firstsideGiven, 2) - Math.pow(hypotenuseGiven, 2)) + "this");
  }
}

它一直告诉我" hypotenuseGiven"和" firstside给予"无法解析为变量。这是供个人使用,而不是学校用品。谢谢。

2 个答案:

答案 0 :(得分:5)

hypotenuseGivenfirstsideGiven的范围仅限于代码中的if() {...}语句。

您不能在该范围之外使用它们。如果您希望这样做,请在if() {...}块之外声明它们。

答案 1 :(得分:0)

变量的范围仅限于if块。

额外注意事项:

1)代码的System.out.print()部分也存在语法错误。

2)根据毕达哥拉斯公式,计算需要一个squreroot。

调试代码示例如下:

import java.util.*;
import java.lang.Math;

public class MissingSide
{
   public static void main(String[] args)
   {
         int firstsideGiven = 0;
         int hypotenuseGiven = 0;
         Scanner userInput = new Scanner(System.in);
         System.out.print("What is the first side, other than the    hypotenuse?");

         if (userInput.hasNextInt()){

         firstsideGiven = userInput.nextInt();

         }else {
            System.out.println("Enter something acceptable");
         }
         System.out.println("What is the hypotenuse?");

        if (userInput.hasNextInt()){
            hypotenuseGiven = userInput.nextInt();
        }else{
            System.out.print("Really?");
        }
        System.out.print("Your missing side value is: " +(Math.sqrt((hypotenuseGiven*hypotenuseGiven)-(firstsideGiven*firstsideGiven))));
        }
    }