gpt4 book ai didi

java - 错误 "hours cannot be resolved to a variable",我做错了什么?

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

    Scanner kb = new Scanner(System.in);
System.out.println("Please enter a military time: ");
int time = kb.nextInt();
int minutes = (time%100);
if (time < 1){
System.out.println("Illegal time, please give another one.");
}else if (time%100>59){
System.out.println("Illegal time, please give another one.");
}else if (time>2400){
System.out.println("Illegal time, please give another one.");
}else{
if (time<100){
final int hours = 12;
}else if (time<1300){
final int hours = (time/100);
}else{
final int hours = ((time/100)-12); }
if (minutes<10)
System.out.println("Standard time is: "+hours+":0"+minutes);
else if (minutes>=10)
System.out.println("Standard time is: "+hours+":"+minutes);

这是一个将军用时间转换为标准时间的程序。我不断收到错误“小时无法解析为变量”,但不明白我的代码出了什么问题。任何洞察力的帮助都会有所帮助。

最佳答案

您已在每个 if case block 中声明了 hours,但由于 block 立即结束,hours 立即超出范围.

if 之前声明它,以便它保留在您需要的范围内。

final int hours;  // Not initialized yet.
if (time<100){
hours = 12;
}else if (time<1300){
hours = (time/100);
}else{
hours = ((time/100)-12); }
// Now it's still in scope here:
if (minutes<10)
System.out.println("Standard time is: "+hours+":0"+minutes);
else if (minutes>=10)
System.out.println("Standard time is: "+hours+":"+minutes);

请注意,编译器足够聪明,可以确定 final 变量 hours 在每种情况下都被初始化一次,因此它不会提示该变量可能不会已经初始化或者变量在初始化后可能已被更改。

关于java - 错误 "hours cannot be resolved to a variable",我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26225406/

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