Вот мой код:Недопустимая константа символов в 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
дважды? У моего профессора есть другой пример для другой программы, и это почти то же самое, что и я, но он не получает ошибку. Почему я получаю эту ошибку?
воздуха не символ –
Эй спасибо парня за быстрый ответ, я починю бардак с timeTraveled, а Я следовал примеру моего профессора и забыл стереть эту часть. (удаление его ничего не делает). Кроме того, когда я помещаю кавычки вокруг воздушной воды и стали, это дает мне ошибку «Тип несоответствие, невозможно преобразовать из строки в символ» – justaregularguy
Вы пытаетесь переключить (char) timeTraveled со смешанными типами. char и String. Вы не можете этого сделать. Объявить timeTraveled, чтобы напечатать String и обернуть воздух в двойных кавычках. –