Reputation: 11
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);
}
}
I can't figure out why java cannot find symbol. My code compiles fine until the last println
. It's pointing at firstHalf
and lastHalf
specifically. I have them defined in the if statement, but it won't compile.
Is it because if statements are kind of isolated from the main code?
Upvotes: 1
Views: 65
Reputation: 1270
In the snippet above the firstHalf
and secondHalf
have scope only in their respective If blocks. Where as you are trying to print it in the method scope of Main.
You can find more info about scopes here.
Check the refactored code below.
import java.util.Scanner;
public class DJNameCreator {
public static void main(String[] args){
String firstName;
String lastName;
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();
int firstLength = firstName.length();
// FirstHalf is in the scope of main method.
String firstHalf = "";
if (firstLength%2 == 0){
firstHalf= firstName.substring(0, firstLength/2);
}
int lastLength = lastName.length();
// LastHalf is in the scope of main method.
String lastHalf ="";
if (lastLength%2 == 0){
lastHalf = lastName.substring((lastLength/2), lastLength);
}
if (lastLength%2 == 1){
lastHalf = lastName.substring((lastLength/2), (lastLength)-1);
}
//Output the DJ name using println combined with the word "Jayster"
System.out.println(firstHalf + "Jayster" + lastHalf);
}
}
Upvotes: 2