Java错误:找不到符号但是声明了变量?

import java.util.Scanner; public class Assignment1Q3 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Please enter the first time: "); int fTime = in.nextInt(); System.out.print("Please enter second time: "); int lTime = in.nextInt(); int tDifference = Math.abs(fTime - lTime); String strTDiff = String.valueOf(tDifference); int length = strTDiff.length(); if (length == 4) { String hours = strTDiff.substring(0, 2); String minutes = strTDiff.substring(3, 5); } else if (length == 3) { String hours = strTDiff.substring(0); String minutes = strTDiff.substring(2, 4); } else { String hours = ("0"); String minutes = strTDiff.substring(0, 1); } System.out.println(hours + " hours " + minutes + " minutes"); } } 

嘿伙计们,所以我试图用一个简单的程序使用Java来找到军事时间给出的2次之间的差异,并以小时和分钟的数量给出输出。 每当我在命令提示符下编译它时,它会给出一个变量小时的错误和最后一行打印行中的变量分钟“无法找到符号”。 我想在if语句之前尝试声明它们,但这也不起作用。 我很抱歉,但我对编程很新,并感谢所提供的任何帮助。

通过在if语句中调用String,它们只存在于if语句中,您需要在if语句之外对它们进行十进制并将其与if中的值相关联。

 import java.util.Scanner; public class Assignment1Q3 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Please enter the first time: "); int fTime = in.nextInt(); System.out.print("Please enter second time: "); int lTime = in.nextInt(); int tDifference = Math.abs(fTime - lTime); String strTDiff = String.valueOf(tDifference); int length = strTDiff.length(); String hours = ""; String minutes = ""; if (length == 4) { hours = strTDiff.substring(0, 2); minutes = strTDiff.substring(3, 5); } else if (length == 3) { hours = strTDiff.substring(0); minutes = strTDiff.substring(2, 4); } else { hours = ("0"); minutes = strTDiff.substring(0, 1); } System.out.println(hours + " hours " + minutes + " minutes"); } } 

所以你可以将它们初始化为“”或删除不必要的else语句将它们初始化为else valuse

  String hours = "0"; String minutes = strTDiff.substring(0, 1); if (length == 4) { hours = strTDiff.substring(0, 2); minutes = strTDiff.substring(3, 5); } else if (length == 3) { hours = strTDiff.substring(0); minutes = strTDiff.substring(2, 4); } System.out.println(hours + " hours " + minutes + " minutes"); 

if块(或任何此类块)中定义对象引用或任何基元变量时,只能在该块中访问它。

改变如下

 final String hours, minutes; if (length == 4) { hours = strTDiff.substring(0, 2); minutes = strTDiff.substring(3, 5); } else if (length == 3) { hours = strTDiff.substring(0); minutes = strTDiff.substring(2, 4); } else { hours = ("0"); minutes = strTDiff.substring(0, 1); }