Need help making loop work [duplicate] - java

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;
}
}

Related

How can i make a specific section of my code loop?

I started working on this little dice game but I need some help figuring out how to make the try again section loop after each failed attempt.
Currently the game restarts and asks the player to re-enter their name.
What I would like is for the user to just re-enter their guess
each time until they become successful.
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main (String[] args) throws IOException {
boolean run = true;
while (run) {
String[] input = new String[]{"1", "2", "3", "4", "5", "6"};
String[] sorry = new String[]{"If at first you don't succeed...", "Your luck will improve...", "Don't give up...", "Not this time..."};
Random dice = new Random();
int select = dice.nextInt(input.length);
Scanner scan = new Scanner(System.in);
System.out.println( "Hi there, may I please have your name?");
String name = scan.nextLine();
System.out.println("What a nice name...");
System.out.println("ok "+name+", please choose a number between 1 and 6");
String play = scan.nextLine();
System.out.println(input[select]);
if (!input[select].equals(play)) {
System.out.println(sorry[select]+" try again");
if (input[select].equals(play))
System.out.println("Bingo!!! "+name+" you've won 1 million imaginary dollars!");
System.out.println("would you like to play again \"Y\" or \"N\"");
String yes = "y";
String no = "n";
String answer = scan.nextLine();
if (answer.equals(yes)) {
continue;
}
if (answer.equals(no)) {
System.out.println("Thank you for playing "+name+". Good bye!");
break;
}
}
}
}
}
Put the print statement that asks name outside the while loop.
Scanner scan = new Scanner(System.in);
System.out.println("Hi there, may I please have your name?");
String name = scan.nextLine();
while(run){
// your code
}
You can use a while loop! At the try again section, change the if to a while loop.
static String play; // Define it (not assign) outside of method
while (!input[select].equals(play)) {
System.out.println(sorry[select]+" try again");
System.out.println("ok "+name+", please choose a number between 1 and 6");
play = scan.nextLine();
}
Definition of while loop from W3Schools:
The while loop loops through a block of code as long as a specified condition is true

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);
}

How to keep the program running if the user entered Y?

Here is my code:
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner Keyboard = new Scanner(System.in);
{
System.out.println("What is the answer to the following problem?");
Generator randomNum = new Generator();
int first = randomNum.num1();
int second = randomNum.num2();
int result = first + second;
System.out.println(first + " + " + second + " =");
int total = Keyboard.nextInt();
if (result != total) {
System.out.println("Sorry, wrong answer. The correct answer is " + result);
System.out.print("DO you to continue y/n: ");
} else {
System.out.println("That is correct!");
System.out.print("DO you to continue y/n: ");
}
}
}
}
I'm trying to keep the program to continue but if the user enters y and closes if he enters n.
I know that I should use a while loop but don't know where should I start the loop.
You can use a loop for example :
Scanner scan = new Scanner(System.in);
String condition;
do {
//...Your code
condition = scan.nextLine();
} while (condition.equalsIgnoreCase("Y"));
That is a good attempt. Just add a simple while loop and facilitate user input after you ask if they want to continue or not:
import java.util.*;
class Main
{
public static void main(String [] args)
{
//The boolean variable will store if program needs to continue.
boolean cont = true;
Scanner Keyboard = new Scanner(System.in);
// The while loop will keep the program running unless the boolean
// variable is changed to false.
while (cont) {
//Code
if (result != total) {
System.out.println("Sorry, wrong answer. The correct answer is " + result);
System.out.print("DO you to continue y/n: ");
// This gets the user input after the question posed above.
String choice = Keyboard.next();
// This sets the boolean variable to false so that program
// ends
if(choice.equalsIgnoreCase("n")){
cont = false;
}
} else {
System.out.println("That is correct!");
System.out.print("DO you to continue y/n: ");
// This gets the user input after the question posed above.
String choice = Keyboard.next();
// This sets the boolean variable to false so that program
// ends
if(choice.equalsIgnoreCase("n")){
cont = false;
}
}
}
}
}
You may also read up on other kinds to loop and try implementing this code in other ways: Control Flow Statements.

Java won't respond to my input

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.

Cannot Store Data into ArrayLists?

thanks for all the help guys but now the nature of the question has changed using Patrick's suggestion below loop is running but it dise not seem to be storing the input to respective arrays data keeps hetting replaced into the ArrayLists rather than going to the next position into the ArrayList any suggestions?
import java.util.ArrayList;
import java.util.Scanner;
public class Arrray {
public static void main(String [] args){
ArrayList<String> names;
ArrayList<String> addr;
do {
names = new ArrayList<String>();
addr = new ArrayList<String>();
Scanner userInput = new Scanner(System.in);
System.out.println("Name and Adreess are: " + names.size() + "**"
+ addr.size());
System.out.println("please Enter Your Name :");
names.add(userInput.next());
System.out.println("please enter your Address :");
addr.add(userInput.next());
System.out.println("Do you want to add another entry? :(y/n)" );
String ans =userInput.next(); // get the value from the user using scanner class
if(ans.equals("n") || ans.equals("N"))
break;
} while (true);
int n = names.size();
int a = addr.size();
for(int i =0; i<n && i<a; i++ )
System.out.println("Name and address are as below: "+ names.get(i)+"**"+ addr.get(i));
}
}
Use a while(true) in conjunction with a break statement:
do {
if(input.next() == 'n'){
break;
}
} while(true);
get value from the user and if user enter n then break otherwise nothing
System.out.println("Do you want to add another entry? :(y/n)" );
String ans = .... // get the value from the user using scanner class
if(ans.equalsIgnoreCase("n"))
break;
Try to capture this user's input
System.out.println("Do you want to add another entry? :(y/n)");
and use that info in the while.
You have to do something like this:
String choice = "";
do {
.
.
.
.
System.out.println("Do you want to add another entry? :(y/n)" );
choice = userInput.next();
} while (!(choice.equals("n") || choice.equals("N")));
The line
choice = userInput.next();
will read user input, and the String classes equals method for comparing the input. The loop will continue until the choice is either N or n.
import java.util.ArrayList;
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
ArrayList<String> name = new ArrayList<String>();
ArrayList<Integer> phone = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
String answer = "";
do {
System.out.println("Please enter your name: ");
name.add(scanner.next());
System.out.println("Please enter your number: ");
phone.add(scanner.nextInt());
System.out.println("Do you want to add a directory y/n?");
answer = scanner.next();
} while (answer.equals("y") || answer.equals("Y"));
if (answer.equals("y") || answer.equals("Y")); //want it to go back to start another direcotry here
else {
System.out.println("Thanks for adding to the directory");
for (int i = 0; i < name.size(); i++) {
System.out.print(name.get(i) + "\t");
System.out.print(phone.get(i));
System.out.println("");
}
}
}
}

Categories