我收到此消息:错误:b无法解析为变量

时间:2014-10-23 22:31:30

标签: java java.util.scanner

这是我的代码。有人可以帮我解决这个问题吗?我收到编译错误消息:

找到2个错误: 文件:C:\ Users \ Keith \ Desktop \ Prog Files \ HW4ChrisMuncher.java [line:13] 错误:a无法解析为变量 文件:C:\ Users \ Keith \ Desktop \ Prog Files \ HW4ChrisMuncher.java [line:19] 错误:b无法解析为变量

import java.util.Scanner;
public class HW4ChrisMuncher
{
  public static void main(String[] args) 
  {
    Scanner input = new Scanner(System.in);

    System.out.println("Enter a number");
    double userNum = input.nextDouble();
    a = userNum;  

    Scanner input2 = new Scanner(System.in);

    System.out.println("Enter a number (no decimals!)");
    double userNum2 = input2.nextDouble();
    b = userNum2;  



    double a;
    int b;
    double c = min(a, b);
    double d = max(a, b);
    double e = abs(a);
    double f = pow(a, b);     



    System.out.println("Minimum Value of 11 and 8 is " + c );        
    System.out.println("Maximum Value of 11 and 8 is " +d );
    System.out.println("The absolute value of 11.5 is " +e );
    System.out.println("11.5 to the power of 8 is " +f );

  }

  // Returns the minimum of two numbers
  public static double min(double n1, int n2) 
  {
    double min;
      if (n1 > n2)
       min = n2;
      else
        min = n1;

      return min; 
   }

   // Return the max between two numbers
   public static double max(double n1, int n2)
   {
     double max;
       if (n1 > n2)
        max = n1;
       else
         max = n2;

       return max;
    }


   //Returns the absolute value of the two numbers
   public static double abs(double n1)
   {
     if (n1 < 0)
       return -n1;
     else 
       return n1;

   }


   public static double pow(double n1, int n2)
   {
     double f = 1;
         for (int i =0; i< n2; i++)
           {
             f = f * n1;
           }
         return f;

   }


}

2 个答案:

答案 0 :(得分:1)

您在声明之前尝试使用ab。在您首次使用之前,请先移动ab的声明(即行double a;int b;)。

答案 1 :(得分:1)

您正在做:

a = userNum;  //compiler: "WTF is a?? I dunno... Exception!!!!!!" 
b = userNum2;   //compiler: "WTF is b?? Exception!!!!" 

//...THEN:

double a;  //compiler: "I didn't read this far, I stopped at the first exception."
int b;

你需要这样做:

double a;  //compiler: "okay, a is going to refer to a double" 
int b;  //compiler: "okay, b is going to refer to an int" 

//...THEN: 

a = userNum;  //compiler: "cool, a refers to THAT double"
b = userNum2;   //compiler: "cool, b refers THAT int"

即。您必须声明 之前