How to get the Java Scanner utility to input twice - java

so heres my code
public class Practice01{
public static void main (String[] args){
System.out.println("Hi there");
Scanner scr = new Scanner(System.in);
String response = scr.nextLine();
if (response.equalsIgnoreCase("hello") || response.equalsIgnoreCase("hi") || response.equalsIgnoreCase("hey")) {
System.out.println("Oh, well arent you well-mannered. Hello there, how are you?");}
else {
System.out.println("Invalid Input");
String responseG;
responseG = scr.nextLine();
if (responseG.equalsIgnoreCase("good")) {
System.out.println("Glad to hear");
}
}
}
}
im a bit of a noobie when it comes to java, I just started today, but after the else statment here, java terminates itself for some reason, and it just doesnt care about the rest of the code. I was looking online and I saw that if you wanted to take another input you used the .nextLine(); function (i dont think its called a function but you know what I mean) but after I type either hey, hello, or hi, it prints "Oh, well arent you well-mannered. Hello there, how are you?" and then I cant type anything else, and it says < terminated > . can anyone help? thanks
Edit: Apparently I'm supposed to move the "responseG" variable and next line into the if statment. When I do that it doesnt activate, (using eclipse IDE, and it just appears as white and as an error) and tells me to delete else. https://gyazo.com/1a27fa9ab8802d594cccb35ecc0cb663 picture of what happens. furthermore if i try to use an else if statment it also says to delete it

Hi, welcome to Stackoverflow!
Your program will only ask for another input from your keyboard if you don't type "hello" or "Hello", or "hey", you know what I mean. If you type "hello" then it will print a line with
"Oh, well aren't you well-mannered. Hello there, how are you?"
And the program will be terminated...
That's what your code it's telling your program to do, since you are only asking for another input in the else statement's body.
As I can see you don't want to use a for loop, since you seem to only care about a path that says hi... how are you?... good... glad to hear... but if you care for it, you can use a while() statement or a do..while() or a for() to make it save in the variable many responses with the scr.nextLine(); function (it is a function), in that case you have to define when/how the program is going to stop asking for input and will terminate.
I believe this is what does what you were trying to do, with the proper indentation, and not declaring unnecessary variables:
public class Practice01{
public static void main (String[] args){
System.out.println("Hi there");
Scanner scr = new Scanner(System.in);
String response = scr.nextLine();
if (response.equalsIgnoreCase("hello") || response.equalsIgnoreCase("hi") || response.equalsIgnoreCase("hey")) {
System.out.println("Oh, well arent you well-mannered. Hello there, how are you?");
}
else {
System.out.println("Invalid Input");
}
//You don't need ResponseG... you've already created the response variable
response = scr.nextLine();
if (response.equalsIgnoreCase("good")) {
System.out.println("Glad to hear");
}
else {
System.out.println("Invalid Input");
}
}
}

You have to use a loop to keep the program working. After you get "Oh, well aren't you well-mannered. Hello there, how are you?" printed, it terminates the fact that there is no more tasks to do.

So what you want to do is move the ResponseG if statement into the your response if statement as that is stopping the code from complete since you are putting in the correct inputs. Also for future projects, to be more organized create variables at the beginning of the code.
public class Practice01{
public static void main (String[] args){
System.out.println("Hi there");
String responseG;
Scanner scr = new Scanner(System.in);
String response = scr.nextLine();
if (response.equalsIgnoreCase("hello") ||
response.equalsIgnoreCase("hi") ||
response.equalsIgnoreCase("hey")) {
System.out.println("Oh, well arent you well-mannered. Hello there, how are you?");
responseG = scr.nextLine();
if (responseG.equalsIgnoreCase("good")) {
System.out.println("Glad to hear");
}
} else {
System.out.println("Invalid Input");
}
}
}

Related

Im trying to make a text based game that looks like a PC terminal, i cant find a way to tell the user if they use a wrong sentence

