Java: Input comparison - java

I'm wondering why when I type 'y' after being asked if there are any more digits in this method the code works correctly and leaves the loop, but upon typing 'n' and hitting return, I need to type 'n' and hit return again or the process just hangs.
Why?
The string 'input' is being passed from the user's input in the main method and is in this case "addition".
private int add(String input)
{
int additionValue = 0;
boolean keepGoing = true;
if (input.matches("addition"))
{
while (keepGoing == true)
{
System.out.println("Next digit = (Type the digit)");
additionValue = additionValue + scan.nextInt();
System.out.println("Any more digits? Type y/n");
if (scan.next().matches("Y|y"))
{
keepGoing = true;
}
else if (scan.next().matches("N|n"))
{
keepGoing = false;
}
else
{
System.out.println("Great, you broke it.");
System.exit(1);
}
}
}
}
I've managed to get the code working by using
System.out.println("Any more digits? Type y/n");
String yayOrNay = scan.next();
if (yayOrNay.length()==1 && yayOrNay.charAt(0)=='y')
{
keepGoing = true;
}
but that seems a little too complicated to me for all that it's doing.

scan.next() pulls a new character from the input steam.
So when you check for 'n' and scan.next().matches("Y|y") executes, it is actually skipping 'n' for your next comparison.
The solution is to assign scan.next() into a variable you can use:
while (keepGoing == true)
{
System.out.println("Next digit = (Type the digit)");
additionValue = additionValue + scan.nextInt();
System.out.println("Any more digits? Type y/n");
String next = scan.next();
if (next.matches("Y|y"))
{
keepGoing = true;
}
else if (next.matches("N|n"))
{
keepGoing = false;
}
else
{
System.out.println("Great, you broke it.");
System.exit(1);
}
}

This is because you call scan.next() two times.
You have to call it one time, putting the resulting string in a variable.
String input2 = scan.next();
if (input2.matches("Y|y"))
{
keepGoing = true;
}
else if (input2.matches("N|n"))
{
keepGoing = false;
}

You need to enter 'n' twice because you scan for input in each if condition. So if the letter is not a 'y', your program will wait for user input in the next if statement.
You can simply do:
String yayOrNay = scan.next();
if (yayOrNay.matches("Y|y"))
{
keepGoing = true;
}
else if (yayOrNay.matches("N|n"))
{
keepGoing = false;
}
...

if (scan.next().matches("Y|y"))
{
keepGoing = true;
}
else if (scan.next().matches("N|n"))
You call scan.next twice
1st time you check if its Y, if it isn't you read from input again
so
somevar=scan.next()
if (somevar.matches("Y|y"))
{
keepGoing = true;
}
else if (somevar.matches("N|n"))
{
keepGoing = false;
}
else ..

Your error is to call scan.next() twice, which requests two imputs.
private int add(String input)
{
int additionValue = 0;
boolean keepGoing = true;
if (input.matches("addition"))
{
while (keepGoing == true)
{
System.out.println("Next digit = (Type the digit)");
additionValue = additionValue + scan.nextInt();
System.out.println("Any more digits? Type y/n");
String s = scan.next();
if (s.matches("Y|y"))
{
keepGoing = true;
}
else if (s.matches("N|n"))
{
keepGoing = false;
}
else
{
System.out.println("Great, you broke it.");
System.exit(1);
}
}
}
}

Please Try This,
Scanner scan = new Scanner(System.in);
int additionValue=0;
while (true)
{
System.out.println("Any more digits? Type y/n");
if (scan.next().matches("Y|y"))
{
System.out.println("Next digit = (Type the digit)");
additionValue = additionValue + scan.nextInt();
//System.out.println("Any more digits? Type y/n");
}
else
{
System.out.println("Thanks");
break;
}
}
I am not sure whether this logic will work for you. 'If you want you can process 'n' also'
output
Any more digits? Type y/n
y
Next digit = (Type the digit)
5
Any more digits? Type y/n
n
Thanks

Related

Compilation Error in a very silly program

