Calling an Integer into a Boolean - java

The section of my code that isn't working
}else if(bossOne == 3){
int bossOneHP = 70 + bossStat.nextInt(10)-5;
int bossOneOP = 27 + bossStat.nextInt(10)-5;
int bossOneBP = 12 + bossStat.nextInt(10)-5;
String bossName = "Spartan King";
waits();
System.out.println("Your first enemy is the Spartan King.");
System.out.println("It has a very powerful attack, lets hope you have enough health.");
}
boolean keepPlaying = true;
while (keepPlaying){
Scanner choice = new Scanner(System.in);
System.out.println("Enter 1 to attack.");
System.out.println("Enter 2 to block.");
System.out.println("Enter 3 to exit the game.");
int selection = choice.nextInt();
if (selection == 1){
waits();
System.out.println("You attack.");
System.out.println(bossOneHP == bossOneHP - (OP - bossOneBP));
}else if(selection == 2){
waits();
System.out.println("You block.");
System.out.println(HP == HP - (bossOneOP - BP));
}else if(selection == 3){
break;
}
if (bossHP == (0 || >0){
System.out.println("Congratulations you won!");
break;
}
if (HP == (0 || >0)){
System.out.println("Sorry you lost.");
break;
}
I need to have the integers be called to the section. This code is for the meat of the game I am creating for my programming class any help would be appreciated.

You want the 'greater than or equal to' operator: >=
if (bossHP >= 0){
System.out.println("Congratulations you won!");
break;
}
if (HP >= 0){
System.out.println("Sorry you lost.");
break;
}

OK, so I'm not sure exactly what is supposed to do what but I will give it a try. It looks like you got a little confused.
For example:
if (selection == 1){
waits();
System.out.println("You attack.");
System.out.println(bossOneHP == bossOneHP - (OP - bossOneBP));
}else if(selection == 2){
In this code you seem to be printing to console a comparison of the variable bossOneHP and bossOneHP - (OP - bossOneBP), which I think is not what you intended as the statement would print true only if (OP-bossOneBP) was zero (basic algebra). What I suspected you intended:
if (selection == 1){
waits();
System.out.println("You attack.");
bossOneHP = bossOneHP - (OP - bossOneBP);
}else if(selection == 2){
This sets the variable bossOneHP to itself minus (OP minus bossOneBP). Note you can also do it like this:
if (selection == 1){
waits();
System.out.println("You attack.");
bossOneHP-= OP - bossOneBP;
}else if(selection == 2){
Which is faster. -= sets a value to itself minus the following value as opposed to = which just sets it to the new value. Also == does a comparison returning true if they are equal while = sets a variable to a new value.
Second issue:
if (bossHP == (0 || >0){
I am assuming you want to activate the if statement if bossHP is less than or equal to zero. The || statement is a boolean operator (It compares the two boolean inputs on either side, whether that be a variable or a comparison or a function, and returns a single boolean value of true if either input was true), and does not function like the word or. To compare two numbers (in this case the variable bossHP and zero), you use one of several operators. They are as follows:
== -returns true (which activates the if statement) if the numbers or objects (if they are the same instance, not if they contain equal values) on both sides are identical.
< -returns true if the left hand number is smaller than the right hand one (doesn't work on objects)
> -returns true if the right hand number is smaller
<= -returns true if the left hand number is smaller or equal to the right hand number
>= -returns true if the right hand number is smaller or equal to the left hand number
!= -returns true if the numbers or objects do not equal each other (effective opposite of the == token)
! -only takes one boolean on the right hand side and returns its opposite (this inverts the value essentially), if(!val) is equivalent and better to if(val == false)
The correct code would probably be something along the lines of:
if (bossHP >= 0){
System.out.println("Congratulations you won!");
break;
}
also instead of doing the while(keepPlaying) thing you could also do while(true) and run a break; command when 3 is inputed

Related

while loop working differently in different projects, but the same code structure?

I've written this code:
while (choice > 2 && count <= 2) {
System.out.println("The number you have typed is invalid. Please try again.");
choice = s.nextInt();
count++;
}
if (choice == 1 && count <= 2) {
System.out.println("You have chosen teacher's information.");
t.information();
} else if (choice == 2 && count <= 2) {
System.out.println("You have chosen student's information.");
st.info();
} else {
System.out.println("You have been blocked.");
}
It works how I intended to, if I try more than 2 times, I'll be blocked, however, in this other project:
while (!rusern.equalsIgnoreCase(username) || !rpass.equals(password) && attempts <= 2) {
System.out.println("Login error. Your username is: " + rusern.equalsIgnoreCase(username) + " ,and password is: " + rpass.equals(password) + "\nPlease try again.");
System.out.println("Please enter your username:");
rusern = s.nextLine();
System.out.println("Enter your password:");
rpass = s.nextLine();
attempts++;
//here i have to use break;
}
if (rusern.equalsIgnoreCase(username) && rpass.equals(password) && attempts <= 2) {
System.out.println("You have succesfully logged in! Please continue: ");
} else {
System.out.println("You have been blocked.");
}
I have to use break; in the while loop, where I mentioned in the comment, because unless I used the break, it would show the questions over and over if I didn't answer correctly, without stopping, and when I finally answered right, it would have me blocked. So my question is, why wouldn't it work without the break like in the first project?
Both variables, the 'attempts' and 'count' and initialized the same, = 0.
a || b && c means a || (b && c) while I believe you intended it to mean (a || b) && c.
See Java operator precedence table: || and && don't have equal precedence.
So your loop should be:
while ((!rusern.equalsIgnoreCase(username) || !rpass.equals(password)) && attempts <= 2) {

Why is this causing a constant 'true' in this while loop?

Here is the code;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Do you need instructions for this game? Y/N.");
char a = input.next().charAt(0);
// This while loop always comes out as true.
while (a != 'y' || a != 'n') {
System.out.println("Please enter either Y/N. ");
System.exit(0);
}
if (a == 'y') {
System.out.println("This game is called heads and tails.");
System.out.println("You must type h (heads), or t (tails).");
System.out.println("You will need to keep guessing correctly, each correct guess will increase your score.");
}
}
}
Is there an explanation on why it always comes out as true, and is there an alternative way of doing this? I want to have a validation check, where if the user inputs anything other than y, or n, the program shuts down.
The problem is, when I enter the character, y, or n, it shuts down anyway even though I'm using the != (not equals) operator.
If you have a==y, then a != 'n' is true and a != 'y' || a != 'n' is true.
If you have a==n, then a != 'y' is true and a != 'y' || a != 'n' is true.
If you have a == other thing, a != 'y' || a != 'n' is true.
It is everytime true with the OR operation. Need use AND.
(a != 'y' || a != 'n') at least one of the sub-conditions must be true.
Consider the three possible cases:
a is 'y': false || true gives true
a is 'n': true || false gives true
a is something else: true || true gives true
The character a cannot both be y and n, so the while loop is executed for any input.
Besides, the loop is not looping.
You're checking whether a is not equal to 'y' OR a is not equal to 'n'.
This is always true.
Change it into while ((a != 'y') && (a != 'n')).
The condition inside while in
while (a != 'y' || a != 'n')
is always true because
if a is equal to y, then a is obviously not equal to n. So, result is true.
And again, if a is equal to n, then a is obviously not equal to y. So, result is true.
And again, if a is not equal to y or n, then also the result is true.
So, the condition inside the while is always true. And for this reason, the execution is entering the while loop and after printing your message it is exiting.
So using AND instead of OR may solve your problem, like
while(a != 'y' && a !='n') {
//your work
}
And I think you willing to do this like below,
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Do you need instructions for this game? Y/N: ");
char a = input.next().charAt(0);
while (a != 'y') {
if(a =='n') {
System.exit(0);
}
else{
System.out.println("Please enter either Y/N : ");
a = input.next().charAt(0);
}
}
if (a == 'y') {
System.out.println("This game is called heads and tails.");
System.out.println("You must type h (heads), or t (tails).");
System.out.println("You will need to keep guessing correctly, each correct guess will increase your score.");
}
}
}
Your logic should be "a is not y and a is not n"
while (a != 'y' && a != 'n')

Why does my do while loop keep going?

I'm trying to do a simple Hangman game for school.
In the beginning the user inputs a word as a String and the string is converted into a char Array, wordArray. Then a char Array starArray is created that has the same amount of elements as wordArray, and is filled with "*". Those start get replaced with letters as the letters are guessed correctly.
After this, I have this loop:
do {
System.out.println("Guess a letter:");
strGuess = scan.nextLine();
chGuess = strGuess.charAt(0);
//prompts the user to guess a letter and converts said letter to a char
for(int i = 0; i<Array.getLength(wordArray); i++){
if (chGuess == wordArray[i]){
starArray[i] = strGuess.charAt(0);
guessCorrect = true;
}
} //this happens if the guess is correct
if (guessCorrect == false){
System.out.println("Nope, wrong guess!");
wrongGuess = wrongGuess + 1;
System.out.println("You have " + (5-wrongGuess) + " lives left.");
} //if the guess isn't correct, amount of wrong guesses increases
guessCorrect = false; //the value of whether a guess is correct resets
for(int i=0;i<starArray.length;i++){
System.out.print(starArray[i]);
} //prints out the word with "*" in place of letters that haven't been guessed yet
/*if starArray == wordArray
wordGuessed = true;*/
} while (wrongGuess == 5 || wordGuessed == false); //if the word is guessed or the user has guessed wrong 5 times, the loop ends
Now this code isn't complete yet, so the "wordGuessed" part of the condition can never happen as of now - you can't win the game yet. However, the loop doesn't end when the wrongGuess value gets higher than 5. It will keep going, prompting the user to guess again and again. I checked and the wordGuessed value does in fact change correctly, do it does reach 5 after 5 wrong guesses.
If wordGuessed is always false, wordGuessed == false will always return true.
The condition to loop is that wrongGuess == 5 || wordGuessed == false is true.
Using the first statement, that could be replaced by: wrongGuess == 5 || true
That will also always be true as anything OR true is true.
You want to stop looping once (wrongGuess == 5 or wordGuessed == true).
In other words, loop while !((wrongGuess == 5) OR (wordGuessed == true)).
Basic boolean algebra, the reverse of A OR B is !A AND !B. You have to keep looping while wrongGuess != 5 && wordGuessed == false

Is it possible to use a boolean expression in this manner?

I am currently learning java script and attempting new things, for example I wish to see if I can set a boolean expression to end if it detects a starting number through an ending number.
Or in other terms what I'll want is 3 through 8.
I will make it clear I am using netbeans IDE.
Within my last else if statement, I want it to end the asking process. I am hoping it is a simple fix, but I can not think of anything that will accomplish this unless I create a lot more else if statements.
Scanner input = new Scanner(System.in);
int[][] table;
boolean stopasking = true;
while (stopasking = true){
System.out.println("Let's make a magic Square! How big should it be? ");
int size = input.nextInt();
if (size < 0)
{
System.out.println("That would violate the laws of mathematics!");
System.out.println("");
}
else if (size >= 9)
{
System.out.println("That's huge! Please enter a number less than 9.");
System.out.println("");
}
else if (size <= 2)
{
System.out.println("That would violate the laws of mathematics!");
System.out.println("");
}
else if (size == 3)
{
stopasking = false;
}
}
You have used the assignmnent operator =
you should use == instead
also the condition size<=2 holds when size<0 so you can use one if for both
while(stopasking){
if (size <= 2) {
System.out.println("That would violate the laws of mathematics!\n");
} else if (size >= 9){
System.out.println("That's huge! Please enter a number less than 9.\n");
} else if (size == 3){
stopasking = false;
}
}
you can use the boolean expression in this way, as condition to exit from a loop. Some would say it is a more elegant solution than break.

Rock Paper Scissors Lizard Spock

My assignment:
Create a tester that creates two HandGamePlayer objects (default constructor for cpu full constructor for human), play for 3 rounds by asking the user for a choice of sign (1-5 now), outputting the two players signs, and outputting who won. Once all rounds are done, output the stats and declare the overall winner!
Been working on this all day, can anyone explain to me how to get the sign symbol to recognize? My professor tried to explain to me what to do but I'm just lost...
This is what he said to do, but I don't even know what it means:
"sign is not declared within main, so it says that the symbol can’t be found. You generated a hand sign, but printed it out and didn’t store it! Instead make an int sign; variable and store the hand sign there (still print it out, but now you’ll be able to use it in your multi-way if/else)"
Check out my code and let me know if you guys got any ideas.
HandGameTester.java
//MAIN
import java.util.Scanner;
public class HandGameTester
{
public static void main(String[] args)
{
Scanner keyboard;
HandSign hs;
int sign;
int handSign;
int win = 0;
int loose = 0;
int tied = 0;
int loopCount;
keyboard = new Scanner(System.in);
hs = new HandSign();
hs = sign;
System.out.println("Pick A Choice Below To Play");
System.out.println("1: Rock");
System.out.println("2: Paper");
System.out.println("3: Scissors");
System.out.println("4: Lizard");
System.out.println("5: Spock");
handSign = keyboard.nextInt();
System.out.println("You chose " + handSign);
hs.printHandSign(hs.getHandSign());
if(handSign == sign) {
System.out.println("You tied!");
tied++;
loopCount++;
} else if(handsign == 1 && sign == 2 || sign == 5) {
System.out.println("You loose!");
loose++;
loopCount++;
} else if(handsign == 1 && sign == 3 || sign == 4) {
System.out.println("You win!");
win++;
loopCount++;
} else if(handsign == 2 && sign == 1 || sign == 5) {
System.out.println("You win!");
win++;
loopCount++;
} else if(handsign == 2 && sign == 3 || sign == 2) {
System.out.println("You loose!");
loose++;
loopCount++;
} else if(handsign == 3 && sign == 2 || sign == 4) {
System.out.println("You win!");
win++;
loopCount++;
} else if(handsign == 3 && sign == 3 || sign == 5) {
System.out.println("You loose!");
loose++;
loopCount++;
} else if(handsign == 4 && sign == 2 || sign == 5) {
System.out.println("You win!");
win++;
loopCount++;
} else if(handsign == 4 && sign == 3 || sign == 4) {
System.out.println("You loose!");
loose++;
loopCount++;
} else if(handsign == 5 && sign == 1 || sign == 3) {
System.out.println("You win!");
win++;
loopCount++;
} else if(handsign == 5 && sign == 2 || sign == 4) {
System.out.println("You loose!");
loose++;
loopCount++;
} else {
System.out.println("You win!");
win++;
loopCount++;
} if((win > loose) || (win > tied)) {
System.out.println("You Win Best Out of Three!");
} else if(tied > win || tied > loose) {
System.out.println("You Tied!");
} else if(loose > win || loose > win) {
System.out.println("You loose!");
} else if(win == loose || win == tied) {
System.out.println("You tied!");
} else {
System.out.println("You Win Best Out of Three!");
}
}
}
HandSign.java
public class HandSign
{
public static final int ROCK = 1;
public static final int PAPER = 2;
public static final int SCISSOR = 3;
public static final int LIZARD = 4;
public static final int SPOCK = 5;
public static int getHandSign();
{
return (int)Math.random() * 5;
}
public static int printHandSign(int sign)
{
switch(sign)
{
case 1:
System.out.println("Rock");
return sign;
case 2:
System.out.println("Paper");
return sign;
case 3:
System.out.println("Scissor");
return sign;
case 4:
System.out.println("Lizard");
return sign;
case 5:
System.out.println("Spock");
return sign;
default:
System.out.println("Fatal Error");
System.exit(0);
}
}
}
}
There are numerous errors (but mostly unecessary variables) in your code.
I suppose you can tell your professor that he or she was wrong in that sign was, in fact, declared, but it was not initialized. Examine the beginning of your main() method. One line simply states,
int sign;
This is a declaration -- you are telling the program that the sign variable exists. However, you are not setting it equal to anything -- you are not initializing it.
However, this is certainly not to say that your code is without other flaws.
Firstly, as stated, you never initialized sign. As you later set handSign equal to the nextInt of a System.in Scanner, we can assume that handSign is the user's chosen sign (Either rock, paper, scissors, lizard, or spok.) You then compare handSign with sign and state that, if they are equal to one another, then you tied with the computer. By this we can assume that sign is the computer's chosen sign. When your professor told you that you did not store a variable within sign, he was dead right! You declared sign, but never made the computer choose what sign was -- you never set it equal to anything.
Look at your HandSign class. You created the getHandSign() method which returns a random value, but you never called the method!
Secondly, you have a lot of unecessary variables.
Here's what you want to do:
In the main method, get rid of the hs variable. Why? Think about it -- there are only two players, and so there will only be two signs. You have three variables for signs -- hs, handSign, and sign. You then imply that handSign is the user's sign and sign is the computer's sign in your if statements. hs is not only unecessary, but it is implied that a sign is, in your program, typically an Integer while hs is of the type HandSign. Also, every variable and method within the HandSign class is static, meaning that any instance of the HandSign class is, in essence, useless.
Secondly, you created several constants within your HandSign class, but never used them. You could either get rid of them entirely, or substitute the numbers in the switch statement for the constants. For example, where it says:
case 1:
you could (and should) change it to:
case ROCK:
You could (and should) do the same thing in your several if / else statements in the HandGameTester main() method. (Note that you would have to reference the constants via the HandSign class -- HandSign.ROCK, etc.)
Finally, and most importantly, initialize the sign variable!
You created the static method which generates a random value between 1 and 5, but never called it, so call it:
int sign = HandSign.getHandSign();
This will call the getHandSign() method and set sign equal to the returned random value between 1 and 5.
"sign is not declared within main, so it says that the symbol can’t be found.
It looks like you added this with
int sign;
You generated a hand sign, but printed it out and didn’t store it! Instead make an int sign; variable and store the hand sign there (still print it out, but now you’ll be able to use it in your multi-way if/else)"
What this means is that you have two HandSign variables, one that you generate (hs) and another you are reading in from the user (sign). However, sign is an int and hs isn't. So you need to get an int from HandSign by calling HandSign.getHandSign() to get the one from the computer player.
You have never remembered the sign generated by getHandSign. You call
hs.printHandSign(hs.getHandSign());
Which prints out the sign the computer generated, but you never remembered this sign in a variable.
You appear to have have a variable for this you just never give it a value.
int sign; // defaults to zero as you have not given it a value
...
hs = new HandSign();
hs = sign; // This line wont compile.
...
if(handSign == sign) { // sign still has no value set so is still the default of zero.
You should be assigning a value to sign before doing your if...else if.... That assignment should look something like
sign = ????;
With the question marks replaced by a valid integer expression.
Some other posters have commented but I'll just add my 2 cents. There are a few problems I can see immediately.
There is no loop in main (unless I'm hallucinating) which means that
only one round will be played.
It would be nice for user interface if you printed out the computer's choice.
You've misspelled "lose" as "loose" which makes the code harder to
read.
Blank lines appear in the wrong places, or not at all, which also
makes the code hard to read and debug.
Huge problem: (int)Math.random() * 5 doesn't do what you want it to
do. Just create a small program that prints the result of that
calculation 10 times and you'll see. You need more parentheses, and also
you need to add 1 because you started counting at 1 instead of 0.
Alternatively, you could start counting at 0 instead, which (IMHO) is
better.
You exit with a fatal error with System.exit(0) but if it really is
an error the argument should be > 0, e.g., System.exit(1).
In addition, I agree with the other posters. However, it shouldn't be too hard to fix, really just a few minutes. Most of the hard work is done.

Categories