Java error: <identifier> expected unable to compile - java

I am trying to finish a homework assignment and keep getting two errors and cannot figure out how to fix them. Here is the code:
import java.util.Scanner;
public class GoughAndreaProg5
{
public static void main (String[] args)
{
Scanner stdIn = new Scanner(System.in);
System.out.println("Enter a password that meets the following rules: ");
System.out.println("");
System.out.println("Is atleast 8 characters long");
System.out.println("Contains atleast 1 lower letter character");
System.out.println("Contains atleast 1 upper letter character");
System.out.println("Contains atleast 1 numeric digit");
System.out.println("Contains atleast 1 special character from the set: !##$%^&*");
System.out.println("Does not contain the word \"and\" or the word \"end\"");
System.out.println("");
String myInput = stdIn.nextLine();
boolean digit = false;
boolean upperCase = false;
boolean lowerCase = false;
for(int x=0; x<myInput.length(); x++)
{
if (Character.isDigit(myInput.charAt(x)))
digit = true;
if(Character.isUpperCase(myInput.charAt(x)))
upperCase = true;
if(Character.isLowerCase(myInput.charA(x)))
lowerCase = true;
}
boolean validLength = true;
if (myInput.length() < 8)
{
System.out.println("Must be at least 8 characters long");
validLength = false;
}
boolean special = false;
if(myInput.indexOf('!') != -1 | myInput.indexOf('#') != -1 || myInput.indexOf('#') != -1 || myInput.indexOf('$') != -1 || myInput.indexOf('%') != -1 || myInput.indexOf('^') != -1 || myInput.indexOf('&') != -1 || myInput.indexOf('*') != -1)
special = true;
else //no special character
{
System.out.println("Must contain a special character");
}
boolean word = false;
if (myInput.indexOf("and") != -1 || myInput.indexOf("end"));
{
word = true;
System.out.println("Contains the string \"and\" or the word \"end\"");
}
if(!digit)
System.out.println("Must have a numeric digit");
if(!upperCase)
System.out.println("Must have an upper case");
if(!lowerCase)
System.out.println("Must hava a lower case");
//output valid or not
if (validLength && special && !word && upperCase && lowerCase && digit)
System.out.println("valid");
else
System.out.println("not valid");
} //end main method
public static void System.out.println(String inStr)
{
System.out.println(inStr);
} //end of alt string print method
} //end of class
The errors are:
C:\Users\gougha\Documents\Park\Java Class\myJavaPgms\GoughAndreaProg5.java:76: error: '(' expected
public static void System.out.println(String inStr)
^
C:\Users\gougha\Documents\Park\Java Class\myJavaPgms\GoughAndreaProg5.java:76: error: <identifier> expected
public static void System.out.println(String inStr)
^
I have tried every thing I can think of. I'm sure it's an easy fix, but this is all so new to me and I can't see it. Thank you!