import java.util.Scanner;
public class KekOrCringe {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String userGuess = "";
boolean Continue = true;
boolean ProperResponse = true;
boolean IsCorrect = true;
boolean YesNo = true;
while (Continue)
{
int secretAnswer = (int)(Math.random() * 2 + 1);
kekOrCringe(secretAnswer);
while (!IsCorrect)
{
System.out.println("Kek or Cringe?");
ProperResponse = false;
while (!ProperResponse) {
userGuess = scan.nextLine();
if (userGuess != "Kek")
System.out.println("Your entry is invalid, please try again!");
else if (userGuess != "Cringe")
System.out.println("Your entry is invalid, please try again!");
else
ProperResponse = true;
}
for (int guessCount = 0; guessCount < 1; guessCount++) {
if (userGuess = "Cringe" && userGuess != secretAnswer) {
System.out.println("It's KeK!");
guessCount++; }
else if (userGuess = "Kek" && userGuess != secretAnswer) {
System.out.println("It's CrInGe!");
guessCount++; }
else
System.out.println("Mr. Morgan, you got it right my boy!");
IsCorrect = true;
}
}
}
YesNo = false;
while(!YesNo) {
System.out.println("Would you like to play again? Yes/No");
String answer = scan.nextLine();
if (answer.equals("No")) {
Continue = false;
YesNo = true;
System.out.println("Fine. You were Cringe anyway!");
}
else if (answer.equals("Yes")) {
YesNo = true;
Continue = true;
IsCorrect = false;
}
}
}
public static String kekOrCringe(int secretAnswer) {
if (secretAnswer = 1) { return "Kek";}
if (secretAnswer = 2) { return "Cringe";}
}
}
Probably an overly complex way to do something unnecessary, but this is my first year in college learning to code, and I was asked to give this a try. I think it's funny, and will probably be funnier if it work, along with being good practice. I'm having trouble converting the int secretAnswer to a returned string, and then comparing the userGuess to the return type. Getting compilation errors on line 32 and 35. Any tips would be appreciated.
P.S. I realize it's silly. Trying to use this silly code as a learning opportunity.
Im guessing line 32 and 35 are the two ifs. userGuess != secretAnswer doesn't work since one is a String, the other an Integer. Your static method kekOrCringe(secretAnswer); returns the String you want, you just need to save it in a variable and then compare it to the userGuess.
Also please use lowercase variable names.
I can't add a comment so I am writing here.
userGuess is String but secretAnswer is int, and you are trying to check if they are equal (userGuess != secretAnswer).
You can use a new variable like secretGuess, assign kekOrCringe(secretAnswer) to secretGuess and check if userGuess is equal to secretGuess.
Like this:
String secretGuess = kekOrCringe(secretAnswer);
if (userGuess != secretGuess) {
//...
}
You are trying to compare int to string which is wrong
userGuess != secretAnswer
Also, instead of comparing you are assigning values inside if condition.
if (secretAnswer = 1) { return "Kek";}
if (secretAnswer = 2) { return "Cringe";}
It should be:
if (secretAnswer == 1) { return "Kek";}
if (secretAnswer == 2) { return "Cringe";}

y/n input validation including no input Enter key

I am trying to catch no input (enter key) and invalid input everything but y/n in one method. I tried it two different ways (pasted) but I cannot make work both “enter key” and “mistype y/n” together. Thank you for your help.
1st attempt:
public static String askToContinue(Scanner sc) {
String choice = "";
boolean isValid = false;
while (!isValid){System.out.print("Continue? (y/n): ");
if (sc.hasNext()){
choice = sc.next();
isValid = true;
} else {System.out.println("Error! "
+ "This entry is required. Try again");
}
if (isValid && !choice.equals("y") || !choice.equals("n")) {
System.out.println("Error! Entry must be 'y' or 'n'. Try again");
isValid = false;
}
}
//sc.nextLine(); // discard any other data entered on the line
System.out.println();
return choice;
}
2nd attempt
public static String askToContinue(Scanner sc) {
System.out.print("Continue? (y/n): ");
String choice;
while (true) {choice = sc.next();
//?????????????????????????????????????????????????????
if (choice.length() == 0){ System.out.println("Error! "
+ "This entry is required. Try again");
continue;
}
if (!(choice.equals("y") || choice.equals("n"))) {
System.out.println("Error! Entry must be 'y' or 'n'. Try again");
continue;
}
break;
}
sc.nextLine(); // discard any other data entered on the line
System.out.println();
return choice;
}
I tried with 1st attempt of your code. I explained with comment line which is included in below code like ;
public static String askToContinue(Scanner sc) {
String choice = "";
boolean isValid = false;
while (!isValid) {
System.out.print("Continue? (y/n): ");
choice = sc.nextLine(); //to reads all line , because this cannot read with empty enter input
isValid = true;
if (choice.isEmpty()) { //this isEmpty for empty enter
System.out.println("Error! "
+ "This entry is required. Try again");
}
System.out.println(choice);
//this logic if not y or n , it will return error
if (!choice.equals("y") && !choice.equals("n")) {
System.out.println("Error! Entry must be 'y' or 'n'. Try again");
isValid = false;
}
}
//sc.nextLine(); // discard any other data entered on the line
System.out.println();
return choice;
}
Your if statement in first case is wrong. You are checking if choice is not equal to 'y' or not equal to 'n' which will always be true .
Change
if (isValid && !choice.equals("y") || !choice.equals("n"))
To
if (isValid && !choice.equals("y") && !choice.equals("n"))

Java Loop only running once

