gpt4 book ai didi

java - Java 中的无效字符常量?

转载 作者:行者123 更新时间:2023-12-01 22:40:50 26 4
gpt4 key购买 nike

这是我的代码:

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':给我两次错误无效的字符常量?我的教授针对不同的程序有一个不同的示例,它与我正在做的几乎相同,但他没有得到错误。为什么我会收到此错误?

最佳答案

您遇到了几个问题。

首先,单引号是为单个字符保留的,例如'a'。整个字符串需要放在双引号中。

其次,timeTraveled 在您使用它时永远不会分配任何内容,因此在您尝试运行它(并进行编译)时它“可能”尚未初始化。您可能想改用input

这就是说,只要您使用 Java 7 或更高版本,您就应该将其编写为 switch 参数:

switch(input) {
// statements to follow
}

我不确定 "steel" 案例末尾的赋值是做什么的,但您可能希望将其逻辑移出 switch 完整声明。

关于java - Java 中的无效字符常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26173966/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com