I'm doing this as a homework assignment for my first CS class, so I'm pretty new to Java. The goal is to create a program that checks a user input for a specified Java variable. There are three stipulations/outputs:
If I run this program and type something like "variable" for the first loop, it will go through and print "Good!" by the end. And when the program asks again and I type something like "4variable", it will return "Illegal" - makes sense. The problem comes right after this. If I type the next variable like "variable" again, it will return "Illegal" because it still thinks there is a digit in the first character position. When I debug, it shows the "number" boolean set to 'true' even though it's false. I can't get it to drop the previous iteration of the loop.
Here is my code:
import java.util.Scanner;
public class IdentifierTestThree {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String userVariable = "";
char ch = ' ';
boolean space = false;
boolean number = false;
boolean capital = false;
//boolean specialCharacter = false;
boolean style = false;
// State what this program does
System.out.println("This program checks to see if a Java variable is legal or not.");
// Get input from user
System.out.println("Enter a variable: ");
userVariable = in .nextLine();
do {
int variableParse = userVariable.length();
for (int i = 0; i < variableParse; i++) {
if ((Character.isLetterOrDigit(userVariable.charAt(i)) == false)) {
style = true;
}
}
// Get the first character
ch = userVariable.charAt(0);
// Check each stipulation
if (Character.isUpperCase(ch)) {
capital = true;
}
if (Character.isDigit(ch)) {
number = true;
}
if (userVariable.contains(" ")) {
space = true;
}
if (space || number || capital) {
System.out.println("Illegal");
} else if (style) {
System.out.println("Legal, but uses poor style.");
} else {
System.out.println("Good!");
}
// Ask the user to enter another variable or end the program
System.out.println("Enter another variable or type 'Q' to quit.");
userVariable = in .nextLine();
} while (!userVariable.equalsIgnoreCase("Q"));
}
}
You need to reset space, number, capital and style inside the do-loop which is processing a single variable. In fact you can move the declarations there as well, since the values are not needed outside that loop.
do {
boolean space = false;
boolean number = false;
boolean capital = false;
//boolean specialCharacter = false;
boolean style = false;
int variableParse = userVariable.length();
for (int i = 0; i < variableParse; i++) {
if ((Character.isLetterOrDigit(userVariable.charAt(i)) == false)) {
style = true;
}
}
// Get the first character
char ch = userVariable.charAt(0);
…