0

This is a silly game written in Python, I was wondering how to reproduce it in Java:

name = ''

while name != 'your name': 
   print('Please type your name.')
   name = input()

print('Thank you!')

Basically, it requests to write the string "your name" to break the while loop, now, I've tried this code in Java but it throws an error:

import java.util.Scanner;

public class sillyGame {

  public static void main(String [] args) {
    String name = "";

    while (name != "your name"){
      System.out.println("Please type your name");
      Scanner input = new Scanner(System.in);
      name = input.next();
      input.close();
    }

    System.out.println("thank you");
  }
}

The error is: "Exception in thread "main" java.util.NoSuchElementException"

I really appreciate your help.

Ismael Padilla
  • 5,246
  • 4
  • 23
  • 35
Cristian Diaz
  • 315
  • 1
  • 3
  • 11
  • 2
    `!name.equals("your name")` **and** remove `input.close()`. – Elliott Frisch Aug 23 '21 at 03:53
  • 1
    To get rid of the `Exception`, you can move the `Scanner` declaration to the top of the `main` method and remove `input.close();` line. use `name = input.nextLine()` insted of `name = input.next()` because `next()` method will only consider the input till a space, `nextLine()` method will consider the input till `\n`. put this condition in while loop `!name.equals("your name")` since `name != "your name"` compares the address not the values in java. – Mahesh Aug 23 '21 at 04:21
  • @Mahesh and Elliot, Thanks a lot for your insight, now the code runs great and I've learned important points in the process – Cristian Diaz Aug 23 '21 at 13:10

0 Answers0