-1

I am a beginner in Java, I have written a simple input java program. I am giving the user the option to repeat the program with a do while, however it's not properly functioning. Can someone point my mistake please?

public static void main(String args[]){
    char repeat = 0;
    Scanner input = new Scanner(System.in);
    do{ 
        String word = null;
        boolean oneWord = false;
        while(!oneWord){
            System.out.println("Please enter a word: ");
            try{
                word = input.nextLine().toLowerCase();
                word= word.trim();
                int words = word.isEmpty() ? 0 : word.split("\\s+").length;
                if(words==1 && word.length()>1 && word.length()<100){
                    System.out.println("Success");
                    oneWord = true;
                    System.out.println("Continue(Y/N)");
                    repeat = input.next().charAt(0);
                }else{
                    System.out.println("Failure.");
                }
            } catch (Exception e) {
                System.out.println("Exception occurred");
            }
        }
    }while(repeat=='Y'|| repeat=='y');
    input.close();
}
Arun Sudhakaran
  • 1,833
  • 2
  • 16
  • 41
JamesAB
  • 13
  • 2
  • 4
    what is not functioning properly? – XtremeBaumer Feb 06 '18 at 09:14
  • Could you describe what you are expecting from it? Then we will be able to help you. – Tomasz Bawor Feb 06 '18 at 09:14
  • When I input y, the output is: Please enter a word: Failure. Please enter a word: – JamesAB Feb 06 '18 at 09:15
  • Welcome to Stack Overflow! Please take the [tour](/tour), have a look around, and read through the [help center](/help), in particular [How do I ask a good question?](/help/how-to-ask) and [What topics can I ask about here?](/help/on-topic). From that second link: "Questions asking for homework help must include a summary of the work you've done so far to solve the problem, and a description of the difficulty you are having solving it." – Timothy Truckle Feb 06 '18 at 09:15

2 Answers2

1

I would suggest you using nextLine() function of Scanner class instead of next() function.

See the difference here

Sushil Jain
  • 299
  • 4
  • 11
0

Even tho its a duplicate, have a look at the line

repeat = input.next().charAt(0);

and change it to

repeat = input.nextLine().charAt(0);

This will solve your problem. For further information regarding the problem, read the duplicate link.

XtremeBaumer
  • 5,158
  • 1
  • 15
  • 44