0

I'm not the best programmer and am quite new to it. I've been trying for hours to get this program correct but I can't seem to come up with a way to make it work out the way I'd like to. Here's what I want to do:

Write a program that prompts a user for their name and then displays "Hello, [Name Here]!"

If the user does not enter anything but pressed Enter anyways, you should re-prompt for the user's name. This flow should look like the following:

Whats is your name?
Please Enter your name: 
Please Enter your name: Programming Practice
Hello, Programming Practice!

Here's how I'm thinking of the program before I start writing anything in my IDE:

  1. Ask the user for their name
  2. Give them a chance to enter their name
  3. If their entry is not in name format, give them output saying incorrect format
  4. Give them a chance to enter in proper format
  5. Repeat steps 4 and 5 as many times as it takes for them to enter proper format
  6. Print "Hello, [Name Here]!"
  7. END

Here's what I've got so far:

package lol;
import java.util.Scanner;
public class Whatever {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in); 

        System.out.printf("What is your name?\n"); 

        String name = sc.nextLine(); 

        if (name != "Programming Practice")
        {
            System.out.println("Please enter a valid name");
            String name2 = sc.nextLine();
            System.out.println("Hello, " + name2 );
        }

        else
        {

        System.out.println("Hello, " + name ); 
        }

    }
}

Right now the output I'm getting regardless of my entries are:

What is your name?

Please enter a valid name

Hello,
mate00
  • 2,727
  • 5
  • 26
  • 34
  • *"Repeat steps 4 and 5 as many times as it takes"* This implies some kind of **loop**. I see no loop in your code. You do know how to write a `while` or `do-while` loop, right? – Andreas Aug 29 '19 at 03:48
  • 1
    `if (name != "Programming Practice")` is bad, see "[How do I compare strings in Java?](https://stackoverflow.com/q/513832/5221149)" – Andreas Aug 29 '19 at 03:49

2 Answers2

1

You can throw the sc.nextLine() into a while(true) loop and break out when you get a result you deem valid.

String name = "";

while(true) {
    name = sc.nextLine();
    if (name.equals("Programming Practice")) { 
        System.out.println("Hello, " + name); 
        break;
    } else {
        System.out.println("Please enter in the correct format");
        continue;
    }
}
Mike
  • 1,471
  • 12
  • 17
1

A better way of approaching this problem would be by using do-while loop.

do {
 // Your processing
} while (checkCondition());

The logic is based on the idea that the user will be prompted to enter details at least once.

Prashant
  • 4,775
  • 3
  • 28
  • 47