Java won't respond to my input - java

I'm budding into java and I've been trying to write this basic program where it asks you a yes or no question, you give it an answer and then it does something based off that answer. currently my code is this.
import java.util.Scanner;
public class Main {
public static void main(String args[])
{
Scanner inputvar = new Scanner (System.in);
String yes, no;
System.out.println("Enter yes or no");
yes = inputvar.nextLine();
no = inputvar.nextLine();
if (inputvar.equals(yes))
{
System.out.println("You said yes!");
}
else if (inputvar.equals(no)){
System.out.println("You said no");
}
}
}
I don't get any errors when compiling but when I run the program It doesn't reply when I put anything in. It allows me to enter two lines of text then it terminates.

Your code yes, no variables are not correct, you invoke nextLine() twice in your code, that's why you are asked to enter inputs twice.
yes = inputvar.nextLine();
no = inputvar.nextLine();
inputvar is a Scanner instance, not a String object, you cannot try
inputvar.equals(yes)
You should only define:
String myInput = inputvar.nextLine();
and checks
if (myInput.equals("yes")){
//do some stuff
}else if(myInput.equals("no")){
//do other stuff
}

Scanner inputvar = new Scanner (System.in);
String yes, no;
System.out.println("Enter yes or no");
yes = inputvar.nextLine(); // You enter the first line
no = inputvar.nextLine(); // You enter the second line
if (inputvar.equals(yes)) // You try to compare an instance of
// Scanner with the firstline (not equal)
{
System.out.println("You said yes!");
}
else if (inputvar.equals(no)){ // You try to compare an instance of
// Scanner with the firstline (not equal)
System.out.println("You said no");
}
// You terminate the program
You should do something like:
String yes = "yes";
String no = "no";
String input = inputvar.nextLine();
if(yes.equals(input)) { [...]

You should change your code to this
Scanner inputvar = new Scanner (System.in);
String input;
System.out.println("Enter yes or no");
input = inputvar.nextLine();
if (input.equals(yes))
{
System.out.println("You said yes!");
}
else if (input.equals(no)){
System.out.println("You said no");
}
Hope this helps and best of luck.

Related

How to repeat a question to a user until while loop condition is false?

I'm bulding a console application where I am trying to force a user to enter an int as a possible answer to a question otherwise the same question is repeated to the user.Thus, the user cannot move on without entering the proper data type.
below is my sample code.
Scanner scanner = new Scanner(System.in);
int userInput = 0;
do {
AskQuestion();
if(scanner.hasNextInt()) {
userInput = scanner.nextInt();
}
}
while(!scanner.hasNextInt()) ;
While I know this can be done in C#, I'm not exactly sure how to do it in java without getting stuck in an infinite loop. How do I get my code to do what I want to do? Please help!
You can use something like this. It'a a pretty simple flag combined with the use of the Scanner class.
boolean flag = false;
int val = 0;
while(!flag){
System.out.println("Something");
if(sc.hasNext()){
if(sc.hasNextInt()){
val = sc.nextInt();
flag = true;
}
else{
sc.next();
}
}
}
Try this:
Scanner scanner = new Scanner(System.in);
int userInput;
while(true) {
AskQuestion();
if (scanner.hasNextInt()) {
userInput = scanner.nextInt();
break;
}
scanner.next(); // consume non-int token
}
Another alternative which utilizes the Scanner#nextLine() method along with the String#matches() method and a small Regular Expression (RegEx) to ensure that the supplied string does indeed contain all numerical digits:
Scanner scanner = new Scanner(System.in);
String userInput = "";
int desiredINT = 0; // Default value.
while (desiredINT == 0) {
AskQuestion();
userInput = scanner.nextLine();
if (userInput.matches("\\d+")) {
desiredINT = Integer.parseInt(userInput);
if (desiredINT < 1 || desiredINT > 120) {
System.out.println("Invalid Input! The age supplied is not "
+ "likely! Enter a valid Age!");
desiredINT = 0;
}
}
else {
System.out.println("Invalid Input! You must supply an Integer "
+ "value! Try Again...");
}
}
System.out.println("Your age is: --> " + desiredINT);
And the AskQuestion() method:
private void AskQuestion() {
System.out.println("How old are you?");
}
This is nice and short one
Scanner scanner = new Scanner(System.in);
do askQuestion();
while(!scanner.nextLine().trim().matches("[\\d]+"));
Tell me if you like it
Note it just tell you if number was an int , and keeps repeating if not, but doesn't give you that int back , tell me if you need that, i shall find a way
My solution might be a bit bloated, but I hope it's nice and clear what's going on. Please do let me know how it can be simplified!
import java.util.Scanner; // Import the Scanner class
class Main {public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
String unit;
// unit selector
while (true) {
System.out.println("Did you measure ion feet or meters? Type 'meters' or 'feet': ");
String isUnit = myObj.nextLine();
if (isUnit.equals("feet") || (isUnit.equals("meters"))) {
unit = isUnit;
break;
} else {
System.out.println("Please enter either 'meters' or 'feet'.");
}
}
System.out.println("Use selected " + unit);
}

JAVA - SCANNER to get user input

I have the following block code:
boolean run = true;
while (run) {
Scanner scanner = new Scanner(System.in);
// do something
System.out.println("Another action? [Y/N]");
while (!scanner.hasNext("[YyNn]")) {
System.out.println("Incorrect input");
scanner.next();
}
String choice = scanner.next();
if (choice.toLowerCase().equals("f"))
run = false;
scanner.close();
}
I want to perform something until the user types 'N'.
Currently, I'm able to run the while loop only one time.
The second time I'm not able to type my choice and I have the following error:
Another action? [Y/N] <--- here no chance to type choice
Incorrect input
java.util.NoSuchElementException
at java.util.Scanner.throwFor
at java.util.Scanner.next
What is wrong?
Thanks
EDIT: I think my problem is in "do something". It is in turn a sequence of user input where i close the scanner.
I took off the scanner.close(); and added "fF" to the pattern, it runs until I input f or F:
boolean run = true;
while(run){
System.out.println("Another action? [Y/N]");
while (!scanner.hasNext("[YyNnfF]")) {
System.out.println("Incorrehct input");
scanner.next();
}
String choice = scanner.next();
if(choice.toLowerCase().equals("f"))
run = false;
// scanner.close();
}
The problem in fact is in your while loop condition. Let's debug:
When you only input chars that do not match with the pattern [YyNn] all goes ok (user will always get the Incorrect input message). But when you give, let's say an Y, your while loop will stop but Y will not be consumed. Therefore, this char will be consumed in the next instruction, i.e. in String choice = scanner.next(); (if you print variable choice you will see it has an Y).
After this, we go to the next iteration. Because there are no input to be consumed, scanner.hasNext("[YyNn]") will be false. But your while loop condition is !scanner.hasNext("[YyNn]"), which give us a true and enters inside the loop. Inside the loop we have the instruction scanner.next(). Since there are no input to be consumed, BOOM, you get a java.util.NoSuchElementException, which says the following:
Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration.
Other of your problems is in your scanner position. At each iteration you are initializing a new instance and closing it. You could just move the scanner initialization and its closure outside the loops.
Below I provide a similar sample code that does what you want with some explanations.
FULL CODE
public static void main(String[] args) {
boolean run = true;
Scanner scanner = new Scanner(System.in); // Init before loops
String userInput = ""; // tmp var that holds input
while (run) {
// do something
System.out.println("Another action? [Y/N]");
userInput = scanner.next(); // Read first time
// Run while user does not put Y || y || N || n
while (!userInput.matches("[YyNn]")){
System.out.println("Incorrect input");
userInput = scanner.next();
}
// User does not want more actions
if(userInput.matches("[Nn]")){
System.out.println("Do you wish to exit the program? [Y/Any other key]");
String choice = scanner.next();
// Stop the program
if (choice.toLowerCase().equals("y"))
run = false;
}
}
scanner.close(); // Close scanner outside
}
Hope it helped!
I think you should change some lines of code like this
Scanner scanner = new Scanner(System.in);
char choice = 'Y'
while(choice!='n'){
// do something
System.out.print("Another action? [Y/N]");
choice = scanner.nextLine().toLowerCase().charAt(0);
if(choice!='y' || choice!='n'){
continue;
}
}
scanner.close();
If you call the scanner.close() method ,System.in will be closed.
So Use this. Close the scanner outside the loop.
public static void main(String[] args) {
boolean run = true;
Scanner scanner = new Scanner(System.in);;
while(run){
// do something
System.out.println("Another action? [Y/N]");
while (!scanner.hasNext("[YyNn]")) {
System.out.println("Incorrect input");
scanner.next();
}
String choice = scanner.next();
if(choice.toLowerCase().equals("f"))
run = false;
//
}
scanner.close();
}
Output
Another action? [Y/N]
Y
Another action? [Y/N]
Y
Another action? [Y/N]
N
Another action? [Y/N]
N
Another action? [Y/N]
test
Incorrect input
This is the correct version of the same using Java8
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ScannerExample {
public static void main(String[] args) {
boolean run = true;
try (Scanner sc = new Scanner(System.in)) {
while (run) {
System.out.println("Another action? [Y/N]");
String option = sc.next();
Pattern patter = Pattern.compile("[YyNn]");
Matcher m = patter.matcher(option);
while (!m.matches()) {
System.out.println("Incorrect input");
option = sc.next();
m = patter.matcher(option);
}
option = sc.next();
if (option.toLowerCase().equals("f")) {
run = false;
}
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
output:
Another action? [Y/N]
Y
N
Another action? [Y/N]
Y
N
Another action? [Y/N]
f
Incorrect input
Y
N
Another action? [Y/N]
f
Incorrect input
Y
f
First thing: You need to move both scanner initialization line and its close() method outside the loop.
Second thing: In the checking condition add fF to let your program exit loop if one of these letters are typed while (!scanner.hasNext("[YyNnFf]")).
public static void main(String[] args) {
boolean run = true;
Scanner scanner = new Scanner(System.in);
while (run) {
// do something
System.out.println("Another action? [Y/N]");
while (!scanner.hasNext("[YyNnFf]")) {
System.out.println("Incorrect input");
scanner.next();
}
String choice = scanner.next();
if (choice.toLowerCase().equals("f")) {
run = false;
}
}
scanner.close();
}
As many of the answers suggests, the problem is with the statement Scanner scanner = new Scanner(System.in);. Following is the corrected version using try-with-resources, a cleaner way to handle resources in Java:
boolean run = true;
try(Scanner scanner = new Scanner(System.in))
{
while (run)
{
System.out.println("Another action? [Y/N]");
while (!scanner.hasNext("[YyNnFf]")) {
System.out.println("Incorrect input");
scanner.next();
}
String choice = scanner.next();
if (choice.toLowerCase().equalsIgnoreCase("f"))
run = false;
}
}
You can see it working here.
NOTE: I have changed the pattern matching statement from [YyNn] to [YyNnFf] and choice.toLowerCase().equals("f") to choice.toLowerCase().equalsIgnoreCase("f"), because It seems a logical error. See if it is as per your need.

Scanner's sc.next() makes me enter value twice

I am taking input for my application using scanner. My code is as follows:
Scanner sc = new Scanner(System.in);
System.out.println("Do you want to give user input :YES/NO")
if(sc.next().equals("YES")){
System.out.println("which input? student or teacher name")
if(sc.next().equals("student")){
system.out.println("do something");
}
if(sc.next().equals("teacher")){
system.out.println("do something");
}
}
}else
{
system.out.println("program will run itseld");
}
Code is working fine but it is asking input twice. Suppose if I enter student it will not proceed but when I enter student again second time my program starts working. I also saw some similar questions on stackoverflow and tried their solutions but I am not able to resolve this. Please help.
sc.next() grabs an input each time. Store this to a variable and just use the variable when comparing.
String input = sc.next();
if(input.equals("YES")) {
// logic here
}
try something like this
import java.io.*;
import java.util.*;
class SumsInLoopTester {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Do you want to give user input :YES/NO");
String input = sc.next();
if (input.equals("YES")) {
System.out.println("which input? student or teacher name");
String input2 = sc.next();
if (input2.equals("student")) {
System.out.println("do something");
} else if (input2.equals("teacher")) {
System.out.println("do something");
}
} else {
System.out.println("program will run itseld");
}
}
}

Not sure what loop to use in this case

I'm trying to make a simple program that asks for the user's age and displays an error when the user inputs a non-integer value.
Here's what I did so far:
import java.util.Scanner;
public class apples {
public static void main(String args[]) {
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name to begin.");
System.out.println("Hello " + nameinput.nextLine() + "!");
Scanner ageinput = new Scanner(System.in);
System.out.println("Please enter your age");
if(!ageinput.hasNextInt()){
System.out.println("Please enter an integer");
}
System.out.println("You've entered a valid age");
nameinput.close();
ageinput.close();
}
}
Here's what I want:
Every time the user inputs a non integer, I want the Please enter an integer error to appear. The user should then be able to input their age again, which will again be checked if it's an integer and so on. This will continue until the user inputs an integer and only then will the message You've entered a valid age be shown. I'm sure about neither which loop to use in this case (for, while, do while) nor how to implement it in the code.
String stringAge;
do {
System.out.println("Please Enter an int");
stringAge = ageinput.next();
} while (!stringAge.matches("^-?\\d+$")); //regex matches for - sign, and then a number
System.out.println("You entered an int");
int age = Integer.parseInt(stringAge);
As you know in Java they're 3 types of loops:
The while and do-while Statements
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once
while is simply a pre-test loop, that is the condition first will be checked before moving on to the body of the loop:
while(condition) # First check, if true or false
{
# Body
}
do-while loop however, checks the condition after executing of the body of the loop at least once, it's a post-test loop:
do{
# Body executed at least once
}while(condition);
The for Statement
The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied
Notice that in your code, asking the user for the age, the proper choice would be do-while, because you need to execute your program at least once to prompt the message and then you have to check the condition, if that's what you intended to do then this will suffice for your purpose. Though, you still can use while.
This is your code edited:
import java.util.Scanner;
public class apples {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name to begin.");
System.out.println("Hello " + input.nextLine() + "!");
System.out.println("Please enter your age");
do{
if(input.hasNextInt()){
System.out.println("You've entered a valid age");
break;
}
else{
System.out.println("Please enter an integer");
input.next();
}
}while(true);
}
}
Since the condition for the loop is the Boolean true it really doesn't matter here if you use while instead of do-while unless if you want to change the condition, that's up to you. For now, this code is very much close to the original code you posted and from my perspective it works, but it may not be the best code out there, there could be other approaches simpler or more complex to the same problem domain.
First of all, there's no need to have multiple Scanner objects wrapping the System.in input stream. (How to use multiple Scanner objects on System.in?)
As for the actual code, here's what came to mind:
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter your name to begin:");
String name = scanner.nextLine();
System.out.println("Hello " + name + "!");
System.out.println("Please enter your age:");
int age;
while (true) {
try { // Try to read in the age.
age = scanner.nextInt();
} catch (InputMismatchException ex) { // The input wasn't a valid integer; parsing the value failed.
System.out.println("Please enter an integer:");
continue; // Attempt reading the age again.
}
break; // The input was a valid integer. Break out of the loop.
}
scanner.close();
System.out.println("You've entered a valid age");
}
}
Hope this is what you wanted. i would suggest that using while is the way to go (my preference)
Using while::
public static void main(String args[]) {
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name to begin.");
System.out.println("Hello " + nameinput.nextLine() + "!");
Scanner ageinput = new Scanner(System.in);
System.out.println("Please enter your age");
while (!ageinput.hasNextInt()) {
System.out.println("Please enter an integer");
ageinput.next();
}
System.out.println("You've entered a valid age");
nameinput.close();
ageinput.close();
}
Using for::
public static void main(String args[]) {
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name to begin.");
System.out.println("Hello " + nameinput.nextLine() + "!");
Scanner ageinput = new Scanner(System.in);
System.out.println("Please enter your age");
for (; !ageinput.hasNextInt();) {
System.out.println("Please enter an integer");
ageinput.next();
}
System.out.println("You've entered a valid age");
nameinput.close();
ageinput.close();
}
Using do while
public static void main(String args[]) {
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name to begin.");
System.out.println("Hello " + nameinput.nextLine() + "!");
Scanner ageinput = new Scanner(System.in);
int i = 0;
do {
if (i == 0) {
System.out.println("Please enter your age");
i++;
} else {
System.out.println("Please enter an integer");
ageinput.next();
}
} while (!ageinput.hasNextInt());
System.out.println("You've entered a valid age");
nameinput.close();
ageinput.close();
}

