Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Your program will need a loop to check the characters of the String entered by t

ID: 3925477 • Letter: Y

Question

Your program will need a loop to check the characters of the String entered by the user. You can extract a character as a char variable using the charAt( position ) method of a string where position is the character position in the string starting at zero. Once you have extracted a character from the String, you can determine if it is a numerical digit with the static boolean method Character.isDigit( courseChar ) where courseChar is the char extracted from the String. This method will return true if courseChar is a number. If it is, you should use that digit to determine the course level. Note that unlike Strings, you can compare char variables with the usual double equals sign, such as

if ( courseChar == '3')
Remember to break from the loop once you have found the first numerical digit.

If the first numerical digit is not 1 to 4 or if there is no numerical digit, your program can respond in any way you want, except to get a program error.

Explanation / Answer

import java.util.Scanner;
class Main {
public static void main(String[] args) throws Exception {
   Scanner sc = new Scanner(System.in);                       // scanner to get user input
   String text;                                               // declare a text variable to store input
    System.out.print("Enter a string:");
    text = sc.next();
    char courseChar='';                                       // initilize courseChar to null
    boolean beginner = false;
    for(int i=0;i<text.length();i++){                           // for each character in text
        courseChar = text.charAt(i);                           // get char at i.
        if(Character.isDigit(courseChar)){                       // check if it is a digit
            if(courseChar == '1' || courseChar == '2' || courseChar == '3' || courseChar == '4'){ // courseChar is between 1 to 4
                beginner = true;
            }
           break;           // break loop as a digit is found
        }
    }
    if(beginner){                                       // if beginner is true print as beginner course
        System.out.println("beginner course");
    }
    else{                                               // print course number
        System.out.println("Course "+courseChar);
    }
sc.close();                           // close scanner
}
}

/* sample output

*/