1

I'm trying to see if the user typed in a string or not, If they did not I want the program to keep asking for the user's name.

public static void main(String[] args) {
    // TODO code application logic here
    Scanner myObj = new Scanner(System.in);  // Create a Scanner object
    System.out.println("Hello Shopper, what is your name?");
    String Name = myObj.nextLine(); // Read user input

    System.out.println("Thank you, " + Name + " It is my pleasure to shop with you today.");
    System.out.println("Press enter to exit");
    String exit = myObj.nextLine();
    System.exit(0);// Output user input
}

}

user158
  • 12,852
  • 7
  • 62
  • 94
kent berg
  • 19
  • 2
  • `System.exit(...);` serves no purpose at all if it is at the end of the program. The program would end naturally anyways. Also note that you should not use it in general, instead let your program flow naturally end. – Zabuzard Oct 18 '19 at 05:33

2 Answers2

2

Java 8 lambda expressions. Both fast and simple.

String name = "";
boolean allLetters = false;
{
  name = myObj.nextLine();
  allLetters = name.chars().allMatch(Character::isLetter);
} while(!allLetters)
sovannarith cheav
  • 743
  • 1
  • 6
  • 19
0

Basically your program is accepting a string input itself as you have coded it in. If the user enters any value it will be taken in as string input itself. you can further check if the string is a number or not by using isDigit(), isNumeric() etc. perform not operation to these methods and you'll have a name input only (special characters included).

Kartik
  • 7,677
  • 4
  • 28
  • 50