//Code up
if (userinput.contains(help)) {
//Go on with the game
}
else {
System.out.println("Im sorry , couldnt understand that"); //here is where i want to go back up and
repeat the command
}
I tried almost everything a beginner would know and nothing , do while loops not working in my case (maybe you can find a way) , if i let the if like that the game closes if you get the wrong answer (something out of conttext) , some help would be great! Thx :D
You could use a 'Recursive' function (a function that calls itself).
So in this case, you could do something like:
public void getAndParseInput(){
String userInput = getUserInput() // Use whatever you're using to get input
if(userInput.contains(help)){
// If the user input contains whatever the help is (note: if you're looking for the specific word help, it needs to be in speech marks - "help").
continueWithGame...
}else{
System.out.println("Im sorry , couldnt understand that");
this.getAndParseInput();
}
}
You need to put that code inside a while loop and establish an exit condition.
boolean endGame = false;
/* Here read userinput */
While(!endGame) {
if (userinput.contains(help)) {
//Go on with the game
} else if(userinput.contains("quit"){
endGame = true;
} else {
System.out.println("Im sorry , couldnt understand that"); //here is where i want to go back up and
repeat the command
}
/* Here read userinput */
}
The Below code is similar to your code,reuse the code with appropriate changes as you required.
The code works as below.
1. Scans the input from the console
2. Compares the scanned input with the String "help"
3. If scanned input matches with help, then continue with the execution
4. Otherwise, if the user wants to continue then he can press the
letter 'C' and continues with the execution.
5. If user doesn't press 'C', then the control breaks the while loop
and comes out of the execution
public void executeGame() {
Scanner scanner = new Scanner(System.in);
String help = "help";
while(true) {
System.out.println("Enter the input for execution");
String input = scanner.nextLine();
if (input.contains(help)){
System.out.println("Continue execution");
} else {
System.out.println("Sorry Wrong input.. Would you like to continue press C");
input = scanner.nextLine();
if (input.equals("C")){
continue;
} else {
System.out.println("Sorry wrong input :"+input);
System.out.println("Hence Existing....");
System.exit(0);
}
}
}
}

Java: how to reject incorrect input and wait for proper input using Scanner

This is the basic setup for a little console-based quiz game. The answers are numbered. I want the player to give the answer number. If the input is not a number, then my program should give a warning, and wait for proper input.
Instead, what I get (after inserting something that is not a number) is an infinite loop of asking the question and presenting the answers again.
public static void main(String[] args) {
boolean quizActive = true;
while(quizActive) {
presentQuestion();
presentAnswers();
Scanner s = new Scanner(System.in);
if (s.hasNext()) {
String choice = s.next();
if (!NumberUtils.isNumber(choice)) {
presentText("Please insert the answer number.");
} else {
System.out.println("You made a choice!");
checkAnswer(choice);
quizActive = false;
}
s.close();
}
}
}
What am I doing wrong here?
If you do not want to question and answers be presented each time move presentQuestion() and presentAnswers() outside the loop.
But main problem is that you closing Scanner.
Remove s.close(); and move Scanner s = new Scanner(System.in); outside of the loop.
I really don't get the point in using scanner for acquiring user input.
The scanner class is perfect to process structured input from a flat file with known structure like an CSV.
But user input need to deal with all the human imperfection. After all the only advantage you get is not needing to call Integer.parseInt() your yourself at the cost to deal with the not cleared input when scanne.nextInt() fails...
So why not using InputStreamReader aside with a loop suggested by others?
Here an Example :
public class Application {
public static void main(String [] args) {
System.out.println("Please insert the answer number. ");
while (true) {
try {
Scanner in = new Scanner(System.in);
int choice = in.nextInt();
System.out.println("You made a choice!");
checkAnswer(choice);
break;
} catch (Exception e) {
System.out.println("Invalid Number, Please insert the answer number ");
}
}
}
}
You started your Quiz in a loop which is regulated by your quizActive boolean. That means that your methods presentQuestion() and presentAnswers() get called every time the loop starts again.
If you don't input a number but a character for example, your program will run the presentText("Please insert the answer number.") and start the loop again. As it starts the loop again, it will call the methods presentQuestion() and presentAnswers().
To stop that, you can do another loop around the input-sequence. Also your Scanner s = new Scanner(System.in) should be outside the loop. And you shouldn't close your Scanner right after the first input and then open it again!
if you want a code example, please tell me :)

Restarting program from a certain point after an if

