2016-04-25 122 views
-2

我的程序遇到的唯一問題是掃描儀,我已經使用了很多次,但在此程序中它不會正確運行。該錯誤在public static getCandlecost()和public static int getShippingType()方法中。根據int shippingType = sc.nextInt();和雙candleCost = sc.nextDouble();都說「sc無法解決」,而在我的主要課程中,我確實聲明瞭這一點。聲明時掃描儀無法使用,sc無法解析

import java.util.Scanner; 
    import java.text.DecimalFormat; 

public class Candel { 

    public static void main(String[] args) { 

    Scanner sc = new Scanner(System.in); 

    double candleCost, shippingCost; 
    int shippingType; 

    candleCost = getCandlecost(); 
    shippingType = getShippingType(); 
    shippingCost = getShippingCost(candleCost, shippingType); 
    output(candleCost, shippingCost); 


} 

public static double getCandlecost() 
{ 
    boolean done = false; 
    do{ 
     try 
     { 
      System.out.print("Enter the cost of the candle order "); 
      double candleCost = sc.nextDouble(); 
      done = true; 
      return candleCost; 
     } catch (InputMismatchException e) 
     { 
      System.out.println("Error, Enter a dollar amount greater than 0"); 

     } 
    } while (!done); 
    return 0; 
} 

public static int getShippingType() 
{ 
    System.out.println("Enter the type of shipping: "); 
    System.out.println("1> Priority <overnight>"); 
    System.out.println("2> Express <2 business days>"); 
    System.out.println("3> Standard <3 to 7 business days>"); 
    System.out.println("Enter type number: "); 
    int shippingType = sc.nextInt(); 
    if(shippingType == 1){} 
     else if(shippingType == 2){} 
      else if(shippingType == 3){} 
    return shippingType; 

} 
public static double getShippingCost(double candleCost, int shippingType) 
{ 

     switch(shippingType) 
     { 
     case 1: 
      candleCost = 16.95 + candleCost; 
      break; 
     case 2: 
      candleCost = 13.95 + candleCost; 
      break; 
     case 3: 
      if (candleCost > 100.00){ 
       candleCost = candleCost; 
      } 
      else{ 
       candleCost = 7.95 + candleCost; 
      } 
      break; 
      } 
     return candleCost; 
} 



public static void output(double candleCost, double shippingCost) 
{ 
    DecimalFormat twoDigits = new DecimalFormat("$#,000.00"); 
    System.out.println("The candle cost of " + twoDigits.format(candleCost) + " with shipping costs of " 
      + shippingCost + " equals " + twoDigits.format(candleCost + shippingCost)); 

} 

} 
+2

您的掃描儀是本地main()。另外,如果你已經用Java編程了很多次,但不瞭解變量的範圍,那麼研究基礎知識是時候了。 –

回答

1

您的掃描儀超出範圍。由於您在main()方法中聲明瞭該方法,因此只有該方法可以訪問它。您的掃描儀也必須是靜態的。這樣寫:

public class Candel { 
    static Scanner sc = new Scanner(System.in); 

    public static void main(String[] args) { 
     ... 
    } 
    ... 
} 
+3

您需要使掃描儀保持靜態,因爲他使用的是靜態方法。僅供參考:我沒有downvote。 –

+0

當我這樣做,我在同一個地方得到的錯誤,但它提供了一個快速修復「改變sc靜態」 – mvanderk10

+0

@ShireResident是的,修復。謝謝。 – Gendarme