所以我试着为大学写一个简单的java程序,我是这个java东西的完全新手。我编译时遇到错误,“错误 - 在方法printreciept中找不到符号”。我知道它无法访问main中的变量。有人可以帮忙吗?我知道如果我确实修理它会有很多错误,但我宁愿从这里开始!附:抱歉所有代码:/
import java.util.Scanner;
public class Order {
public static void main (String[] args) {
String clubcard;
double clubcard_discount;
double special_discount;
double balance;
double final_balance;
int apples;
int oranges;
int apples_cost;
int oranges_cost;
final Scanner scanner = new Scanner( System.in);
System.out.println("How Many Bags of Apples?");
apples = scanner.nextInt( );
System.out.println("How many bags of Oranges?");
oranges = scanner.nextInt( );
System.out.println("Do you have a clubcard? Yes/No");
clubcard = scanner.nextLine();
if(clubcard == "Yes") {
clubcard_discount = clubcard_discount - 1.0;
final_balance = final_balance - (balance / 100 * 10);
}
else if(clubcard == "No") {
special_discount = 0.0;
}
if(apples == 3) {
special_discount = -1.0;
balance = balance - 1.0;
}
}
//Calculating the cost of apples and oranges
public void calculate_apples (final double apples_cost ) {
apples_cost = apples * 1.0;
}
public void calculate_oranges (final double oranges_cost ) {
oranges_cost = oranges * 1.25;
}
//Printing the receipt
public static void printReceipt() {
System.out.println("Bags of apples: " + apples);
System.out.println("Bags of oranges: " + oranges);
System.out.println("Clubcard: " + clubcard);
System.out.println( );
System.out.println("Price for apples: " + apples_cost);
System.out.println("Special discount: " + special_discount);
System.out.println("Price of oranges: " + oranges_cost);
System.out.println("Total: " + balance);
System.out.println("Clubcard discount: " + clubcard_discount);
System.out.println( );
System.out.println("Final price: " + final_balance);
System.out.println( );
System.out.println("Thanks for doing business with CS2500.");
}
}
答案 0 :(得分:2)
您已在main
方法中将所有变量声明为局部变量,因此它们不在main
之外的范围内。要使其他方法可以访问它们,您可以执行以下操作之一:
static
类变量,但在类中。答案 1 :(得分:0)
您没有传递变量,这就是问题所在。你在主要宣布他们。但是,如果在main方法之前将它们声明为静态变量,那么它将起作用。
答案 2 :(得分:0)
您可以添加使它们成为静态的变量。
public class Order {
static String clubcard;
static double clubcard_discount;
static double special_discount;
static double balance;
static double final_balance;
static int apples;
static int oranges;
static int apples_cost;
static int oranges_cost;
public static void main (String[] args) { ...
试试这个并告诉我们。
答案 3 :(得分:0)
在任何方法中声明的变量仅适用于该方法(本地范围)。 要么在类级别声明这些方法,要么将它们作为参数从main传递(根据用例,如果从main调用方法)。
答案 4 :(得分:0)
您传递的变量仅在main中可见。 函数printReceipt()无法查看变量,因为它们超出了其可见范围。
在这里,您可以尝试几个选项,程序将起作用:
将变量声明为公共类Order的数据成员,而不是将它们保留为main()函数的成员(最佳选项)。
public class Order{ static String clubcard; static double clubcard_discount; static double special_discount; static double balance; static double final_balance; static int apples; static int oranges; static int apples_cost; static int oranges_cost; //main() and other functions... }
OR
将数据成员作为参数传递给PrintReceipt()函数(虽然这可能会让您的功能有点混乱)。
public static void printReceipt(int apples,int oranges,....){
//...defining your function
}
希望这有帮助!