public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("How many of your two bosses are smiling?");
int smiles = in.nextInt();
final boolean trouble;
if(smiles == 0 || smiles == 2){
trouble = true;
}else if(smiles == 1){
trouble = false;
if(trouble == false){
System.out.println("The coast is clear!");
}
else if(trouble == true){
System.out.println("You're in trouble!");
}in.close();
}
This whole thing is stupid.
I need to basically make a boolean-using program that tells the user, via the number of bosses smiling, wether or not they are in trouble.
Both/Neither smiling = trouble
One smiling and the other not smiling = no trouble
But it will only print the given strings if there's no trouble.
I get that I'm a fukken idiot, and this whole task I'm required to do is, personally, kinda stupid. But whatever, moron can't do simple code. Maybe someone could tell me what stupid mistake I made so I can get this done and out of the way?
It's resolved, I'm an idiot who can't read the bracket placement/formatting properly. Also yes, it shouldn't have been a final, though changing that was not the resolution at first.
Change
final boolean trouble;
to
boolean trouble = false;
Your boolean value is final and thus cannot be modified, its default value is "false". That means that it is never changed from "false" no matter what happens next.
By the way, if a number larger than 2 is input, the boolean value will also be "false".
A check to see if the integer being input is in the right range (between 0 and 2) would be a good idea.
Related
Alright, so I'm trying to make a very rudimentary version of battleship in order to test out my one week's worth of programming knowledge. Basically, all the program does is have the user enter two numbers and those numbers are then used to locate a slot on a multidimensional boolean array. If the array's slot is true, it should say hit. If it is false, it should say miss. However, for some reason, no matter what I enter, I keep getting "Hit! Way to go!" Fortunately, the program is displaying an error for the "else" command. It says, "The following branch is never used." Unfortunately, I don't know why the branch is never used and I don't know how to fix it. Can I have some pointers, help, and/or advice? Thanks!
import java.util.Scanner;
class Battleship {
public static void main(String[] arguments) {
System.out.println(" Welcome to Battleship Solo Edition!");
System.out.println(" There are seven boats scattered across this 10 by 10 grid.");
System.out.println(" When you get a \'Hit!\', mark it on your accompanying paper.");
System.out.println(" Once you have completely shot down all seven boats (18 Hits), you win!");
System.out.println(" But play carefully! You only have 50 missiles.");
System.out.println();
boolean[][] field = new boolean [10][10];
//Ship one
field[8][2] = true;
field[8][3] = true;
field[8][4] = true;
field[8][5] = true;
field[8][6] = true;
//Ship two
field[1][9] = true;
field[2][9] = true;
//Ship three
field[2][4] = true;
//Ship four
field[2][2] = true;
field[3][2] = true;
field[4][2] = true;
//Ship five
field[4][8] = true;
field[5][8] = true;
field[6][8] = true;
field[7][8] = true;
//Ship six
field[6][3] = true;
field[6][4] = true;
//Ship seven
field[6][6] = true;
for (int missileattempts=0; missileattempts<=50; missileattempts++){
System.out.println("What is the X-Coordinate of your guess?");
Scanner scan = new Scanner(System.in);
int AnswerX = scan.nextInt();
System.out.println("What is the Y-Coordinate of your guess?");
Scanner scan2 = new Scanner(System.in);
int AnswerY = scan.nextInt();
if (field[AnswerX][AnswerY]=true){
System.out.println("Hit! Way to go!");}
else {System.out.println("Miss! Try again!");}
}
}}
a = b // assignment
a == b // comparison
You need to use the correct operator in your if condition.
Assignment results in the value from the right-hand side of the operator. Because you are assigning the value true to field[x][y], your condition will always evaluate to true.
In the if condition, you are assigning the value true to the variable, and then that gets checked. (It's always true at that point because that's what you assigned.
Two things here: First, the Boolean test operator is == rather than =. Second, if the variable is Boolean anyway, then you should just check it rather than doing an equality check at all, like this: if (field[AnswerX][AnswerY]) {. Doing equality checks on Booleans is bad style - in part because it lends itself to exactly the error that you have here.
I'm creating an application which updates users on the score of a football match either in real time or as a final result. At least one score must be inputted in order for the TextView to be updated and the relevant score to be displayed. I'm checking that at least 1 of a pair of EditText fields is not empty using the following code:
if(!(et_current.getText().toString().isEmpty())||(!(et_final.getText().toString().isEmpty()))
&& (!(et_current2.getText().toString().isEmpty())||(!(et_final2.getText().toString().isEmpty()))){
if(!(et_final.getText().toString().isEmpty()))
tv_final.setText(et_final.getText().toString());
else
tv_current.setText(et_current.getText().toString());
if(!(et_final2.getText().toString().isEmpty()))
tv_final2.setText(et_final2.getText().toString());
else
tv_current2.setText(et_current2.getText().toString());
}
I want to be able to set the correct TextView so I have another if statement inside the original if statement to see ensure the correct score is being updated.
When I run the code, I do not seem to be getting past the first if statement. Am I using the correct format or is there an better way to complete these checks?
Thanks!
For readabilities sake, get some variables going
boolean currentEmpty = et_current.getText().toString().isEmpty();
boolean current2Empty = et_current2.getText().toString().isEmpty();
boolean finalEmpty = et_final.getText().toString().isEmpty();
boolean final2Empty = et_final2.getText().toString().isEmpty();
And then your code can be much cleaner. Something like
if( (!currentEmpty || !finalEmpty) || (!current2Empty || !final2Empty)) {
if(finalEmpty) {
tv_current.setText(et_current.getText());
}
else {
tv_final.setText(et_final.getText());
}
if(final2Empty) {
tv_current2.setText(et_current2.getText());
}
else {
tv_final2.setText(et_final2.getText());
}
}
I'm not sure if that is completely correct as the requirement is not entirely clear to me, but it should atleast be a good start to follow what's going on.
I currently have java homework that I would appreciate some help with. We are to calculate a team record scenario.
We are given the following numbers:
Team1 Points
{23,45,65,20}
Opponent Points
{20,30,20,18}
I threw these into an array. I also created a public boolean. Basically, you are to pull these points from the array to the boolean? And let the boolean decide which team won? Obviously team1 has won, but we are supposed to let the computer decide, not the human.
Here is my code:
public class TeamScore {
public static boolean Winner(int team1Points, int opponentPoints) {
if (team1Points > opponentPoints) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
// Scanner in = new Scanner(System.in);
int[] team1Points = { 23, 45, 65, 20 };
int[] opponentPoints = { 20, 30, 20, 18 };
int team1 = 1;
int opponent = 1;
for (int i = 0; i < 5; i++) {
if (Winner(team1Points[i], opponentPoints[1])) {
team1 += 1;
} else {
opponent += 1;
}
}
for (int i = 0; i < 5; i++) {
if (team1 > 0 && opponent == 0) {
System.out.println("Team 1 has the perfect record!");
} else {
System.out.println("Win" + Arrays.toString(team1Points));
System.out.println("Loss" + Arrays.toString(opponentPoints));
}
}
}
Could anyone possibly help me? I am currently in programming II, but I did not have the best teacher in programming I. Any help would be appreciated!
EDIT:
I do not think this is a duplicate question because I already can fix it by changing the variable i-->1. My problem is that the computer thinks that team1 has already won regardless of the score.
When I run the code I am getting an java.lang.ArrayIndexOutOfBoundsException error. However when I change team1Points[i] to team1Points[1] then it goes okay and tells me that "Team 1 has the perfect record!". However, if I change some of the array values for team1Points to be less than opponentPoints then it still says "Team 1 has the perfect record!".
Not sure why you have a method Winner (also as Kevin said, it should be winner because of naming conventions) which turns ´(a > b)´ into a large if-statement. Similar stuff appear elsewhere in your code.
Your variables ´team1, opponent = 1´ inexplicably start with the value 1, am I to understand this as a way for your code to imply to a reader that both teams initialize at a win? Using 0 would probably make more sense.
Your game ought to crash from an indexoutofboundsexception at ´team1Points[i]´, as you have arrays of length 4, but your loops runs 5 times (the currently used range is [0-4], inclusive). Changing your loops to i=1 won't help, as the issue is that you eventually encounter team1Points[4] due to the i < 5 statement.
I don't know what game you are modelling or how it works, but the comparison ´Winner(team1Points[i],opponentPoints[1])´ looks like a blatant error to me (you always look at the opponents score for their second round).
Why are you printing your results 5 times? If you want to print the first message only when team1 won all rounds and the point for each round otherwise, you would need to use the loops counter as an index to the arrays in second case. First case should break loop so its not written five times, in addition you don't need to check team1>0 && opponent==0 as it's enough to only check if ´opponent==0´ (speaking of this conditional, it only works if you initialize the variables at 0 as I mentioned before). You could have checked if team1 equals size of the array instead, but imo thats more of a hassle than opponent==0.
Lastly, please fix your indenting. use the preview system so you can make double sure before posting.
Edit: Kevin also brings up a good point that you should be using the length of the array in your loops second statement.
I'm trying to make a very basic game where you guess a number between 1-1000 using a do loop. Everything works, except when I finally make the correct guess, I am still prompted to make another guess, and when I enter the same correct guess again, the program terminates like it's suppose to.
Why do I have to make that extra guess to finally get my program to work? Am I looping around an extra time? Also, if I make a correct guess (the compiler will say I am correct then still prompt me), then a wrong guess (the compiler will tell me I'm wrong), then the correct guess again, the program will only terminate after I make the correct guess a second time.
The second do loop at the bottom is what I put in my main method. Everything above is in a method I wrote called play.
public static boolean play()
{
boolean c;
int n = 0;
do {
String input = JOptionPane.showInputDialog("Enter a number between 1-1000");
n = Integer.parseInt(input);
if (n == guess)
{
System.out.println("Correct");
c = true;
}
else if (n < guess)
{
System.out.println("Not Right");
c = false;
}
else
{
System.out.println("Not Right");
c = false;
}
guess++;
} while (c == false);
return c;
}
In main method:
do {
game1.play();
} while (game1.play() != true);
This loop runs the play method twice in each iteration of the loop :
do {
game1.play(); // first call
} while (game1.play()!=true); // second call
You are not testing the value returned by the first call, so even if it returns true, you would still call game1.play() again, which will display "Enter a number between 1-1000" again.
Replace it with:
boolean done = false;
do {
done = game1.play();
} while (!done);
This would only call play() one time in each iteration of the loop.
That said, I'm not sure why you need the outer loop.
You can just replace in with one call to game1.play(), since game1.play() will loop until the correct number is entered.
An assignment we were given recently had us building a basic, console-based, 'Tax Calculator', as it is something that got us to implement the things we'd learnt so far - variables, constants, loops etc.
One part of it had us present the user with a menu, where they would enter a letter - be it a,b,c,d or x - depending on what they wanted to do next.
That was no drama, as our assignment didn't ask for us to account for what happened if a user entered a choice not on the menu.
Now, for my own personal interest, I went back to it today, wanting to put some validation in there.
I defined the 'menuChoiceRule':
(menuChoice being a String)
boolean menuChoiceRule = (menuChoice.equalsIgnoreCase("A"))
|| (menuChoice.equalsIgnoreCase("B"))
|| (menuChoice.equalsIgnoreCase("C"))
|| (menuChoice.equalsIgnoreCase("D"))
|| (menuChoice.equalsIgnoreCase("X"));
And here is what should happen for as long as the rule is being broken: (The program should keep asking until it gets something that is in keeping with the rule, and then stop asking)
while (menuChoiceRule == false) {
System.out.print(menuChoiceString);
System.out.print("Enter Your Selection");
menuChoice = SCANNER.nextLine();
}
And what happens if the user is doing the right thing:
// As long as the user input is 'A','B','C' or 'D', they'll be able to
// keep doing stuff.
while (menuChoiceRule == true) {
*All the various menu options go here*
}
At the moment the while(menuChoiceRule == true) block (is that the right term?) works fine but while(menuChoiceRule == false) does not; Once the user inputs something that is in violation of the menuChoiceRule, the loop repeats endlessly no matter what is input (inputted?)
If someone could provide some insight as to why I'm having trouble here, it'd be much appreciated.
Regards,
AUS_Doug.
Looks like the boolean test is not being changed within the loop, place the code again at the bottom of the while loop.
Also, boolean tests do not need the ==, while(menuChoiceRule){ ... is the preferred coding style.
I would also consider creating a method to test for your rule:
private boolean testChoice(String menuChoice) {
return ((menuChoice.equalsIgnoreCase("A"))
|| (menuChoice.equalsIgnoreCase("B"))
|| (menuChoice.equalsIgnoreCase("C"))
|| (menuChoice.equalsIgnoreCase("D"))
|| (menuChoice.equalsIgnoreCase("X")));
}
This would give rise to the code:
boolean validChoice = false;
while (!validChoice) {
System.out.print(menuChoiceString);
System.out.print("Enter Your Selection");
menuChoice = SCANNER.nextLine();
validChoice = testChoice(menuChoice);
}