Im building a code guessing game if you insert an invalid input ie( 333 ) it will prompt you to change your guess. however this only works on guess #1 on guess #2 - #6 it will let any invalid input go through
public void game(){
System.out.println("Enter guess #" + (guessAtt + 1));
guess = keyboard.next();
guess = guess.toLowerCase();
if( guess.equals(quit)){
System.exit(0);
}
if (guess.length() < 2){
System.out.println("Guess Too short try again");
game();
}
if (guess.length() > 3){
System.out.println("Guess too long try again");
game();
}
letter1 = guess.charAt(0);
letter2 = guess.charAt(1);
letter3 = guess.charAt(2);
isValid();
}
public boolean isValid(){
if (letter1.equals('a')|| letter1.equals('b')|| letter1.equals('c')|| letter1.equals('d')|| letter1.equals('e')){
isValid1 = true;
}
if(letter2.equals('a')|| letter2.equals('b')|| letter2.equals('c')|| letter2.equals('d')|| letter2.equals('e')){
isValid2 = true;
}
if(letter3.equals('a')|| letter3.equals('b')|| letter3.equals('c')|| letter3.equals('d')|| letter3.equals('e')){
isValid3 = true;
}
if(isValid1 == true && isValid2 == true && isValid3 == true){
isValid = true;
}
else {
isValid = false;
}
while (isValid == false){
System.out.println("invalid input try again\n");
game();
}
return isValid;
}
you could both use a while loop in the game that breaks when isValid() returns a true. You could also call the function game if isValid() returns a false value. Now you ask for a boolean value, but you don't use it. No matter what it returns, as long as your value contains the right lenght, the game ends.

How do I break out of a loop while reading in a string?

For example:
Scanner keyboard = new Scanner(System.in);
int counter=1;
while (!(keyboard.equals('0')))
{
for (int i=1;i<=counter;i++)
{
prodNum[i]=keyboard.nextInt();
quantity[i]= keyboard.nextInt();
}
counter++;
}
How do I break out of a loop when I enter in a zero? I can't seem to figure it out. It keeps taking input, even when I enter a zero? I need for it keep taking input until the user enters a zero.
Any ideas what I'm doing wrong?
keyboard.equals('0') will compile, but it is never going to evaluate to true, because Scanner object cannot possibly be equal to a Character object.
If you would like to wait for the scanner to return zero to you, you should call next() or nextLine() on it, and compare the resultant String object to "0".
while (true) {
while (keyboard.hasNext() && !keyboard.hasNextInt()) {
System.out.println("Please enter an integer value.");
keyboard.nextLine();
}
if (!keyboard.hasNextInt())
break;
prodNum[i]=keyboard.nextInt();
if (prodNum[i] == 0)
break;
while (keyboard.hasNext() && !keyboard.hasNextInt()) {
System.out.println("Please enter an integer value.");
keyboard.nextLine();
}
if (!keyboard.hasNextInt())
break;
quantity[i]=keyboard.nextInt();
if (quantity[i] == 0)
break;
i++;
}
Demo.
int counter=1;
int flag = 1;
while (flag != 0)
{
for (int i=1;i<=counter;i++)
{
if(flag == 0)
{
break;
}
prodNum[i]=keyboard.nextInt();
quantity[i]= keyboard.nextInt();
flag = quantity[i];
}
counter++;
}

Boolean bug (FibonacciNumbers)

First of all I am not asking anyone to do anything just need a little help to fix this bug with boolean. I put false but the program stops. I got two parts to the program.
First part where i did the calculations:
class FibonacciNumbers {
FibonacciNumbers() {} //default constructor
public int fOf(int n) {
if (n == 0) //the base case
{
return 0;
} else if (n == 1) {
return 1;
} else {
return fOf(n - 1) + fOf(n - 2);
}
}
}
Second where the main method is:
import java.util.*;
public class FibonacciNumbersTesters {
public static void main(String[] args) {
FibonacciNumbers fNumbers = new FibonacciNumbers(); //creates new object
Scanner in = new Scanner(System.in);
String again;
String test;
boolean IsRepeat = true;
boolean isQuit;
try {
isQuit = false;
while (!isQuit) {
System.out.print("Enter the number you want to convert to Fibanocci('q' to quit): ");
int n = in.nextInt();
System.out.print("The Fibanocci number for " + n + " is: ");
n = fNumbers.fOf(n);
System.out.println(n);
System.out.print("Do you want to run again? (Y or N): ");
again = in.next();
if (again.equalsIgnoreCase("N")) {
System.out.println("Thank you! Please terminate the program by entering 'Q' or 'q' OR you can cotinue by entering anything else: ");
String toQuit = in.next();
if ((toQuit.charAt(0) == 'q') || (toQuit.charAt(0) == 'Q')) {
System.out.println("Good-bye!");
isQuit = true;
}
} else {
IsRepeat = true;
}
}
} catch (InputMismatchException ex) {
test = in.nextLine();
if ((test.charAt(0) == 'q') || (test.charAt(0) == 'Q')) {
System.out.println("Good-bye!");
isQuit = true;
} else {
System.out.println("Invalid input!");
System.out.println("Try again! ");
isQuit = false;
}
}
}
}
This part where i put isQuit = false; at the end it just stops. I want it to continue.
Try putting your try catch statement inside of your while loop.

Categories