2017-09-16 130 views
0

我是一名學生,剛學習類和方法。我收到一個錯誤(第30行 - 儲蓄= PR *折扣/ 100)「找不到符號」。我知道我的可變折扣超出了範圍,但我無法弄清楚如何解決這個問題。我已按照提供給我的說明進行操作,但仍然無法正常工作。我已經在課本中發現了一些錯別字,所以有什麼遺漏嗎?還是我對大括號的定位?Java變量超出範圍

import java.util.Scanner; // Allows for user input 

public class ParadiseInfo2 
    { 
    public static void main(String[] args) 
    { 
     double price; // Variable for minimum price for discount 
     double discount; // Variable for discount rate 
     double savings; // Scanner object to use for keyboard input 
     Scanner keyboard = new Scanner(System.in); 

     System.out.print("Enter cutoff price for discount >> "); 
     price = keyboard.nextDouble(); 
     System.out.print("Enter discount rate as a whole number >> "); 
     discount = keyboard.nextDouble(); 

     displayInfo(); 

     savings = computeDiscountInfo(price, discount); 


    System.out.println("Special this week on any service over " + price); 
    System.out.println("Discount of " + discount + " percent"); 
    System.out.println("That's a savings of at least $" + savings); 

    } 

    public static double computeDiscountInfo(double pr, double dscnt) 
    { 
    double savings; 
    savings = pr * discount/100; 
    return savings; 
    } 

    public static void displayInfo() 
    { 
    System.out.println("Paradise Day Spa wants to pamper you."); 
    System.out.println("We will make you look good."); 
    } 
} 
+0

這是一個簡單的問題來解決。我在下面添加了一個答案。 – Assafs

+0

順便說一句,如果我的回答解決了這個問題 - 我可以問你笑納通過單擊旁邊的灰色複選標記的答案,使其成爲綠色? – Assafs

+2

讓我們來看看爲什麼從變量名稱中刪除元音是一個糟糕的主意。 –

回答

1

你的代碼是正確的 - 你剛纔叫出來的範圍變量打折的時候,你所需要的範圍變量dscnt。試試這個:

public static double computeDiscountInfo(double pr, double dscnt) { 
    double savings; 
    savings = pr * dscnt/100; 
    return savings; 
} 
1

問題是由引起的,因爲你在你的問題中提到,該變量discount被淘汰的範圍。我們來看看爲什麼。

在原來的代碼,該方法computeDiscountInfo(double pr, double dscnt)傳遞給參數:一個雙標記PR,和另一個雙標記dscnt。你的方法只知道這兩個參數,而不知道其他任何事情。 (有一些例外,如「靜止」的變量,或從父母傳給變量。然而,這些是最有可能超出你的學習,此刻的範圍。我相信你很快就西港島線覆蓋它們在學校。 )

由於在main()方法中聲明變量discount,因此您的方法無法知道它的存在。當您CAL這種方法,你可以通過它的discount變量,要使用的參數(如你在你的代碼savings = computeDiscountInfo(price, discount);做),那麼該方法的discount值適用於您在定義它自己的局部變量dscnt方法的聲明。這是該方法將知道並使用的變量。

現在,讓我們回頭看看你的方法:

public static double computeDiscountInfo(double pr, double dscnt) 
    { 
    double savings; 
    savings = pr * discount/100; 
    return savings; 
    } 

在這種方法中,你指的是變量discount,而不是由本地名稱dscnt作爲方法的參數聲明。該方法不瞭解什麼是discount。它可以在這個地方通過任何雙重。通過改變字discountdscnt你的方法中,該方法將能夠理解你reffering什麼和正確使用的價值。

public static double computeDiscountInfo(double pr, double dscnt) 
    { 
    double savings; 
    savings = pr * dscnt/ 100; 
    return savings; 
    } 

我希望這對你有意義,請讓我知道,如果它不。局部變量和變量範圍的概念是面向對象編程基礎的關鍵部分。

+0

非常感謝你的精彩解釋!是的,這是有道理的。我感謝您的幫助! – Beth

+0

很高興我能幫上忙! – JJT