Java错误:找不到符号,变量是否已声明?
嘿,伙计们,我正试图用Java编写一个简单的程序,找出军事时间中给出的2次时间之间的差异,并给出小时和分钟数的输出。每当我在命令提示符下编译此文件时,它都会在最后一行中为变量hours和变量minutes提供一个错误,并显示“找不到符号”。我本想在if语句之前声明它们,但这也不起作用。很抱歉,我对编程非常陌生,非常感谢您提供的帮助。当您在Java错误:找不到符号,变量是否已声明?,java,variables,symbols,Java,Variables,Symbols,嘿,伙计们,我正试图用Java编写一个简单的程序,找出军事时间中给出的2次时间之间的差异,并给出小时和分钟数的输出。每当我在命令提示符下编译此文件时,它都会在最后一行中为变量hours和变量minutes提供一个错误,并显示“找不到符号”。我本想在if语句之前声明它们,但这也不起作用。很抱歉,我对编程非常陌生,非常感谢您提供的帮助。当您在if块(或任何此类块)中定义对象引用或任何基本变量时,它只能在该块中访问 更改如下 import java.util.Scanner; public class
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();
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");
}
}
通过调用if语句中的字符串,它们只存在于if语句中,您需要在if之外对它们进行贴标,并在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);
}
因此,您可以将它们初始化为“”或删除不必要的else语句将它们初始化为else值
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");
}
}
哦,所以我必须为每个子块制作3个单独的输出?无需将它们分配给
null
。让编译器帮助您,并确保所有代码路径都对它们进行初始化。我正要这么说。如果可能的话,让它们成为final
。@GregKopff C/C++习惯,修复了这一点,非常感谢,但是null命令到底做什么呢?我以前从未被介绍过。
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");