简体   繁体   中英

Java Basic Calculator

I need to build this program that will find the missing side of a triangle, but I keep getting an error message. This is my code:

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

It keeps telling me that "hypotenuseGiven" and "firstsideGiven" cannot be resolved into a variable. This is for personal use, not a school thing. Thank you.

The scope of hypotenuseGiven and firstsideGiven is limited to the if() {...} statements in your code.

You cannot use them outside that scope. If you wish to do so, declare them outside the if() {...} blocks.

The scope of the variables is limited to the if blocks.

Extra note:

1)There is also a syntax error in your System.out.print() part of the code.

2)Calculation requires a squreroot according to pythagoras formula.

A Debugged code sample is as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM