gpt4 book ai didi

java - 用户输入摄氏度和华氏度验证

转载 作者:行者123 更新时间:2023-11-30 05:52:34 25 4
gpt4 key购买 nike

首先,感谢所有提供帮助的人。其次,请记住我是一个新手(如我的代码所示哈哈)。

我只是想让它做用户输入验证的事情。它应该验证气温、单位和风速。无论我输入什么,它都会告诉我该单位无效。我是否对阅读键盘输入部分做了一些奇怪的事情?
这是我的程序输出的内容(示例用户输入以粗体显示):

  • Wind Chill calculation program.
  • Enter the air temperature followed by the unit. For example, 25 F for Fahrenheit or 25 C for Celsius.
  • Air temperature: 25 F
  • Enter the wind speed (in miles per hour).
  • Wind speed: 10
  • The unit is invalid.
  • Wind Chill not calculated: Total Errors = 1
  • Wind Chill program is completed.
  • BUILD SUCCESSFUL (total time: 53 seconds)

另外,我还没有尝试过这部分,但我想让单位不区分大小写。我会用 .toLowerCase() 或 .toUpperCase() 来做到这一点,对吧?我只是想确保我走的是正确的方向。

下面的链接是作业要求以及该程序应该执行的操作的示例。如果您不想(当然),则不必查看它们,但我添加了它们,以防万一我没有很好地解释自己。

  1. Detailed program specs
  2. Code skeleton of program specs
  3. Sample program output

这是我到目前为止所得到的:

import java.util.Scanner;

public class WindChill2
{
public static void main(String args[])
{
// Variables
Scanner keyboard = new Scanner(System.in);
double temp, // Temperature
windSpeed, // Speed of wind in miles per hour
windChill; // Wind chill factor
int errorCount = 0; // User entry errors
char unit;

// Input
System.out.println("Wind Chill calculation program.");

System.out.println("Enter the air temperature followed by the unit. "
+ "For example, 25 F for Fahrenheit or 25 C for "
+ "Celsius.");
System.out.print("Air temperature: ");
temp = keyboard.nextDouble(); // Store user entry in temp
unit = keyboard.next().charAt(0); // Store unit (C or F)
System.out.println("Enter the wind speed (in miles per hour).");
System.out.print("Wind speed: ");
windSpeed = keyboard.nextDouble(); // Store user entry in windSpeed

// Processing
if (temp < -40 || temp > 50) // Validate temperature
{
System.out.println("The air temperature is invalid.");
errorCount++;
}

if (unit != 'C' || unit != 'F') // Validate unit
{
System.out.println("The unit is invalid.");
errorCount++;
}

if (windSpeed < 0 || windSpeed > 50) // Validate wind speed
{
System.out.println("The wind speed is invalid.");
errorCount++;
}

if (errorCount > 0) // Error counter
{
System.out.println("Wind Chill not calculated: Total Errors = "
+ errorCount);
}
else // Calculate wind chill factor
{
windChill = 91.4 - (91.4 - temp) * (.478 + .301 *
Math.sqrt(windSpeed) - .02 * windSpeed);
System.out.print("The Wind Chill factor is ");
System.out.printf("%.1f\n", windChill);
}

System.out.println("Wind Chill program is completed.");
}
}

最佳答案

您所写的检查设备的条件有误。 单位!= 'C' ||当 unit == 'F' 时,unit != 'F' 将返回 true,因为其中一个条件 (unit != 'C') 为 true。如果任一表达式为 true,OR 运算符 (||) 将返回 true。

要解决此问题,只需使用 AND 运算符 (&&),这样,如果单位不等于 C AND,则该单位无效F

因此条件应该是unit != 'C' && unit != 'F'

关于java - 用户输入摄氏度和华氏度验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53643908/

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