I started studying Java not too long ago, I am currently trying to make a little game to see if I got the things I saw right.
I want to make a "game" that let's you choose between two dialogue options which have different consequences.
This is the code I used:
package programs;
import java.util.Scanner;
public class Programma1_0 {
public static void main(String[] args) {
System.out.println(
"You wake up in a laboratory. You don't remember ever being there. You actually don't remember anything.");
System.out.println("A door opens, a girl comes towards you.");
System.out.println("Girl:<<Hi, I see you woke up. How are you feeling?>>");
System.out.println("(Write Good or Bad)");
Scanner first = new Scanner(System.in);
String firstch = first.nextLine();
if (firstch.equals("Good")) {
System.out.println("Great, we have a lot to explain.");
} else if (firstch.equals("Bad")) {
System.out.println("You should be alright in an hour or so. You've slept for a long time.");
} else {
System.out.println("(I told you to write Good or Bad)");
}
}
}
So far it's working as intended. The only problem is that if I write something other than Good or Bad i get the message "(I told you to write Good or Bad)" and the program terminates. Is there a way to automatically restart it? If i put more choices in, I want the program to automatically restart from the question where it terminated (So I don't play through half of the game, get a question wrong and have to restart the program from the start), is that possible?
Thanks.
You can accomplish this by putting this before your if statement.
while (true) {
if (firstch.equals("Good") || firstch.equals("Bad"))
break;
else {
System.out.println("(I told you to write Good or Bad)");
firstch = first.nextLine();
}
}
Then you can also remove the last else part of your if statement.
Now it will continue asking for a new input till it gets either "Good" or "Bad"
You can simply put your if-else statement inside the do-while loop, that way you can loop through until you get correct response
int i = 0;
do {
System.out.println("(Write Good or Bad)");
firstch = first.nextLine();
if (firstch.equals("Good")) {
System.out.println("Great, we have a lot to explain.");
i = 0;
} else if (firstch.equals("Bad")) {
System.out.println("You should be alright in an hour or so. You've slept for a long time.");
i = 0
} else {
System.out.println("(I told you to write Good or Bad)");
i = 1;
}
} while (i == 1);
You can partition your program into separate methods. Here I created a method called retrieveAnswer() which its only task to create a Scanner and get input. This method will return a String as seen in the public static String header.
Another method I created was entitled getResult() which takes a String argument and will now compare the String passed from
String firstch = retrieveAnswer();
getResult(firstch);
If the result goes to the else block, it will call retrieveAnswer() and pass the value returned to getResult() as seen in getResult(retrieveAnswer()) which will then restart the whole process.
There are multiple solutions to this, but I just took the recursion route instead. Good luck with Java! If you are confused, look more into methods as they are VERY essential in programming.
import java.util.Scanner;
public class Source {
public static void main(String[] args) {
System.out.println(
"You wake up in a laboratory. You don't remember ever being there. You actually don't remember anything.");
System.out.println("A door opens, a girl comes towards you.");
System.out.println("Girl:<<Hi, I see you woke up. How are you feeling?>>");
System.out.println("(Write Good or Bad)");
String firstch = retrieveAnswer();
getResult(firstch);
}
public static String retrieveAnswer(){
Scanner first = new Scanner(System.in);
String firstch = first.nextLine();
return firstch;
}
public static void getResult(String firstch){
if (firstch.equals("Good")) {
System.out.println("Great, we have a lot to explain.");
} else if (firstch.equals("Bad")) {
System.out.println("You should be alright in an hour or so. You've slept for a long time.");
} else {
System.out.println("(I told you to write Good or Bad)");
getResult(retrieveAnswer());
}
}
}

Abbreviation Decoder Script in Java

I am working on a program that is supposed to pull abbreviated text meanings from a list that is created from if-else statements. I am running into trouble with the logic of making the program see an incorrect input and provide a suggestion from the supported list. Here is the code we were given to edit.
import java.util.Scanner;
public class TweetDecoder {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String origTweet = "";
System.out.println("Enter abbreviation from tweet: ");
origTweet = scnr.next();
if (origTweet.equals("LOL")) {
System.out.println("LOL = laughing out loud");
}
else if (origTweet.equals("BFN")) {
System.out.println("BFN = bye for now");
}
else if (origTweet.equals("FTW")) {
System.out.println("FTW = for the win");
}
else if (origTweet.equals("IRL")) {
System.out.println("IRL = in real life");
}
else {
System.out.println("Sorry, don't know that one.");
}
return;
}
}
This is for a class so I would like to know if someone can push me in the right direction rather than give the full answer or the string that I should be using. I feel like is should be something to do with String Comparison or String Access Operations but I cant seem to get it nailed down. If someone can assist I would greatly appreciate it. Thank you in advance!
it wouldn't let me add a comment, so i suppose here will do.
I would suggest looking into the .startsWith method. Its a method contained in the String class.
For example,
if(origTweet.startsWith("L")) //
System.out.println("Perhaps you meant LOL");
sorry if this isn't what you meant / wanted

about java scanner. Error: java.util.NoSuchElementException: No line found

I'm a oversea student. I use blueJ do my assessment. My code could run in terminal well, but after I submit my assessment the page response fails and shows
java.util.NoSuchElementException: No line found
My code:
public void input() {
Scanner keyboard = new Scanner(System.in);
System.out.print("Move (l/r/u/d): ");
String name = keyboard.nextLine();
if(name.equals("l")) {
move(-1,0);
}
else if(name.equals("r")) {
move(1,0);
}
else if(name.equals("u")) {
move(0,-1);
}
else if(name.equals("d")) {
move(0,1);
}
else {
System.out.println("Invalid move");
}
}
I suggest that you read the requirements for your assignments again carefully.
The symptoms clearly indicate that your program is being tested in a context in which there is no input to be read from System.in. The most obvious explanation is that your program is supposed to be getting its input some other way. But unless we see the requirements, we cab only guess what it is supposed to do.
I guess another possibility is that the program that is testing your assignment code is faulty.
By seeing the error line not found,u replace print() into println().

Categories

Resources