为什么即使定义了字符串,java也找不到符号?
import java.util.Scanner;
public class DJNameCreator {
public static void main(String[] args){
//Variables to store inputted names
String firstName;
String lastName;
//Scanner for user inputted names
Scanner keyboard = new Scanner (System.in);
System.out.println("Please enter your first name: ");
firstName = keyboard.nextLine();
System.out.println("Nice to meet you, "+firstName+"!");
System.out.println("Please enter your last name: ");
lastName = keyboard.nextLine();
//Use substring and length method to get total length of string
//First name section
int firstLength = firstName.length();
if (firstLength%2 == 0){
String firstHalf = firstName.substring(0, firstLength/2);
}
//Last name section
int lastLength = lastName.length();
if (lastLength%2 == 0){
String lastHalf = lastName.substring((lastLength/2), lastLength);
}
if (lastLength%2 == 1){
String lastHalf = lastName.substring((lastLength/2), (lastLength)-1);
}
//Output the DJ name using println combined with the word "Jayster"
System.out.println(firstHalf + "Jayster" + lastHalf);
}
}
我不明白为什么java找不到符号。我的代码在最后一个println
之前编译得很好。它特别指向firstHalf
和lastHalf
。我在if语句中定义了它们,但它不会编译
这是因为if语句与主代码是隔离的吗
# 1 楼答案
在上面的代码段中,
firstHalf
和secondHalf
仅在各自的If块中具有作用域。当您试图在Main的方法范围内打印它时您可以找到有关作用域here的更多信息
检查下面的重构代码