There are several compile errors with your code
To start
public static void System.out.println(String inStr)
should be (though you don't use it so I suggest just remove this method)
public static void println(String inStr)
Then
if (myInput.indexOf("and") != -1 || myInput.indexOf("end"));
should be
if (myInput.indexOf("and") != -1 || myInput.indexOf("end") != -1);
Finally
if(Character.isLowerCase(myInput.charA(x)))
should be
if(Character.isLowerCase(myInput.charAt(x)))

You do not need to create this method public static void System.out.println(inStr). Infact the syntax is also wrong. You just need to provide a method name when you create it. Not the class name along with it.
// Not required at all
public static void System.out.println(String inStr)
{
System.out.println(inStr);
}
System.out.println() is the inbuilt method to print values to the console. So just use System.out.println(inStr) in your main method, whenever you need to print something on the System's output console.

Related

Getting the final else statement to run Java recursive method

Everything works in this class except for the final else statement. This is a recursive java letter tester. The program tests a user's word for all three letters (e, l, f). So far, Program throws exception error string index out of bounds if the word doesn't contain e, l and f
import java.util.Scanner;
public class FrettyRecursionMethod {
static boolean e = false;
static boolean f = false;
static boolean l = false;
static int n = 0;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userWord;
System.out.println("Enter a single word.");
userWord = input.nextLine();
elfish(userWord, 0);
} // end main
public static void elfish(String userWord, int n) {
char ee = userWord.charAt(n);
if (ee == 'e' || ee == 'E') {
e = true;
} // end if
else if (ee == 'f' || ee == 'F') {
f = true;
} // end else if
else if (ee == 'l' || ee == 'L') {
l = true;
} // end else if
if (e == true && f == true && l == true) {
System.out.println("Your word is elfish!");
}
else if (n < userWord.length()) {
elfish(userWord, n + 1);
}
else
{
System.out.println("Your word isn't elfish.");
} // end if-else else
} // end elfish method
}// end class
I'm pretty sure it's because you don't terminate your recursion properly. In order to check the n+1 character, the current n has to be n-2 or the value of n+1 is going to be out of range. That's because charAt() is limited to at most n-1.
So you want to make sure that n is less than n-1 before you pass it.
else if (n < userWord.length()-1) {
elfish(userWord, n + 1);
Replace n < userWord.length() with n < userWord.length()-1
Why? If input word has 3 letters, the last index you can access of it is 2. But the length() method returs the number of lettets that string contains, and it cointains 3 letters.
So 2 < 3 == true and program calls the eflish function with n=3, and it throws Index Out Bounds Exception.

Validate User Input Using Java Chars and Strings

I have seen this asked 2x, but the correct response I need has not been addressed.
In this assessment,
you will design and code a Java console application that
validates the data
entry
of a course code (like IT4782)
and
report
back if the
course code is valid or
not
valid.
The
application
uses the Java char
and
String data types to implement
the validation.
You
can
use
either
the
Toolwire environment
or your
local
Java
development
environment
to complete this
assignment.
The requirements of
this application are
as follows:
The application is to read
a course code
entered
by the user
from the
keyboard.
The course code
is made
of 5 characters and should
follow
these
Rules:
First
character
is always
an
upper
case I
or a lower
case i
Second character
is always an upper
case
T or
a lower
case t
Third,
fourth,
fifth,
and sixth characters
are always digits (0-
9)
The application then validates the course code against
above the rules and prints a
message
If the
course code
is valid
or not.
If the course code is not
valid,
the application should print
a message
explaining why
the course
code is not
valid.
Output should look like this:
Here is my code, I cannot get the code to produce the pictured results. It outputs all the invalid messages.
package u4a1_validatecoursecode;
import java.util.Scanner;
public class U4A1_ValidateCourseCode {
public static void main(String[] args) {
// Larry Copy
Scanner s = new Scanner(System.in);
System.out.print("Enter a course code to validate (e.g. IT4782) : ");
String code = s.nextLine();
if (validateCode(code)) {
System.out.println("Course code: " + "" + code + "" + " is valid.");
} else {
System.out.println("Not valid code");
}
}
private static boolean validateCode(String code) {
if (code.length() != 6) {
return false;
} else {
//First character is always an upper case I or a lower case i
if (code.charAt(0) != 'I' && code.charAt(0) != 'i') {
return false;
}
System.out.println("integer is not an I or i");
// Second character is always an upper case T or a lower case t
if (code.charAt(1) != 'T' && code.charAt(1) != 't') {
return false;
}
System.out.println("integer is not a T or t");
// Third, fourth, fifth, and sixth characters are always digits (0-9)
if (!Character.isDigit(code.charAt(2))) {
return false;
}
System.out.println("integer 3 is not a number");
if (!Character.isDigit(code.charAt(3))) {
return false;
}
System.out.println("integer 4 is not a number");
if (!Character.isDigit(code.charAt(4))) {
return false;
}
System.out.println("integer 5 is not a number");
if (!Character.isDigit(code.charAt(5))) {
return false;
}
System.out.println("integer 6 is not a number");
return false;
}
}
}
When you return false; the code after is not executed so you'll never see why it returns
If you return only false the test will never pass, you need a variable to validate or not the code
If it goes in one if (not valid) you'll get the message, and the valid will be false
private static boolean validateCode(String code) {
if (code.length() != 6) {
return false;
} else {
boolean valid = true;
//First character is always an upper case I or a lower case i
if (code.charAt(0) != 'I' && code.charAt(0) != 'i') {
System.out.println("integer is not an I or i");
valid = false;
}
// Second character is always an upper case T or a lower case t
if (code.charAt(1) != 'T' && code.charAt(1) != 't') {
System.out.println("integer is not a T or t");
valid = false;
}
// Third, fourth, fifth, and sixth characters are always digits (0-9)
if (!Character.isDigit(code.charAt(2))) {
System.out.println("integer 3 is not a number");
valid = false;
}
if (!Character.isDigit(code.charAt(3))) {
System.out.println("integer 4 is not a number");
valid = false;
}
if (!Character.isDigit(code.charAt(4))) {
System.out.println("integer 5 is not a number");
valid = false;
}
if (!Character.isDigit(code.charAt(5))) {
System.out.println("integer 6 is not a number");
valid = false;
}
return valid;
}
}
You are using too much line of code:
Here what I do:
private static boolean validateCode(String code,String validCode) {
boolean b=true;
if (code.length() != 6) {
return false;
}
for(int i=0;i<code.length();i++){
if(code.toLowerCase().charAt(i)!=validCode.toLowerCase().charAt(i) && i<2){
System.out.println("Character at "+i+" position is not an "+ validCode.charAt(i));
b= false;
}
if(Character.isDigit(code.charAt(i)) && i>2){
System.out.println("Character at "+i+" is not a digit");
b= false;
}
}
return b;
}

Password input rules

import java.util.Scanner;
public class Exercise6_18 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Password rules:\n"
+ "Password must have at least eight characters\n"
+ "Password must consist of only letters and digits\n"
+ "Password must contain at least two digits\n"
+ "Enter a password:");
String pWT = sc.next();
passWordIsValid(pWT);
}
public static void passWordIsValid (String password) {
boolean passWordIsValid;
if (password.length() < 8) {
passWordIsValid = false;
}
else if (password.indexOf(0) == -1 && password.indexOf(1) == -1
&& password.indexOf(2) == -1 && password.indexOf(3) == -1
&& password.indexOf(4) == -1 && password.indexOf(5) == -1
&& password.indexOf(6) == -1 && password.indexOf(7) == -1
&& password.indexOf(8) == -1 && password.indexOf(9) == -1) {
passWordIsValid = false;
}
else
passWordIsValid = true;
if (passWordIsValid == true)
System.out.print("Password is valid");
else if (passWordIsValid == false)
System.out.println("Password is invalid");
}
}
I am trying to write a program that prompts the user to enter a password that is at least 8 characters long, contains at least two digits and is comprised of only letters and digits but when I enter: password12 it says password is invalid. P.S. I know I haven't added the requirement for at least two digits in the method.
...else if (password.indexOf(0) == -1 && password.indexOf(1) == -1
&& password.indexOf(2) == -1 && password.indexOf(3) == -1
&& password.indexOf(4) == -1 && password.indexOf(5) == -1
&& password.indexOf(6) == -1 && password.indexOf(7) == -1
&& password.indexOf(8) == -1 && password.indexOf(9) == -1) {
passWordIsValid = false;
}...
What are you trying to achieve with this code? It doesn't make any sense at all. You probably want to loop over every character of the string instead while counting for every character if it is a digit (and you could "break;" out of the loop as soon as your count is >=2).
Also: Don't save passwords in strings... they will stay in the string pool for quite a while and can be read from memory by malicious programs. You can use a char[] instead.
If you do not want to use Regex, you can use a simple for loop and if statement, you may do something like this:
import java.util.Scanner;
public class PromptPassword {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("Password rules:\n"
+ "Password must have at least eight characters\n"
+ "Password must consist of only letters and digits\n"
+ "Password must contain at least two digits\n"
+ "Enter a password:");
String pWT = sc.nextLine(); //read the entire line
passWordIsValid(pWT.trim()); // to remove leading spaces (if any)
}
public static void passWordIsValid (String password) {
boolean passWordIsValid = true;
int noOfDigits =0;
if (password.length() > 8) { // if it's less than 8 chars -> no need to continue
for(char c : password.toCharArray()){
if(Character.isDigit(c)){ // if it's a digit, increment
noOfDigits++;
}
else if(!Character.isAlphabetic(c)){ // if it's not a digit nor alphapet
passWordIsValid = false;
break;
}
}
}
if (passWordIsValid && noOfDigits>=2){
System.out.print("Password is valid");
}
else{
System.out.println("Password is invalid");
}
}
}
Test
Enter a password: abcd12 -> Password is invalid (less than 8)
Enter a password: abcde#123 -> Password is invalid (contains special char)
Enter a password: abcdefghi1 -> Password is invalid (less than 2 digits)
Enter a password: abcdefg12 -> Password is valid (9 in length and contains 2 digits and no special chars)
Your algorithm will not check whether there are at least two digits, and will not check that there are only printable characters and digits in it. Instead of checking for indexOf() you need to loop through all of the characters and count the number that are digits, and ensure each one is either a digit or an alphabetic character, keeping track of the number that are digits.
Use Regex to validate password. positive Lookahead does very good job at validating strings.
Example in java
public static void main(String[] args) {
String passwd = "aaZZa44#";
String pattern = "^(?=.*[0-9].*[0-9])(?=.*[a-z])(?=.*[A-Z]).{8,}$";
System.out.println(passwd.matches(pattern));
}
(?=.*[0-9].*[0-9]) at least 2 digits.
(?=.*[a-z]) lower case a-z
(?=.*[A-Z]) upper case A-Z
{8,} 8 digit in length

