【问题标题】:cannot find symbol : Variable error [duplicate]找不到符号:变量错误[重复]
【发布时间】:2016-01-31 07:39:17
【问题描述】:

这是我的代码。我正在上编程课,似乎遇到了很多错误,我不知道如何解决。他们都这么说:

C:\Users\patrickwilliams\Desktop\Java\tuition.java:30:找不到符号 符号:可变小时 地点:课堂教学 小时 = 0;

每个变量以此类推

import java.io.*;
import java.util.*;
import java.text.DecimalFormat;


public class tuition {
  public static void main(String[] args) {
    int hours;
    double fees, rate, tuition;



    displayWelcome();
    hours = getHours();
    rate = getRate(hours);
    tuition = calcTuition(hours, rate);
    fees = calcFees(tuition);
    displayTotal(tuition + fees);

  }

  public static void displayWelcome() {

    System.out.println("Welcome to the tuition calculator!");

  }

  public static int getHours() {
    String strHours;
    hours = 0;
    boolean done = false;



    while (!done) {
      try {
        int hours;

        System.out.println("Enter the total number of hours.");
        hours = Input.nextInt();

        done = true;
      } catch (Exception e) {
        System.out.println("Please enter an integer value.");
      }
    }
    return hours;
  }

  public static double getRate(int hours) {

    if (hours > 15) {
      rate = 44.5;
    } else {
      rate = 50;
    }
    return rate;
  }

  public static double calcTuition(int hours, double rate) {
    tuition = hours * rate;
    return tuition;
  }

  public static double calcFees(double tuition) {

    fees = tuition * .08;
    return fees;
  }

  public static void displayTotal(double total) {

    DecimalFormat twoDigits = new DecimalFormat("$#,000.00");

    System.out.println("Your total is " + twoDigits.format(tuition + fees));

  }
}

【问题讨论】:

    标签: java variables find symbols


    【解决方案1】:
    public static int getHours() {
        String strHours;
        hours = 0;
        ...
    

    这是你的问题hours。在您尝试为其赋值之前,不会声明此变量。

    稍微扩展一下:

    在 java 中,您需要在函数内部声明一个变量,然后才能使用它。稍后在这个相同的功能中你有

    while (!done) {
      try {
        int hours;
    ...
    

    int hours 将声明在此函数中使用的变量,但在您的情况下,您尝试在声明之前使用它。删除此 int hours; 行并在您的 hours = 0; 之前添加 int 应该会清除此错误。

    【讨论】:

    • 你不认为问题是因为他定义了两次 int hours 吗?
    • @therealprashant 我不这么认为,该函数只有 1 个 hours 声明,但它发生在他/她尝试为其分配 0 之后。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-12
    • 2021-01-31
    • 2011-06-24
    • 2012-12-27
    • 2016-08-08
    相关资源
    最近更新 更多