Need help making loop work [duplicate]

This question already has answers here:
Breaks from loop
(3 answers)
Closed 8 years ago.
I have looped my code so it keeps repeating until a "yes" or a "no" is given when being asked "Continue?". But my code breaks from the loop after entering a random value and then yes.
for example:
Add or delete another name? Add
Please enter a name you want to add: Matt
Continue? f
Continue? yes
It should say:
Add or delete another name? Add
Please enter a name you want to add: Matt
Continue? f
Continue? yes
Add or delete another name?
actual code
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class AddOrDeleteNames {
public static void main(String[] args) throws Exception {
ArrayList<String> names = new ArrayList<String>();
Scanner scan = new Scanner(new File("names.txt"));
Scanner myScan = new Scanner(System.in);
Scanner scanRedo = new Scanner(System.in);
String userRedo;
String userResponse;
while (scan.hasNext())
names.add(scan.next());
do {
System.out.print("Add or delete another name? ");
userResponse = myScan.next();
if (userResponse.equalsIgnoreCase("add")) {
System.out.print("Please enter a name you want to add: ");
names.add(myScan.next());
} else if (userResponse.equalsIgnoreCase("delete")) {
System.out.print("Please enter a name you want to delete: ");
names.remove(myScan.next());
} else {
System.out.print("Invalid Choice");
}
PrintWriter writer = new PrintWriter("namesupdated.txt");
for (int i = 0; i < names.size(); i++)
writer.println(names.get(i));
writer.close();
System.out.print("Continue? ");
userRedo = scanRedo.next();
} while (userRedo.equalsIgnoreCase("yes"));
do { // THIS LOOP IS HERE BECAUSE IF THE USER ENTERS A VALUE OTHER THAN CONTINUE, YES OR NO, THE QUESTION REPEATS
if(userRedo.equalsIgnoreCase("no")) {
System.out.print("Thank You.");
userRedo = scanRedo.next();
} else if (!userRedo.equalsIgnoreCase("yes")) {
System.out.print("Continue? "); // LOOP ENDS EARLY HERE
userRedo = scanRedo.next();
}
} while (!userRedo.equalsIgnoreCase("yes")); // NOT SURE HOW TO RESTART PREVIOUS LOOP
scan.close();
myScan.close();
scanRedo.close();
}
}
The way you do this is always with a while loop with some sort of changable condition:
Scanner scan = new Scanner(System.in);
boolean stop = false;
while(!stop) {
//do whatever
...
System.out.println("Continue? Yes or No");
String s = Scan.nextLine();
if(s.equals("No")) {
stop = true;
}
}

Categories