Input String with if doesn't work

I have following problem:
The user has to put his name correctly in my program:
the name only contain letters, hyphens "-" and blanks " "
the first letter should be a capital letter.
after a blank or hyphens should be followed by a capital letter.
For example only this form should be accepted by the program:
"Name" or "Firstname-Secondname" or "Firstname Secondname".
The 3rd point doesn't work in my code:(
My Java code:
public class Test {
private static Scanner scanner = new Scanner(System.in);
private static String name;
public static void main(String[] args) {
boolean check = false;
check = checkName();
System.out.println("Check= "+check);
output(check);
}
public static void output(boolean check) {
if (check == false) {
System.out.println("Fehler");
}
if(check == true) {
System.out.println("Dein Name ist: "+name);
}
}//End output()
public static boolean checkName() {
System.out.print("Name: ");
name = scanner.nextLine();
boolean check = false;
if(name.charAt(0) >= 'A' && name.charAt(0) <= 'Z') {
for(int i=1; i < name.length(); i++) {
if (name.charAt(i) >= 'a' && name.charAt(i) <= 'z') {
check = true;
} else if (name.charAt(i) == '-') {
i++;
if(name.charAt(i) >= 'A' && name.charAt(i) <= 'Z') {
check = true;
} else {
check = false;
}
} else if (name.charAt(i) == ' ') {
i++;
if(name.charAt(i) >= 'A' && name.charAt(i) <= 'Z') {
check = true;
} else { check = false;
}} else {
check = false;
break;
}
}
} return check;
}//End checkName()
Can someone help please?
This looks like a good place to use a regular expression. What about the following example:
String name = scanner.nextLine();
if (Pattern.compile("^[A-Z][a-z]*(?:(?: |-)[A-Z][a-z]*)?$").matcher(name).find()) {
// Valid Name
}
This checks the variable name against a regular expression to see if it matches. To explain the regular expression:
^ This means start of string.
[A-Z][a-z]* This means an uppercase letter followed by zero or more lowercase letters.
((?: |-)[A-Z][a-z]*)? This means followed by a space or hyphen with an uppercase followed by an optional lowercase character - this section is optional as the group is followed by a ?.
$ This means end of string.
You can also use String.matches() which is simpler, instead of Pattern.compile().matcher().

Java: checking if a phone number fits a valid format

I am trying to find if a phone number fits the format (xxx)xxx-xxxx where x is a digit. First, I have the program for the length and the '(',')', and '-'. When I type in something that doesn't work, I get the logical output. However, when I type in a properly formatted number, my program doesn't return anything.
import java.util.Scanner;
public class Program04 {
public static void main(String args[])
{
Scanner stdIn = new Scanner(System.in);
String pN;
System.out.print("Please enter a phone number (ddd)ddd-dddd :");
pN = stdIn.nextLine();
char a = pN.charAt(1);
char b = pN.charAt(2);
char c = pN.charAt(3);
char d = pN.charAt(5);
char e = pN.charAt(6);
char f = pN.charAt(7);
char g = pN.charAt(9);
char h = pN.charAt(10);
char i = pN.charAt(11);
char j = pN.charAt(12);
if (pN.length() == 13 && pN.charAt(0)=='(' && pN.charAt(4)== ')' && pN.charAt(8)=='-')
{
if (a>=0 && a<=9)
{
if (b>=0 && b<=9)
{
if (c>=0 && c<=9)
{
if (d>=0 && d<=9)
{
if (e>=0 && e<=9)
{
if (f>=0 && f<=9)
{
if (g>=0 && g<=9)
{
if (h>=0 && h<=9)
{
if (i>=0 && i<=9)
{
if (j>=0 && j<=9)
{
System.out.print("This is a valid phone number!");
}
}
}
}
}
}
}
}
}
}
}
else System.out.println("Not a vaid phone number.");
}
}
It's easier to use pattern-matching (regex) for validation:
...
pN = stdIn.nextLine();
System.out.println(pN.matches("\\(\\d{3}\\)\\d{3}-\\d{4}"));
Even if you want to have it check if each character is a digit, using so many nested if's is not the way to go. Instead, define a simple method that applies the check, say:
private static boolean isDigit(char x) {
return x>=0 && x<=9;
}
and then do:
if ( isDigit(a) && isDigit(b) && ...) {
return true;
}
else {
return false;
}
If you're not allowed to use RegEx or if it is too difficult to understand, try simplifying your nested if's by a simple switch inside a loop, it is much more readable and maintenance is the easiest :
public static void main(String[] args) {
String pn = scan.nextLine();
boolean valid = true;
if (pn.length() == 13){
for (int i = 0 ; i < 13 ; i++){
switch(i){
case 0 : valid = pn.charAt(0) == '(';break;
case 4 : valid = pn.charAt(4) == ')';break;
case 8 : valid = pn.charAt(8) == '-';break;
default : valid = Character.getNumericValue(pn.charAt(i)) >= 0 && Character.getNumericValue(pn.charAt(i))<= 9 ; break;
}
if (!valid) break;
}
if (!valid) System.out.println("Invalid number");
}else{
valid = false;
System.out.println("Invalid length");
}
if (valid){
System.out.println(pn + " is a valid telephone number");
}
}
Also, to avoid working with the ASCII value of a char, try using the Character.getNumericValue(Char c) method. It returns a numeric that you can use for your tests, like above.
It is better to use regex in this case:
You can use following :
String pattern = "(\\(\\d{3}\\)\\d{3}-\\d{4})";
Pattern r = Pattern.compile(pattern);
pN = stdIn.nextLine();
Matcher m = r.matcher(pN);
if (m.find( )) {
System.out.println("Found value: " + m.group(0) );
} else {
System.out.println("NO MATCH");
}

Categories