當我嘗試從用戶收集字符串輸入並將其轉換爲字符類型時,我總是收到超出範圍的錯誤。這裏是我的代碼: 編輯:我的問題沒有得到回答。我在我的charAt語句中添加了一個參數,但它仍然不起作用。當我運行它時,它告訴我問題出現在第33行。這個問題不是我得到的任何鏈接的重複。我無法理解這個所謂的類似問題。請問有人能告訴我第33行有什麼問題嗎?Java - 字符串索引超出範圍錯誤
//Arthur Fidas
import java.util.Scanner; //Needed for Scanner class
import java.lang.String;
/**
This program computes and displays the shipping charges for Fed Ex.
*/
public class FedEx
{
public static void main (String[] args)
{
final double ZONE_A = .6, ZONE_B = 1.0, ZONE_C = 1.25, ZONE_D = 1.4;
String input;
char zone;
String name;
double weight;
double total = 0.0;
int serviceCode;
int hazardCode;
double hazardCodeCalculation;
//Create a Scanner object for keyboard input
Scanner keyboard = new Scanner (System.in);
//Prompt user for package weight
System.out.println("What is the weight of the package?: ");
weight = keyboard.nextDouble();
//Prompt user for Zone
System.out.print("Enter the zone letter: ");
input = keyboard.nextLine();
zone = input.charAt(0);
//Calculate zone price
switch(zone)
{
case 'a':
case 'A':
total = weight*ZONE_A;
break;
case 'b':
case 'B':
total = weight*ZONE_B;
break;
case 'c':
case 'C':
total = weight*ZONE_C;
break;
case 'd':
case 'D':
total = weight*ZONE_D;
break;
default:
System.out.println("Please enter A, B, C, or D.");
break;
}
//Prompt user for service charge
System.out.println("Enter the Special Service number: ");
serviceCode = keyboard.nextInt();
//Caculate Service Charge
if (serviceCode == 1)
{
total += 0;
}
else if (serviceCode == 2)
{
total += 10;
}
else if (serviceCode == 3)
{
total += 25;
}
else
{
System.out.println("Please enter 1, 2, or 3.");
}
//Prompt user for Hazard Code
System.out.println("Enter the Hazard Code number :");
hazardCode = keyboard.nextInt();
//Calculate Hazard Charge
switch(hazardCode)
{
case 1:
total += 0;
break;
case 2:
hazardCodeCalculation = total * .1;
total += hazardCodeCalculation;
break;
case 3:
hazardCodeCalculation = total * .25;
total += hazardCodeCalculation;
break;
default:
System.out.println("Please enter either 1, 2, or 3.");
break;
}
}
}
而且這將是有益的,如果你能幫助我編寫的代碼,將在結束方式在下面的評論呈現的顯示計算: –
,什麼是錯誤堆棧跟蹤出現「超出範圍錯誤」的位置? –
[String index out of range]可能重複(http://stackoverflow.com/questions/5011866/string-index-out-of-range) – paisanco