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.");
Related
I apologize if this question is uber-simplistic, but I'm still in the early stages of learning Java. I have an example program that calls other methods within the class, and I'm not totally following a few of the elements - hoping someone can clarify. It's a simply random number guessing game and it works fine, but I want to better understand some components. Specifically:
There is a boolean variable (validInput) that is declared but never appears to be used anywhere in the methods
There are 2 methods (askForAnotherRound and getGuess) with a 'while' loop that just has 'true' as the variable(?) - i.e. "while (true)."
This code is directly from the example in the book and, again, it works. I just want to better understand those 2 elements above. (I think the validInput variable is not useful as when I 'comment out' that line the code still executes). I'm curious, though, about the "while (true)" element. There is an option to set, in the askForAnotherRound, to set the return value to false (ending the program). Are boolean methods defaulted to 'true' when they are first executed/called?
Again...understand this is probably a super-simple question for most folks on here, but as a newb I just want to understand this as best I can...
Thanks!!!
// Replicates the number guessing game using 4 separate methods.
import java.util.Scanner;
public class GuessingGameMethod2
{
static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("Let's play a guessing game!");
do
{
playARound();
}while (askForAnotherRound());
System.out.println("Thanks for playing!");
}
public static void playARound()
{
boolean validInput;
int number, guess;
String answer;
//Pick a Random Number
number = getRandomNumber();
//Get a guess
System.out.println("\nI'm thinking of a number between 1 and 10.");
System.out.print("What do you think it is? ");
guess = getGuess();
//Check the guess
if (guess == number)
System.out.println("You're right!");
else
System.out.println("You're wrong! The number was " + number + ".");
}
public static int getRandomNumber()
{
return (int)(Math.random() * 10) + 1;
}
public static int getGuess()
{
while (true)
{
int guess = sc.nextInt();
if (guess < 1 || guess > 10)
{
System.out.print("I said, between 1 and 10. Try again");
}
else
return guess;
}
}
public static boolean askForAnotherRound()
{
while (true)
{
String answer;
System.out.print("\nPlay again? Y or N: ");
answer = sc.next();
if (answer.equalsIgnoreCase("Y"))
return true;
else if (answer.equalsIgnoreCase("N"))
return false;
}
}
}
I don't see boolean validInput being used either. But if it were to be used somewhere it would probably be to check that you guess satisfies 1 <= guess <= 10.
When it comes to askForAnotherRound and getGuess here's what you should know:
while(true) is always executed. One way you can get out of the while loop is if you use the break statement or if the loop is in a function you can return something. The method askForAnotherRound() will always return either true or false. Depending on the returned value of askForAnotherRound() you will either play another round or not. Note that when you have
`do{
...
someActions()
...
}while(booleanValue)`
someActions() will be executed at least once before it checks for the value of booleanValue which, if it turns out false you'll exit out of the do/while loop. Boolean methods do not default to anything, you have to give them a value.
Hope this helps! I'm also in the process of learning Java right now, so good luck!
As I see you're absolutely true about validInput - it isn't used. May be it will be used in the following chapters.
As for askForAnotherRound() - no, boolean methods don't evalute to true, by default. Even more, Java compiler throw an error if it find a method which does not return value and finish it execution in some cases.
while(true) - it's infinite loop, so it will be executed untill some instruction which interrupts loop, in general it's return statement.
askForAnotherRound() do the following:
- asks user if he/she want to play again
- returns true if user input "Y"
- returns false if user input "Y"
- asks again in all other cases(so it doesn't finish execution) and etc.
Hope it'll help
The validInput is indeed worthless.
The infinite loops are required to read from the console to get a valid input. e.g
while (true)
//start infinite loop
{
int guess = sc.nextInt();
if (guess < 1 || guess > 10)
{
//continue the loop the input is not between 1-10
System.out.print("I said, between 1 and 10. Try again");
}
else
//break out of infinite loop, valid int
return guess;
}
If we take this method without the infinite loop, and i recommend trying this, it will simply return the value read even if it was not valid.
For example.
return sc.nextInt();
will allow any int returned, if we returned anything outside of the bounds in the current impl it would loop again until you enter a value between 1-10
The same is also true for ask for next round, its looping until a valid input is given.
I would bet the next exercises will use the validInput var as both these methods loop until a valid input is given.
You are right about validInput. It is not used. And probably missed after some code change. Should be removed.
while(true) - true is not variable but a boolean constant. It will basically make program run for ever in this case unless somebody kills program. Another alternative would have been to use break to exit out of loop on some condition.
I have recently started a course where the main language we are learning at the moment is Java.
I have been tasked with creating a program that allows people to vote on two candidates - the program then counts the votes, and depending on how man votes have been made depends on what is displayed.
Here is the part I am concerned with at the moment:
public String printResults(){
if(candidate1Votes == 0 && candidate2Votes == 0)
{
System.out.println ("No votes cast, results cannot be displayed.");
return "No votes cast, results cannot be displayed.";
}
else if(this.completed == false)
{
System.out.println ("Voting has not finished");
return "Voting has not finished";
}
else if(this.completed == true)
{
System.out.println ("Voting has finished, no more votes will be allowed.");
return "Voting has finished, no more votes will be allowed";
}
{
double totalVotes = this.candidate1Votes + this.candidate2Votes;
double cand1Share = (double) this.candidate1Votes/totalVotes*100;
double cand2Share = (double) this.candidate2Votes/totalVotes*100;
System.out.format(candidate1 + " received %3.1f percent of the votes\n", cand1Share);
System.out.format(candidate2 + " received %3.1f percent of the votes\n", cand2Share);
return "v";
}
}
Originally I used void in this method, but part of our task was to then change it to a string value. This is where I am struggling - once I set completed to true, it is still allowing me to cast votes. I know that this code is incomplete but I can't finish it as I am unsure what to do! These were the next parts to the questions.
Modify your printResults method so that it applies the first two rules. Note that the value of the completed field indicates whether or not voting is complete. The method should be modified to return a String which indicates whether printing has been successful.
Modify your vote method to apply the third rule.
Test your methods by creating an instance and doing the following – before
doing each test note the result you expect to get, and compare this with what you actually get:
• Try to print results immediately
• Cast votes for both candidates and try to print results
• Set the completed field to true by calling setCompleted
• Try to cast a vote for a candidate
• Print the results
I am new to this (this is my first year) and have managed to do okay in my books to get this far, however any help on this next issue would be greatly appreciated!
First of your code is unnecessary complicated, which makes it hard to read/enhance. It can easily simplified, like
public String printResults(){
if(candidate1Votes == 0 && candidate2Votes == 0) {
System.out.println ("No votes cast, results cannot be displayed.");
return "No votes cast, results cannot be displayed.";
} // you returned ... NO need for ELSE!
if(this.completed == false) {
System.out.println ("Voting has not finished");
return "Voting has not finished";
}
// it is very clear here that completed must be true!
double totalVotes = this.candidate1Votes + this.candidate2Votes;
double cand1Share = (double) this.candidate1Votes/totalVotes*100;
double cand2Share = (double) this.candidate2Votes/totalVotes*100;
System.out.format(candidate1 + " received %3.1f percent of the votes\n", cand1Share);
System.out.format(candidate2 + " received %3.1f percent of the votes\n", cand2Share);
return "v";
}
Probably that easier-to-read code is all that you need to get you going!
Looking at the code the last block will never be reached because either you have no votes or you have votes and in that case completed will be either true or false and will thus reach always one of the else ifs and they all return a string. So I wonder why how you can cast any votes at all.
You could also post the code where you call printResults and setCompleted to see where the problem lies.
Some more hints for improving your code:
Sometimes you have the opening bracket on the same line and sometimes on the next. You should probably choose one style
It is not necessary to surround the last code block with brackets
if (this.completed == true) and else if (this.completed == false) is a bit redundant and can be written like: if (this.completed) and if (!this.completed). Also you can write
if (this.completed) {
...
} else {
....
}
because if completed is not true it can only be false.
Instead of writing every String two times and having to edit it two times in case you want to change something you could also do the following:
String msg = "Voting has not finished"
System.out.println(msg);
return msg;
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.
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.
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.