Question
I need my Java program to ONLY accept letter inputs from the scanner . So if a user enters numbers like 1234567 or special characters
I need my Java program to ONLY accept letter inputs from the scanner. So if a user enters numbers like 1234567 or special characters like !#&()_@" the program will end and not crash and will just display an error message before ending. The program should allow spaces
I would like help on how to do this with my example code.
2) ALSO in another second program I want to know how to do this with it instead prompting the user to try again one more time and loops back to ask the user to input a valid string before ending the program. I am a beginner and would like simple code, but if it is complex can you please comment on what the code is doing?
3) AND A LAST THIRD THING. I want to know how to make the code loop and keep asking for input until it is correct so the program does not end. Please help me understand thank you! This is not a homework assignment just a learning question.
My example code:
import java.util.*;
public class LettersOnly {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a string: ");
int string = input.nextString();
if(){
*something*
System.out.println("Invalid string. Use only letters and spaces."
}else{
System.out.println(string);
}
}
}
**Second code to prompt user to enter string again after first invalid attempt before ending code if attempt is invalid. (I shortened my syntax to get my point across)
import java.util.*;
public class LettersOnly {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a string: ");
int string = input.nextString();
if(){ //some kind of loop here
string is invalid
print ("invalid string. please use letters and spaces only. Try again.)
*something*
}
if else(second attempt failed program will now end){
}else{ //if input is valid on first or second attempt the code will continue
System.out.println(string);
}
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started