import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
// program in this project exercises 36.1-36.5
// actually this is just one program that is split in many parts
Scanner reader = new Scanner(System.in);
System.out.println("Type numbers: ");
int input = Integer.parseInt(reader.nextLine());
while(true){
if(input == -1){
break;
}
}
System.out.println("Thank you and see you later!");
}
}
The user should be able to put in multiple numbers until -1 is reached. Once its reached it should break the loop and print the last line.
You need to put
System.out.println("Type numbers: ");
int input = Integer.parseInt(reader.nextLine());
into your loop, else it will never get new user input
You need call scanner inside loop
import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
while(true){
Scanner reader = new Scanner(System.in);
System.out.println("Type numbers: ");
int input = Integer.parseInt(reader.nextLine());
if(input == -1){
break;
}
}
System.out.println("Thank you and see you later!");
}
}
Related
I am trying to achieve a certain result or output before terminating the loop.
Here is my code:
import java.util.Scanner;
public class learnjava {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("How old are you?");
int age = scanner.nextInt();
scanner.nextLine();
System.out.println("Do you prefer cats or dogs?");
String animal = scanner.nextLine();
if (age > 10 || animal.equals("cats"))
{System.out.println("welcome!");}
else {System.out.println("No access");}
scanner.close();
}
}
Ideally I want to create a loop that makes my code run until system prints out welcome, so that I can avoid restarting the program. I want to provide the user another chance at inputting right answers once the first input fails without running again, hence the console should ask again "how old are you?"
You can use a do while loop for this use case. The actual validation logic can be put within the loop and the loop will be terminated only if the condition is invalid.
So in you case, the loop will check the condition age < 10 || !animal.equals("cat"). So the loop will run till the age exceeds 10 or the animal is "cat". As this is an exit check loop, it will exit only after printing "Welcome" to the console.
The code is as follows,
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String animal;
int age;
do{
System.out.println("How old are you?");
age = scanner.nextInt();
scanner.nextLine();
System.out.println("Do you prefer cats or dogs?");
animal = scanner.nextLine();
if (age > 10 || animal.equals("cats"))
{
System.out.println("welcome!");
}
else {
System.out.println("No access");
}
}while(age < 10 || !animal.equals("cat"));
scanner.close();
}
}
You use loops in java for repeated task. while loop is one of them
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
if (askUser(scanner)) {
System.out.println("welcome!");
break;
} else {
System.out.println("No access");
}
}
scanner.close();
}
private static boolean askUser(Scanner scanner) {
System.out.println("How old are you?");
int age = scanner.nextInt();
scanner.nextLine();
System.out.println("Do you prefer cats or dogs?");
String animal = scanner.nextLine();
return (age > 10 || animal.equals("cats"));
}
How about wrapping the logic in a while loop with a boolean variable to indicate the isFinished status:
import java.util.Scanner;
public class learnjava {
private static final String WELCOME = "welcome!";
private static final String ACCESS_DENIED_TRY_AGAIN = "No access";
public static void main(String[] args) {
boolean isFinished = false;
Scanner scanner = new Scanner(System.in);
while (!isFinished) {
System.out.println("How old are you?");
int age = scanner.nextInt();
System.out.println("Do you prefer cats or dogs?");
String animal = scanner.nextLine();
if (age > 10 || animal.equals("cats")) {
System.out.println(WELCOME);
isFinished = true;
} else {
System.out.println(ACCESS_DENIED_TRY_AGAIN);
}
}
scanner.close();
}
}
I need help making it so that the entire script will loop from the beginning if the user types y at the end and the script ends if the user types n at the end. Thanks for any help.
package test123;
import java.util.Scanner;
public class test321 {
public static void main(String[] args) {
int n = 1;
int c;
String playAgain;
do {
System.out.println("Enter a number");
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
if ( n < 0 )
System.out.println("Number cant be a negative.");
else
{
int x=n*(n-1)*(n-2);
System.out.println("Factorial= "+x);
System.out.println("Do you want to continue? (y/n):");
playAgain = scanner.nextLine();
}while (!playAgain.equals("y"));
}
}
}
package test123;
import java.util.Scanner;
public class test321 {
public static void main(String[] args) {
int n = 1;
int c;
String playAgain;
do {
System.out.println("Enter a number");
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
if ( n < 0 )
System.out.println("Number cant be a negative.");
else
{
int x=n*(n-1)*(n-2);
System.out.println("Factorial= "+x);
System.out.println("Do you want to continue? (y/n):");
playAgain = scanner.nextLine();
} // end else
} // end do
while (playAgain.equals("y"));
}// end main
} // end class
Change
while (!playAgain.equals("y"));
to
while (!playAgain.equals("n"));
For java practice, i am trying to create a program that reads integers from the keyboard until a negative one is entered.
and it prints the maximum and minimum of the integer ignoring the negative.
Is there a way to have continuous input in the same program once it runs? I have to keep running the program each time to enter a number.
Any help would be appreciated
public class CS {
public static void main(String []args) {
Scanner keys = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = keys.nextInt();
while(true)
{
if(n>0)
{
System.out.println("Enter again: ");
n = keys.nextInt();
}
else
{
System.out.println("Number is negative! System Shutdown!");
System.exit(1);
}
}
}
}
Here is a part of my code - It works, but i think there is an easier way of doing what i want but not sure how!
import java.util.Scanner;
public class ABC {
public static void main(String []args) {
int num;
Scanner scanner = new Scanner(System.in);
System.out.println("Feed me with numbers!");
while((num = scanner.nextInt()) > 0) {
System.out.println("Keep Going!");
}
{
System.out.println("Number is negative! System Shutdown!");
System.exit(1);
}
}
}
You could do something like:
Scanner input = new Scanner(System.in);
int num;
while((num = input.nextInt()) >= 0) {
//do something
}
This will make num equal to the next integer, and check if it is greater than 0. If it's negative, it will fall out of the loop.
A simple loop can solve your problem.
Scanner s = new Scanner(System.in);
int num = 1;
while(num>0)
{
num = s.nextInt();
//Do whatever you want with the number
}
The above loop will run until a negative number is met.
I hope this helps you
So I'm trying to use if-else statement dependant upon the user's input. It works when the user's input is only one word, however, multiple word inputs go unrecognized and triggers the else statement. How can i resolve this?
import java.util.Scanner;
public class MyFirstJavaClass {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner myScanner = new Scanner(System.in);
String answer;
System.out.println("Catch the tiger or run away?");
answer = myScanner.next();
if (answer.equals("Catch the tiger" )) {
System.out.println("You've been mauled by a tiger! What were you thinking?");
answer = myScanner.next();
} else {
System.out.println("run away");
}
}
}
Replace:
answer = myScanner.next();
With:
answer = myScanner.nextLine();
next will only read in the next value until it reaches a space or newline. You want to read in the full line before making the comparison
try this :
Scanner scanner = new Scanner(System.in);
int choice = 0;
while (scanner.hasNext()){
if (scanner.hasNextInt()){
choice = scanner.nextInt();
break;
} else {
scanner.next(); // Just discard this, not interested...
}
}
Reference :
Flush/Clear System.in (stdin) before reading
Try this
import java.util.Scanner;
public class MyFirstJavaClass {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner myScanner = new Scanner(System.in);
System.out.println("Catch the tiger or run away?");
if (myScanner.hasNext("Catch the tiger")) {
System.out.println("You've been mauled by a tiger! What were you thinking?");
} else {
System.out.println("run away");
}
}
}
import java.util.Scanner;
public class test {
public static void main(String[] args) {
System.out.print("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
int x = keyboard.nextInt();
}
}
How do I loop a piece of code like the one above until an int is entered instead of giving an error when a non-int is entered?
The Scanner class has a lot of stuff built in so that you don't need to do try-catches unless you are explicitly looking to catch the errors.
public static int test(){
int number = 0;
Scanner input = new Scanner(System.in);
boolean valid = false;
do{
System.out.print("Please enter an integer: ");
if(input.hasNextInt()){ // This checks to see if the next input is a valid **int**
number = input.nextInt();
valid = true;
}
else{
System.out.print("Not a valid integer!\n");
input.next();
}
}while(valid == false);
return number;
}
This tries to run the scanner, if a input is one that is not expected it will simply restart. You can add a message to it, my code was for brevity.
import java.util.Scanner;
public class test {
public static void main(String[] args) {
System.out.print("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
try {
int x = keyboard.nextInt();
}
catch (java.util.InputMismatchException e) {
main(null);
}
}
}