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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!