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;
}
}
Related
I've read that I would need to put "continue" after an "if" statement, but every I tried this with my if statement and it states that "continue cannot be used outside of a loop."
Set it in the loop. EX:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true){
System.out.print("Enter a password: The password must have at least eight characters, only letters and digits, and at least two digits. ");
String s = input.nextLine();
if (thepassword(s)) {
System.out.println("Valid Password");
break;
} else {
System.out.println("Invalid Password");
}
}
}
See more : Java Break and Continute
Use an outer infinite loop with a lable, then break the loop using break loop_lable. Check until a valid input is made.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a password: The password must have at least eight characters, only letters and digits, and at least two digits. ");
loop:for(;;)
{
String s = input.nextLine();
if (thepassword(s))
{
System.out.println("Valid Password");
break loop;
}
else
{
System.out.println("Invalid Password");
continue loop;
}
}
input.close();
}
public static boolean thepassword(String password) {
boolean thepassword = true;
if (password.length() < 8) {
thepassword = false;
} else {
int totaldigits = 0;
for (int n = 0; n < password.length(); n++) {
if (thedigit(password.charAt(n)) || theletter(password.charAt(n))) {
if (thedigit(password.charAt(n))) {
totaldigits++;
}
} else {
thepassword = false;
break;
}
}
if (totaldigits < 2) {
thepassword = false;
}
}
return thepassword;
}
public static boolean theletter(char c) {
return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'));
}
public static boolean thedigit(char c) {
return (c >= '0' && c <= '9');
}
}
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;
}
I really do not know to how explain this but here we go.
I am testing something for a bigger program I have to make. In the program I have to validate input from the user to see if it is being to be accepted as a valid answer.
I have the code to where it will say if the input is invalid but if I attempted to enter another letter the code crashes with this error:
Enter a letter:
f
Your answer is not valid.
A
Enter a letter:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:695)
at example.main(example.java:18)
Here is the code:
import java.util.Scanner;
public class example
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
boolean UserInput;
do
{
char user_answer = 0;
System.out.println("Enter a letter:");
user_answer=input.nextLine().charAt(0);
if ( user_answer == 'A')
{
UserInput = true;
}
else if (user_answer == 'B')
{
UserInput = true;
}
else if (user_answer == 'C')
{
UserInput = true;
}
else if (user_answer == 'D')
{
UserInput = true;
}
else
{
System.out.println("Your answer is not valid.");
UserInput = false;
input.next();
}
}
while (!UserInput);
}
}
either remove input.next() or change it to input.nextLine()
What's happening is that input.next() will catch the A you input. Then you go back to the beginning of the do and start over, and do input.nextLine() but you had already pressed enter to input A and the A was consumed by input.next().
Remove the input.next(); and it will work fine. The reason is because when you use input.next(), it reads the next character the user types, without exiting the line. Then when the input.nextLine() executes, it reads that same line, but immediately after the number. Since nothing is after the number, it reads in nothing "" and the charAt(0); becomes out of bounds.
import java.util.Scanner;
public class Example
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
boolean UserInput;
do
{
char user_answer = 0;
System.out.println("Enter a letter:");
// user_answer=input.nextLine().charAt(0);
user_answer=input.next().charAt(0);
if ( user_answer == 'A')
{
UserInput = true;
}
else if (user_answer == 'B')
{
UserInput = true;
}
else if (user_answer == 'C')
{
UserInput = true;
}
else if (user_answer == 'D')
{
UserInput = true;
}
else
{
System.out.println("Your answer is not valid.");
UserInput = false;
// input.next();
}
}
while(!UserInput);
}
}
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 =
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.