Last active
June 5, 2020 05:41
-
-
Save CobyR/9765c95b2f15f1186a89b474de9accdc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.Scanner; | |
public class IdentifierCheck | |
{ | |
public static void main(String[] args) | |
{ | |
// input from user | |
Scanner in = new Scanner(System.in); | |
String name = " "; | |
char sp; | |
System.out.println("This program checks the properness of a proposed Java variable name."); | |
while (true) { | |
ArrayList<String> errors = new ArrayList<String>(); | |
System.out.println("Enter a variable name. (q to quit):"); | |
name = in.nextLine(); | |
if (name.charAt(0) == 'q' && name.length() == 1) break; | |
for (int i = 0; i < name.length(); i++) | |
{ | |
sp = name.charAt(i); | |
if (Character.isWhitespace(sp)) | |
{ | |
if(!errors.contains("Illegal, no whitespace allowed.")) | |
errors.add ("Illegal, no whitespace allowed."); | |
} | |
else if (Character.isDigit(sp) && i == 0) | |
{ | |
errors.add ("Illegal, must begin with a letter."); | |
} | |
else if (Character.isLetterOrDigit(sp)) | |
{ | |
if(Character.isLowerCase(sp) && i == 0) | |
{ | |
errors.add("Warning, it would be better with the first letter in uppercase."); | |
} | |
} | |
else { | |
errors.add("Illegal, must only contain letters and digits."); | |
} | |
} | |
if(errors.size() == 0) { | |
System.out.println("Well done, that's a nice variable name."); | |
} else { | |
System.out.println("You had errors:"); | |
System.out.println(errors); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment