JAVA Intellij Coding - java

String marital = (String) JOptionPane.showInputDialog("Are you a single or married joint filer?");
while ((marital.length() >= 6) && (marital.length() <= 7)) {
System.out.println("You are " + marital + " thank you.");
if (marital.length() > 7) {
break;
}
}
im pretty new to Java so i was wondering how i could stop the while loop from printing more than one line. The objective is that the user will say single or married but i dont know how to only print it once

Just put break; after print, just like that, no if or anything. Right now you have your break inside if, that checks condition that will for sure fail, because if there was a possiblity that marital.length > 7 then it wouldn't even enter this while loop, since you are making sure that it's length is 7 or lower. All this code is weird tho, you are probably doing all this to train/learn, but I suggest just doing this:
String marital = (String) JOptionPane.showInputDialog("Are you a single or married joint filer?");
if ((marital.length() == 6) || (marital.length() == 7)) {
System.ou.tprintln("You are " + marital + " thank you.");
}
That will check if martital length is 6 OR 7 (you had something like that in your code, expressed in a convoluted way) and if yes then it's gonna print your sentence.

Related

Validating user input in java?

My guessing game takes either 5, 10, or 20 guesses from a user and they are supposed to try to guess a random number chosen by the computer. Everything in my code is working except this: when the code asks the user whether they want 5, 10, or 20 guesses, if the user were to enter 15, for example, which is not one of the options, it goes on and starts asking for their guesses. I need some type of validation that will make sure they enter one of the options. I'm not sure where or how to include this in the correct way since I am new to programming. I've tried several different ways but get errors for all. What I need is if the user puts a number that is not one of the options, it should just ask them again until they input one of the options. Can someone show me how I should do this?
First of all if (answer.length() ==3) makes no sense.
Maybe you meant:
if(answer.equals("yes"))
Besides, to accomplish what you want I would use a Set containing the valid guesses numbers. It is scalable and makes much more sense than checking against multiple values in an if clause. It will look like this:
Set<Integer> validNumberOfGuesses = new HashSet<Integer>(Arrays.asList(5, 10, 20));
int numberOfGuesses = scan.nextInt();
while (!validNumberOfGuesses.contains(numberOfGuesses)) {
/* ask again */
System.out.println(numberOfGuesses + " is not a valid number of guesses, please try again");
numberOfGuesses = scan.nextInt();
}
Take input from the user inside a loop. For example:
System.out.print("How many guesses would you like? (5, 10, 20)");
do {
int numberOfGuesses = scan.nextInt();
//on correct guess, break out of the loop
if(numberOfGuesses == 5 || numberOfGuesses == 10 || numberOfGuesses == 20)
break;
System.out.print("Please enter a guess having one of these values (5, 10, 20)");
} while (true);
Unless the user, enters one of the three values, he/she will kept being prompted to enter a correct guess value.
Java has the continue keyword that jumps to start of the current loop when run. See The Continue Statement documentation.
Once you have your user input you can do something like
if (numberOfGuesses != 5 && numberOfGuesses != 10 && numberOfGuesses != 20) {
continue; // jumps to start of while loop block, without running conditional
}
When you receive the "numberOfGuesses" you should check the value of that number before moving on. Otherwise you just move on in your code because you don't actually validate the number.
It may be a good idea to creat a function that returns a boolean value and then you can check the number there.
boolean isValidOption(int number)
In the function you want to perform some comparison and validate. Since you have three options you can opt for something like
if (number == 5 || ... )
You can consider how you'll verify the value as there are many ways. Just compare with valid numbers you know you want, you can do some if statements, or place the numbers in an array and compare the value while iterating through the array, and so on. Hope that helps you get started and happy coding!
Edit: Lastly I should have mentioned, but you need to consider the flow of your code. A loop of somesort like while(!isValidOption()) for your check should be use. Loop around the instructions until the user enters a valid option. You need to consider order of operations here in your code and understand the computer doesn't think for you. It does what you tell it, so understand what you are trying to tell it here. I want to step into my game, if and only if, the condition of isValidOption is met for example.
What you need to do is to stay in the loop until you get input that satisfy your demands for example you can use the following function
private int getNumberOfGuesses(Scanner scan) {
int numberOfGuesses;
boolean numberOfGuesesIsValid;
do {
System.out.println("How many guesses would you like? (5, 10, 20)");
numberOfGuesses = scan.nextInt();
numberOfGuesesIsValid = numberOfGuesses == 5 || numberOfGuesses == 10 || numberOfGuesses == 20;
if (!numberOfGuesesIsValid) {
System.out.print("Wrong option !!!");
}
} while (!numberOfGuesesIsValid);
return numberOfGuesses;
}
you can write your code inside a loop to make sure the value is either 5,10 or 20
while(numberOfGuesses!=5||numberOfGuesses!=10||numberOfGuesses=!20);
and the condition if(answer.length()==3 can cause errors. it means it will work every time the input is of length 3,even "noo"

Implementing Java code for a betting game on coin-flips [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have looked all over this website and other websites trying to figure how to do this with the knowledge that my teacher has provided me.
Basically the program is supposed to be a user input system where you can make bets on a head or tails coin flipping game.
So far, I've had no luck in what to do. Not asking someone to finish it for me, but to help me in the right direction.
Thank you in advance.
Here is my code so far:
package Homework6;
import java.util.Scanner;
import java.lang.Math;
public class CoinFlip {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
int money = 10;
double flip = Math.random();
String heads = "heads";
String tails = "tails";
int bet = input.nextInt();
while(bet < 0 || bet > money){
if(true){
System.out.println("How much do you want to bet?");
input.next();
}
}
System.out.println("Guess if the coin will be heads or tails.");
String guess = input.next();
String coin;
if (flip <0.5) coin = heads;
else coin = tails;
if(guess == coin){
int correct = money + bet;
System.out.println("The flip was"+ coin);
System.out.println("You win" + bet);
System.out.println("")
}
}
}
To fix the possible infinite loop:
do{
System.out.println("How much do you want to bet?");
bet = input.nextInt();
}
while(bet > 0 && bet > money);
You can drop the if statement since it's not really needed. You will however need to declare the variable bet to have the correct scope.
if(guess.equals(coin)) // proper way of checking Strings
Use this form for checking the value of the guess vs the coin.
A few notes for you (since you're starting out and still a student):
1) Your while loop is a little bit poorly constructed. That System Out will constantly be printing to the screen until there is some input. And that if statement is essentially doing no conditional checking. It is always true.
2) You never originally prompt the user for how much they want to bet. You're only prompting them after they've input a value. So when you originally hit play, the console is just blank. But really it's waiting for some input.
3) Your if statement for changing the coin state is a little extraneous.
4) The user's amount of money is never actually updated, and the output at the end could be a little more informative.
5) What if someone wins the first one and wants to play again? They probably want to keep that bank growing! So you could encompass the entire thing inside of a do/while that runs while bank > 0.
6) You should only use the == operator when comparing primitive types. Pretty much all other times, use Object.equals(object);
I know you didn't ask someone to complete it for you, but this site works best by sharing information. Below should work for you, I've commented it extensively. Hopefully this can teach some things beyond just this homework assignment.
public static void main(String[] args)
{
// Setup some initial variables
int bank = 10;
double flip = Math.random();
// Instantiate a new Scanner object
Scanner input = new Scanner(System.in);
// Let the user bet until they run out of money in the bank
do
{
// Ask the user how much money to wager
System.out.println("How much do you want to bet?");
int bet = input.nextInt();
// The bet was invalid
while(bet < 0 || bet > bank)
{
System.out.println("Invalid bet (" + bet + "). Minimum bet = 0. Maximum bet = " + bank);
bet = input.nextInt();
}
// Ask the user for which side
System.out.println("Heads or tails?");
String guess = input.next();
// The coin is either heads or tails, so it can always start as tails. If the value goes under .5, change it to heads. If not, it remains the same, "tails".
String coin = "tails";
if (flip < 0.5)
{
coin = "heads";
}
// Tell the user the result, regardless of win or lose
System.out.println("The flip was " + coin);
// Update the user's bank and inform them of the new value
if(guess.equalsIgnoreCase(coin)) // this allows for any form of HeaDs or TaILs
{
bank += bet;
System.out.println("You win " + bet);
System.out.println("Your bank contains " + bank);
}
else
{
bank -= bet;
System.out.println("You lose " + bet);
System.out.println("Your bank contains " + bank);
}
}
while(bank > 0);
// Goodbye message
System.out.println("Thanks for playing!");
// Don't forget to close your Scanner object!
input.close();
}
Alright, since you are having so much trouble with this, I will lay it out how I achieved this.
You need a couple variables, I used these below, taken from your code.
Scanner input = new Scanner(System.in);
int money = 10;
String heads = "heads";
String tails = "tails";
int bet = 0;
String guess;
String coin;
You then need a loop. You have a while loop already, and that will do, BUT your conditional is incorrect as I see it. You are testing bet < 0 || bet > money which I read as "If you bet less than no money or bet more money that you have, enter this loop" I believe you want the opposite of that. I also added if you ran out of money.
while(bet > 0 || bet < money || money <= 0)
Now for the inside of the loop. Here, you want to do a couple things in a certain order.
Ask how much they want to bet, read it in the appropriate variable.
Ask what their guess is, read it in the appropriate variable.
Use your if statement you have to determine if the flip was heads or tails, But I got rid of the flip variable, and used Math.random() < 0.5 directly.
Check their guess vs the flip. If they were correct, do what you need to do, i.e. add bet to money and display some sort of message.
If they were wrong, do what you need to do, i.e. subtract bet from money, display some message.
Then your program will start over.

Mastermind game if statement problems

I am trying to make it so when two or more of my if statements work they dont both print instead they just say two are in the correct spot or more it more works. Im not sure if im suppose to make more if statements of if i am suppose to use another statement or a forloop.
//If Statements
if (Gameboard[0] == Secret_code[0]) {
System.out.println ("You have one in the correct spot");
}
if (Gameboard[1] == Secret_code[1]) {
System.out.println ("You have one in the correct spot");
}
if (Gameboard[2] == Secret_code[2]) {
System.out.println ("You have one in the correct spot");
}
if (Gameboard[3] == Secret_code[3]) {
System.out.println ("You have one in the correct spot");
}
}
}
You can loop over Gameboard[x] == Secret_code[x] checks and print the total at the end.
EDIT: removed code in the spirit of promoting learning.
The solution "In words"
Instead of just checking whether the code is correct in each spot and then printing immediately, consider creating a variable which will count the number of times the peg has been correct. Then don't print anything until you know that the value of this variable has taken into consideration all of the elements of Secret_code (a good way (the "right" way)) to do this would be to loop through the Secret_Code array and use your new variable to count each time the code is correct.
Finally, print the message to the user using the variable which holds the information about how many are correct.
I won't include example code so you can be sure to implement and understand it yourself :-)
You could create a compound condition
if(cond1 || cond2 ||.....){print};
The nature of Java is that once the first true condition is encountered, further evaluation stops and the print statement is executed. This is just one of many solutions. But if your array index is huge, I don't recommend my solution since a compound condition should only be about 3 or 4 at most, IMHO.
if (Gameboard[0] == Secret_code[0]) {
System.out.println ("You have one in the correct spot");
}
if (Gameboard[1] == Secret_code[1]) {
System.out.println ("You have one in the correct spot");
}
if (Gameboard[2] == Secret_code[2]) {
System.out.println ("You have one in the correct spot");
}
if (Gameboard[3] == Secret_code[3]) {
System.out.println ("You have one in the correct spot");
}
should be changed to something akin to
private static final String[] numbers = {zero, one, two, three, four};
int correctCount = 0;
for(int i = 0; i < /*4*/ GameBoard.length; i++) {
if(Gameboard[i] == Secret_code[i]) {
currentCount++;
}
}
System.out.println("You have " + numbers[currentCount] + " in the correct spot.");

