Java: while loop not working - java

I want to check the users input when a new game is created, and see if it is y, n, or neither.
For some reason it skips the while loop all together and just outputs "Welcome to Questions."
import java.util.Scanner;
public class Questions {
public static final Scanner INPUT = new Scanner(System.in);
private boolean ans;
public Questions() {
while (ans = false) {
System.out.print("Do you want to start a new game (y/n)?: ");
String input = INPUT.nextLine();
if (input == "y"){
ans = true;
//some code
}
else if (input == "n"){
ans = true;
//some code
}
else {
System.out.println("Invalid input, Try again");
ans = false;
}
}//end while
}
public static void main(String[] args) {
Questions game = new Questions();
System.out.println("Welcome to Questions.");
}

while (ans = false) {
Should be:
while (ans == false) {
= is for assignment == is for checking equality
Also Strings are compared using .equals() or .equalsIgnoreCase() not ==:
if (input == "y"){
Should be:
if (input.equalsIgnoreCase("y")){

Change private boolean ans to
private boolean ans = false;
or use do while loop
Also comparison is done using == not =

Related

While loop does not update based on inside parameters

I'm writing code for a game of blackjack, this while loop for some reason never ends even when I enter something other then an H.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
boolean hit = true;
while (hit = true) {
System.out.println("Do you want to (H)It or (S)tand");
String hitorstand = console.next();
char firstchar = hitorstand.charAt(0);
if (firstchar == 'H' || firstchar == 'h') {
hit = true;
}
else {
System.out.println("This should now be false :)");
hit = false;
}
}
}
I ran the below code and it works properly.
public static void main(String[] args) {
// TODO code application logic here
Scanner s=new Scanner(System.in);
boolean h;
do {
System.out.println("hit(H) or stand(S)");
String hitOrStand;
hitOrStand=s.next();
char hOrS;
hOrS = hitOrStand.charAt(0);
if(hOrS=='H' || hOrS=='h')
h=true;
else{
System.out.println("This should now be false :)");
h = false;
}
} while (h);
}
You need to change your "while(hit = true)" condition. As "hit = true" always returns true & assigns true to hit always.
So modify your while condition as below:
while (hit) {
System.out.println("Do you want to (H)It or (S)tand");
String hitorstand = console.next();
char firstchar = hitorstand.charAt(0);
if (firstchar == 'H' || firstchar == 'h') {
hit = true;
}
else {
System.out.println("This should now be false :)");
hit = false;
}
}

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

How do I fix my java method to correctly iterate through string?

I need some major help.
My assignment is to recognize a lowercase string and return a true or false statement despite the presence of other characters or words. So far, I'm able to recognize the string in all lowercase, but my code still returns a TRUE value if the word is all uppercase; I only want it to recognize the lowercase values.
The assignment:
Write a program that takes in a string line and prints true if letters of my name (“john”) have appeared in the string in the same order, all in lowercase. Please note that there might be other characters between the letters of my name.
Here's my code:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
boolean output = Check();
if (output == true) {
System.out.println("true");
}
else if (output == false) {
System.out.println("false");
}
}
public static boolean Check() {
String random;
Scanner sc = new Scanner(System.in);
random = sc.nextLine();
String word = "john";
for (int i = 0; i < word.length(); i++) {
if (random.contains(word.substring((i)))) {
return true;
}
}
if (random.contains("JOHN")) {
return false;
}
return false;
}
}
Any help would be great thanks.
Some sample outputs:
Sample Input 1:
hello John
Sample Output 1:
false
Sample Input 2:
j123o23h56n
Sample Output 2:
true
Sample Input 3:
joh'n
Sample Output 3:
true
Sample Input 4:
ho0jn
Sample Output 4:
false
Sample Input 5:
J2j##oh123$NNNnn
Sample Output 5:
true
You need to write a logic where you pick each char from "john" string and compare it in order whether all of them occurred in that order or not. The moment it finds all the characters are found in the input string, it immediately return true without the need to further scan the input string. You may write something like this,
public static boolean Check() {
String random;
Scanner sc = new Scanner(System.in);
random = sc.nextLine();
String word = "john";
sc.close();
int findIndex = 0;
char findChar = word.charAt(findIndex);
for (char c : random.toCharArray()) {
if (findChar == c) {
findIndex++;
if (findIndex == word.length()) {
return true;
}
findChar = word.charAt(findIndex);
}
}
return false;
}
You can simply do this (I didn't understand your condition for uppercase though; this Check method can find whether j,o,h,n appear in the string in the proper order),
public static boolean Check(){
String random;
Scanner sc = new Scanner(System.in);
random = sc.nextLine();
HashMap<String, Boolean> map =new HashMap<String, Boolean>();
for(int i=0;i<random.length();i++){
if(map.size() == 0){
//find j
if(random.charAt(i) == 'j'){
map.put("j", true);
}
}else if(map.containsKey("j") && map.size() == 1){
//find o
if(random.charAt(i) == 'o'){
map.put("o", true);
}
}else if(map.containsKey("o")&& map.size() == 2){
//find h
if(random.charAt(i) == 'h'){
map.put("h", true);
}
}else if(map.containsKey("h")&& map.size() == 3){
//find n
if(random.charAt(i) == 'n'){
map.put("n", true);
}
}
}
return map.size() == 4;
}
Alternatively, you can use a stack to solve this too,
public static boolean Check(){
String random;
Scanner sc = new Scanner(System.in);
random = sc.nextLine();
ArrayDeque<Character> stack = new ArrayDeque<Character>();
stack.push('n');
stack.push('h');
stack.push('o');
stack.push('j');
for(int i=0;i<random.length();i++){
if(random.charAt(i) == stack.peek()){
stack.pop();
}
if(stack.size() == 0){
return true;
}
}
return false;
}

Verifying a String for Numbers and Periods/Decimals

I have this short snippet of code where I have to check a string to see if it contains integers and possibly a decimal. The string is an amount of money (12.34) so as well it can not go past the fourth index.
My question is I'm being told to use charAt() (and in my code I used matches() and contains() which is wrong) to check for integers and decimals so that this routine will return a boolean that is true if the string works with those parameters, however I'm confused at how to go about converting this to use charAt() instead of matches() and contains().
As well, I'm sorry if I formatted this wrong, or worded something wrong, or the code looks awful, I'm in my first semester of Java and it's my very first programming class I've ever taken so I'm a bit rough.
import java.util.Scanner;
public class Auction
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String price;
String quantity;
System.out.print("How much money are you willing to bet on this item?: $");
price = keyboard.next();
if(price.matches("[0-9]*") && price.length() <= 5)
{
Float f = Float.parseFloat(price);
System.out.printf("$%5.2f", f);
System.out.println();
}
else if(price.matches("[0-9]*") && price.length() <= 5 && price.contains("."))
{
Float f = Float.parseFloat(price);
System.out.printf("$%5.2f", f);
System.out.println();
}
else
{
System.out.println("Invalid input");
}
System.out.print("What quantity do you want to bid on?: ");
quantity = keyboard.next();
if(quantity.contains("."))
{
System.out.println("Invalid input");
}
}
}
I am typing this from a phone. So excuse the mistakes please. have u been asked by your professor to use charAt instead of regex and matches?
if (inpString!= null && !inpString.isEmpty () && inpString.length() <= 5){
int periodCount = 0;
for (int i=0; i < inpString.length (); i++){
char c = inpString.charAt (i);
if (c == '.'){
periodCount++;
}else if (c >= '0' && c <= '9'){
}else {
System.out.println("invalid output");
break;
}
if(periodCount > 1){
System.out.println("too may periods. Invalid output");
break;
}
}
}else {
System.out.println ("invalid input");
}
Can you comment if u need to check that there are no thousandth digit i.e 1.234? If yes make sure
inpString.substring
(inpString.lastIndexOf
(".")).length < 3
with all the null and indexOutOfBounds checks
How about this way?
import java.util.Scanner;
public class Auction {
private static final String numberRegex = "^\\d*(\\.\\d+)?$";
private static final String integerNumber = "^\\d*$";
private static final int MAX_LENGTH = 5;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String price;
String quantity;
System.out.print("How much money are you willing to bet on this item?: $");
price = keyboard.next();
if (price.length() <= MAX_LENGTH && price.matches(numberRegex)) {
Float f = Float.parseFloat(price);
System.out.printf("$%5.2f\n", f);
} else {
System.out.println("Invalid input");
return;
}
System.out.print("What quantity do you want to bid on?: ");
quantity = keyboard.next();
if (!quantity.matches(integerNumber)) {
System.out.println("Invalid input");
}
}
}

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