這裏是我的代碼:Java中的字符常量無效?
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
/*
Medium Speed
Air 1100 feet per second
Water 4900 feet per second
Steel 16,400 feet per second
Write a program that asks the user to enter "air", "water", or "steel", and the distance that a sound wave will
travel in the medium. The program should then display the amount of time it will take.
You can calculate the amount of time it takes sound to travel in air with the following formula:
Time = Distance/1100
You can calculate the amount of time it takes sound to travel in water with the following formula:
Time = Distance/4900
You can calculate the amount of time it takes sound to travel in steel with the following formula:
Time = Distance/16400
*/
public class SpeedOfSound
{
public static void main(String[] args)
{
String input;
char timeTraveled;
Scanner keyboard = new Scanner(System.in);
double distance;
double time;
double time2;
double time3;
time = (distance/ 1100);
time2 = (distance/ 4900);
time3 = (distance/ 16400);
DecimalFormat formatter = new DecimalFormat("#0.00");
System.out.println("Enter air, water, or steel: ");
input = keyboard.nextLine();
System.out.print("Enter distance: ");
distance = keyboard.nextDouble();
switch(timeTraveled)
{
case 'air':
System.out.printf("The total time traveled is " + formatter.format(time) + ".");
break;
case "water":
System.out.printf("The total time traveled is " + formatter.format(time2) + ".");
break;
case "steel":
System.out.printf("The total time traveled is " + formatter.format(time3) + "seconds.");
timeTraveled = input.charAt(0);
break;
keyboard.close();
}
} // main()
} // class SpeedOfSound
爲什麼case 'air':
給我的錯誤invalid character constant
兩次?我的教授對另一個程序有不同的例子,它和我正在做的幾乎一樣,但他沒有得到錯誤。爲什麼我會得到這個錯誤?
空氣不是一個char – 2014-10-03 06:02:09
嘿傢伙感謝您的快速反應,我就修理好惹的timeTraveled,如我正在按照我的教授的例子,忘記擦除那部分。 (擦除它不會做任何事情)。另外,當我在空氣水和鋼周圍加上引號時,它給了我錯誤「類型不匹配,無法將字符串轉換爲字符」 – justaregularguy 2014-10-03 06:07:08
您正在嘗試使用混合類型切換(char)timeTraveled。字符和字符串。你不能那樣做。聲明timeTraveled以輸入String並用雙引號將空氣換行。 – 2014-10-03 06:26:10