How to make a proper if-else statement given multiple rules to run the program

Hello i need to invent a baccarat game.. now on top of that there are rules given that i need to follow to make the game successful. the problem is im getting confused with my if-else statement. Idk which should come first. and which shouldnt. sometimes when i run it it looks good but when i run it several times with different random numbers being produced, it seems like none of my if-else statement works( under the //rules section). Please help!
EDITED:(new //rules)
//rules
if(sumPlayer > 7 && sumPlayer <10) {
System.out.println ( " Natural! No cards are drawn. ");
} else if (sumPlayer <6){
System.out.println ( " Player must draw to a hand of 5 or less." +
"\nPlayer draws a third card: " +c3+ " .");
} else if(c3 > 5){
System.out.println ( " Player stands a pat. ");
} else {
System.out.println ( " Player's hand is now : " +sumC3+ " .");
}
You want to deal with the player and dealer's hands separately. In a series of if/else decisions, only one branch can ever be selected. This means the conditions tested inside a set of if/else statements should be mutually exclusive. If you test conditions of your hand, and then the dealers hand, those two conditions may both be possible at the same time, but if/then code can't handle both.
Here's some pseudocode that illustrates this:
if(test my hand 1) {
do something with my score
} else if(test my hand 2){
do something with my score
} else if(test my hand 3){
do something with my score
} else {
do a default thing with my score
}
if(test dealer hand 1) {
do something with dealer score
} else if(test dealer hand 2){
do something with dealer score
} else if(test dealer hand 3){
do something with dealer score
} else {
do a default thing with dealer score
}
By the way - when you show which player wins, you might want to show the score too. It's good for debugging and also nice to let the user know how well they played.

Checking values in boolean array (Java)

I am having som slight difficulties with the following problem.
I have initialized a boolean array called numberArray with 31 indexes. The user is supposed to enter 5 digits between 1 and 30, and each time a digit is entered, the program is supposed to set the proper index to true. For instance, if I enter 5 then:
numberArray[5] = true;
However, if the user enters the value 5 a second time, a message should be given to the user that this number has already been entered, and so the user has to choose a different value. I have tried to create a loop as follows:
public void enterArrayValues() {
for(int i = 1; i < 6; i++) {
System.out.print("Give " + i + ". number: ");
int enteredNumber = input.nextInt();
while (numberArray[enteredNumber] = true) {
System.out.println("This number has already been chosen.");
System.out.print("Give " + i + ". number again: ");
enteredNumber = input.nextInt();
}
numberArray[enteredNumber] = true;
}
}
The problem is that when I run the program, I automatically get the message "The number has already been chosen" no matter what I enter. Even the first time I enter a number. I don't get this. Isn't all the values in the boolean array false by default?
I would greatly appreciate it if someone could help me with this!
while (numberArray[enteredNumber] = true) {
make that
while (numberArray[enteredNumber] == true) {
or change to
while (true == numberArray[enteredNumber]) {
or simply drop the ==true
while (numberArray[enteredNumber]) {
while (numberArray[enteredNumber] = true)
is an assignment, use the == operator or simply while (numberArray[enteredNumber]).
I know its hard to get into while you are still learning, but the earlier you start coding in an IDE the better off you will be. This is one tiny example of something an IDE will warn you about.
Change the while line to:
while (numberArray[enteredNumber]) {
Because mistakenly entering = instead of == is a common mistake, some people always code this type of statement in the following manner:
while (true == numberArray[enteredNumber]) {
With this format, if you use = instead of ==, you will get a compiler error.
Also, if you use a type of static analysis tool such as PMD, I believe you get a warning for the statement that you originally wrote.
Thde problem is in the condition of the while loop - you are using the assignment operator (=), whereas you are supposed to use the equality comparer (==). This way the loop condition is always true, because you are assigning true to the indexed field.
I hope this will work :-) .
The condition in the while loop should be while (numberArray[enteredNumber] == true). You're using the assignment operator =, not the comparison operator ==. Assignment is an expression that returns the assigned value, which is true in your case.

Categories

Resources