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");
}
}
}
Related
I am supposed to make a program that asks users for a list of input. Then, from that list, my program is supposed to pick out the third answer and then print it out. It sounds really simple, but how do I assign numbers to each of the user inputs? Do I even do that? I am a beginner, and thank you so much for your help!
This is the code I have so far:
import java.util.*;
public class MyProgram
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
while(true) {
System.out.println("What do you appreciate in your life or school?");
String ans = scan.nextLine();
if(ans.equals(""))
{
break;
}
}
System.out.println("You said \"" + input3 + "\" as your third answer.");
}
}
You can strore the third input in a variable you initialized bevor the loop.
if there is no third input it prints: ""
import java.util.*;
public class MyProgram
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int index = 0;
String input3 = "";
while(true) {
System.out.println("What do you appreciate in your life or school?");
String ans = scan.nextLine();
if (index == 2) {
input3 = ans;
}
if(ans.equals("")){
break;
}
index++;
}
System.out.println("You said \"" + input3 + "\" as your third answer.");
}
}
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();
}
}
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!");
}
}
Hi I'm trying to write a program that will check a designated file for a number that a user has input, however if the number is not present in the file I want the program to loop back to the beginning, how could I do this?
Here is the mess I've made so far:
import java.util.Scanner;
public class Classtest2 {
public static void main(String[] args) {
// //1. class
Scanner sc = new Scanner(Classtest2.class.getResourceAsStream("trombones.txt"));
Scanner myScanner = new Scanner(System.in);
System.out.println("What number would you like to check for?");
String number = myScanner.nextLine() ;
String keyWord = number, word;
int lineNum = 0;
while(sc.hasNextLine()) {
word = sc.next();
if(word.equals(myScanner.nextLine().trim())) {
System.out.println("The number "+number+ " is there");
break;
} else {
// not found
}
} // main
} // class
all you need to do is take input from user and then check is it exist in file .you shouldn't use myScanner.nextLine().trim() inside while loop because then it waits to get user input every loop time .ones you get a number from user ,you should check it in the file .what you did is get user input and then again wait for user to input value again and again
fixed code
import java.util.Scanner;
public class Classtest2 {
public static void main(String[] args) {
// //1. class
Scanner sc = new Scanner(Classtest2.class.getResourceAsStream("trombones.txt"));
Scanner myScanner = new Scanner(System.in);
System.out.println("What number would you like to check for?");
String number = myScanner.nextLine() ;
int lineNum = 0;
while(sc.hasNextLine()) {
word = sc.next();
if(word.equals(number.trim())) { //here was the problem
System.out.println("The number "+number+ " is there");
return;
} else {
}
}
System.out.println("not found"); // not found
}
the best approach
import java.util.Scanner;
public class Classtest2 {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println("What number would you like to check for?");
String number = myScanner.nextLine();
if(isFound(number)){
System.out.println("The number "+number+ " is there");
}else{
System.out.println("The number "+number+ " doesn't exist");
}
}
public static boolean isFound(String number) {
Scanner sc = new Scanner(Classtest2.class.getResourceAsStream("trombones.txt"));
String word="";
while (sc.hasNextLine()) {
word = sc.next();
if (word.equals(number.trim())) {
return true;
}
}
return false;
}
}
This works for me, hope is useful for you:
package test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class Classtest2 {
public static void main(String[] args) throws IOException {
File f = new File("trombones.txt");
f.createNewFile();
Scanner myScanner = new Scanner(System.in);
boolean numExiste = menu(new Scanner(f), myScanner);
while (!(numExiste)){
numExiste = menu(new Scanner(f), myScanner);
}
myScanner.close();
}
private static boolean menu(Scanner fileScanner, Scanner myScanner) throws FileNotFoundException{
String word = "";
System.out.println("What number would you like to check for?");
String number = myScanner.nextLine().trim();
while(fileScanner.hasNextLine()){
word = fileScanner.nextLine();
if(word.trim().equals(number)){
System.out.println("The number "+number+ " is there");
return true;
}else{
//Not the number
}
}
System.out.println("The number "+ number+ " is not in the file\n\n");
return false;
}
} // main } // class
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);
}
}
}