0

A little bit confused...

EDIT: This problem below was already fixed, however I ran into another problem. This time is when I attempted to insert a user input for the string, "name". Usually, nextString() works, but it doesn't exist on here, so I used next() but it wouldn't let me enter a name. I'm working on a project where it involves the player entering strings to interact with the environment, and one of the thing I had in the background was an integer generating a random number to create a backstory. Whenever I run it however, I always get this message: "Seems like your program requires input", but it works fine. Here's a chunk of code for reference: String action, name; int score, randomStory; Scanner user = new Scanner(System.in); Random rand = new Random(); randomStory = rand.nextInt(3); if (randomStory == 0){ System.out.println("story1"); } else if (randomStory == 1){ System.out.println("story2"); } else if (randomStory == 2){ System.out.println("story3"); } else System.out.println("ERROR!"); Thanks in advance!

6th Jan 2017, 5:39 AM
JumperKru
JumperKru - avatar
7 ответов
+ 1
Remove "Scanner user = new Scanner(System.in);" line. Scanner class is used to read input that is given by the user. Since you instatiated Scanner class the compiler thinks that your code needs a input from the user (which actually it doesn't), that's why your are getting that message.
6th Jan 2017, 5:27 AM
Akash Middinti
0
Thanks!
6th Jan 2017, 5:32 AM
JumperKru
JumperKru - avatar
0
Scanner user = new Scanner(System.in); name = user.next(); //add this
6th Jan 2017, 5:50 AM
Akash Middinti
0
I tried as what you've said, and the results gave me an error. The error is: Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at Adventure.main(Adventure.java:36)
6th Jan 2017, 5:55 AM
JumperKru
JumperKru - avatar
0
close the scanner Scanner user = new Scanner(System.in); name = user.next(); user.close(); //add this and try.
6th Jan 2017, 5:59 AM
Akash Middinti
0
I tried adding user.close();, and it gave me an error: Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at Adventure.main(Adventure.java:36)
6th Jan 2017, 6:11 AM
JumperKru
JumperKru - avatar
0
Scanner user = new Scanner(System.in); if(user.hasNext()) //add this name = user.next(); user.close();
6th Jan 2017, 6:18 AM
Akash Middinti