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 4 years ago.
Improve this question
I am new to coding. Please be gentle with me.
I have been charged with creating a program that compares the scores of two competing volleyball. To win a match in volleyball, a team must get 25 points. But the team must also win by 2. These two teams are going to play five matches.
The program should accept from the user the scores for each team one match at a time. If at any time that user enters scores that violate the 25-point rule or the “win by 2” point rule, print an error on the screen and make the user enter both scores again.
When the user is finished entering the scores, print which team won the game, that is the team that won the most matches.
You have to use arrays and loops in this assignment.
My program is only scoring the first set of scores in the array.
How do I make it store all five sets of scores?
public static void main(String[] args) {
int team1[];
int team2[];
team1=new int[5];
team2=new int[5];
int counter1=0;
int counter2=0;
int k = 0;
for (int i=0;i<=4;i++){
Scanner scanint = new Scanner(System.in);
System.out.println("Enter the number of points Team 1 earned in Match " + (i+1));
team1[i] = scanint.nextInt();
System.out.println("Enter the number of points Team 2 earned in Match " + (i+1));
team2[i] = scanint.nextInt();
////////////////////////////////////////////
if (team1[i] < 25 & team2[i] < 25){
System.out.println("That cannot be. One team must get at least 25 points. Please re-enter the data.");
System.out.println("Enter the number of points Team 1 earned in Match " + (i+1));
team1[i] = scanint.nextInt();
System.out.println("Enter the number of points Team 2 earned in Match " + (i+1));
team2[i] = scanint.nextInt();
}
else if (team1[i] - team2[i] < 2 || team2[i] - team1[i] < 2){
System.out.println("That can't be. One team must win by at least two points. Please re-enter the data.");
System.out.println("Enter the number of points Team 1 earned in Match " + (i+1));
team1[i] = scanint.nextInt();
System.out.println("Enter the number of points Team 2 earned in Match " + (i+1));
team2[i] = scanint.nextInt();
}
else {
System.out.println("Enter the number of points Team 1 earned in Match " + (i+1));
team1[i] = scanint.nextInt();
System.out.println("Enter the number of points Team 2 earned in Match " + (i+1));
team2[i] = scanint.nextInt();
}
/////////////////////////////////////////////
if (team2[i] < team1[i]){
counter1++;}
else{ counter2++;}
}
if (counter1 > counter2) {
System.out.println("Team 1 has won the game.");}
else{
System.out.println("Team 2 has won the game.");
}
Well, there are only a few rules for finished games that I see:
Neither team can have negative points.
At least one team has to have 25 or more points.
The points for a team can't be above 25 unless it's exactly two points above or below the other team.
So, how do we do this? With some if statements for each rule. For the first rule:
if ((team1 < 0) || (team2 < 0)) {
System.err.println("A score cannot be negative!");
i--;
continue;
}
For the second rule:
if ((team1 < 25) && (team2 < 25)) {
System.err.println("At least one team has to have 25 or more points!");
i--;
continue;
}
For the third rule (this can be converted into one if statement with an &&, but I've made it a bit simpler to understand):
if ((team1 > 25) || (team2 > 25)) {
if ((team1 - team2 != 2) && (team2 - team1 != 2)) {
System.err.println("If a team has more than 25 points, the other team must be two points away from it!");
i--;
continue;
}
}
Note that the continue; means to go to the next iteration of the loop you're in. So, you go to the previous iteration with i--; and you go to the next iteration with continue;. This is a trick to allow you to restart the current iteration of the loop you're in.
Also, I wouldn't use arrays unless I used the scores somewhere outside the initial data input loop (though you should follow the rules for the assignment and use them anyway). I'd immediately point out when a game's scores were invalid and I'd keep track of the wins for both teams in some variables, like int team1Wins = 0; and int team2Wins = 0;.
Related
I am writing a program in which the random method generates a random number between 1 and 100, and then the user guesses what the number is.
Everything in the code I built works fine so far, except the part where the program also calculates the number of user guess attempts.
I know the general idea of how to get the user attempt count: create a count-tracking variable and then increment it with each user entry. Now matter how or where I apply the count-tracking variables, the number of user attempts is always 2, even though there are far more actual attempts. I Googled this issue, and tried different ideas from results (ex: put count++ into every "if/else" statement), but nothing works.
Can anyone tell what is wrong with my code, and why it is always showing 2 as number of user attempts? Thank you in advance for any help.
System.out.println("Enter a number between 0 and 100: ");
int randomDigit = (0 + (int) (Math.random() * 101));
while (true) {
Scanner scr = new Scanner(System.in);
int guess = scr.nextInt();
int guessCount = 0;
guessCount++;
guessCount = guessCount + 1;
if ((guess < 0) || (guess > 100)) {
System.out.println("You entered an invalid number. \nPlease enter a valid number.");
} else if (guess > randomDigit) {
System.out.println("Your guess is too high. \nPlease enter another guess.");
} else if (guess < randomDigit) {
System.out.println("Your guess is too low. \nPlease enter another guess.");
} else if (guess == randomDigit) {
System.out.println("Congradulations, you found the number! It is " + randomDigit
+ ".\nThe number of attempts it took you to guess the correct answer is: " + guessCount + ".");
break;
}
}
The above code always has 2 as number of user attempts.
Move this line:
int guessCount = 0;
Outside the loop, as you are constantly repeating the initialization of the variable, and thus, not actually counting it.
When you use a counter, always define it outside your while/for loops.
Good luck
I'm making a game called 'Game of Nim' in Netbeans. Basically, a random amount of stones between 15-30 is generated and a computer and a player take turns taking 1-3 stones until there are none left. The player to take the last stones loses. I'm coding this in a jframe form. I want to make sure the player doesn't enter a number bigger than 3, less than 1 and bigger than the total stones, so I made a while loop with an if statement for the input that meets the requirements and an else statement if they aren't met. My problem is that when a player does enter numbers that shouldn't be entered, no error message appears and the game continues as normal.
Here is where I think the problem is:
public int playerInput(){
// Getting the user input and converting it into an integer
int userIn = Integer.parseInt(txtIn.getText());
//
boolean input = false;
// Do this while the input isn't between 1-3 and higher than the total amount of rocks
while(!input){
//
if (userIn < 3 || userIn > 1 || userIn < totalStone){
//
input = true;
}
//
else{
// Output an error message
txtaOut.setText(txtaOut.getText() +"\nEnter a number between 1 - 3 and less than the amount of stones left.");
}
}
// return the amount of rocks the user takes
return userIn;
}
Here is most of the code for the game (I am going to use the random slashes for commenting):
public void computerMove() {
// Generating a number for the computer's move
int comIn = (int)(Math.random() * 2) + 1;
// If number generated is bigger than the total stones,
if (comIn > totalStone){
// Get the difference between the total and the random number
int totalComDiff = Math.abs(totalStone - comIn);
// Subtract the difference from the random number
comIn -= totalComDiff;
// Substract the rocks taken from the total
totalStone -= comIn;
// Display a message of the rocks taken and the rocks left
txtaOut.setText(txtaOut.getText() +"\nThe computer picked up " +comIn +" stone(s). There are " +totalStone +" stones left.");
}
// Otherwise, if the random number is smaller than the total,
else if (comIn < totalStone){
// Substract the rocks taken from the total
totalStone -= comIn;
// Display a message of the rocks taken and the rocks left
txtaOut.setText(txtaOut.getText() +"\nThe computer picked up " +comIn +" stone(s). There are " +totalStone +" stones left.");
}
// If the total equals amount the computer takes,
else if (totalStone == comIn){
// Substract the rocks taken from the total
totalStone -= comIn;
// Display a message of the rocks taken and the rocks left
txtaOut.setText(txtaOut.getText() +"\nThe computer picked up " +comIn +" stone(s). There are " +totalStone +" stones left.");
// Display a message that says the player wins
txtaOut.setText(txtaOut.getText() +"\nThere are no more stones left. The player wins!");
}
// Otherwise, if the amount of stones is 0,
else if (totalStone == 0){
// Display an end game message
txtaOut.setText(txtaOut.getText() + "\nThe game has ended.");
}
}
public void playerMove(){
// If there are no more stones left,
if (playerInput() == totalStone){
// Subtracting how much the player took from the total amount of rocks
totalStone -= playerInput();
// Displaying how many rocks were taken and how many are left
txtaOut.setText(txtaOut.getText() +"\nYou picked up " +playerInput() +" stone(s). There are " +totalStone +" stones left.");
// Display a message that says the computer wins
txtaOut.setText(txtaOut.getText() + "\nThere are no more stones left. The computer wins.");
}
//
else if (playerInput() != totalStone){
// Subtracting how much the player took from the total amount of rocks
totalStone -= playerInput();
// Displaying how many rocks were taken and how many are left
txtaOut.setText(txtaOut.getText() +"\nYou picked up " +playerInput() +" stone(s). There are " +totalStone +" stones left.");
}
//
else if (totalStone <= 0){
//
txtaOut.setText(txtaOut.getText() + "\nThe game has ended.");
}
}
private void btnEnterActionPerformed(java.awt.event.ActionEvent evt) {
//
if (totalStone > 0){
// Display how many rocks there are
txtaOut.setText(txtaOut.getText() +"\nThere are " +totalStone +" stones.");
// The player does their move
playerMove();
}
//
if (totalStone > 0){
// Computer does a turn
computerMove();
}
//
else if (totalStone == 0){
//
txtaOut.setText(txtaOut.getText() + "\nThe game has ended.");
}
}
private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {
// Generating another random number
totalStone = (int)(Math.random() * 15) + 15;
// Clearing all the textfields
txtIn.setText("");
txtaOut.setText("");
// Outputting the number of starting stones
txtaOut.setText(txtaOut.getText() +"There are " +totalStone +" stones. It's your turn.");
}
your if needs to look like this:
while (!input) {
if (!(userIn < 3 && userIn > 1 && userIn < totalStone)) {
// Output an error message
txtaOut.setText(txtaOut.getText() +"\nEnter a number between 1 - 3 and less than the amount of stones left.");
// Prompt the user again
userIn = Integer.parseInt(txtIn.getText());
} else {
input = true;
}
}
And, it will work.
It is better to check if conditions are not valid first, and then if the verification is passed do the normal flow in else block.
The way you wrote it, the if condition would always be true since || represents 'or' so you're asking weather userIn is less then 3 or greater then 1 or lesser than totalStone which is always true.
On the other hand && represents 'and' and '!' represents not. So, you basically want all the conditions to be fulfilled and checking if they aren't by putting them into the brackets and putting ! (negation) in front
You also need to prompt the user again if the condition is not met. Otherwise it's gonna run forever and freeze the ui.
If the user enters an incorrect number, they should then be prompted to enter a new one. In your code, it will be stuck in the loop forever.
You should also be checking that all conditions are satisfied using &&.
You need a number that is (<=3) AND (>=1) AND (<=totalStones)
public int playerInput () {
int userIn;
do {
System.out.println("Enter a number between 1 - 3 and less than the amount of stones left.")
userIn = Integer.parseInt (txtIn.getText ());
} while (!(userIn <= 3 && userIn >= 1 && userIn <= totalStone));
This will continue to loop while the conditions are not satisfied.
Okay, so the problem isn't necessarily the actual code because it works, but rather the logic. The problem is how many guesses will it take the computer to get the number your thinking? Between 1-100 it will always guess your number in 7 tries no matter what it is as long as it's between 1-100. The next question is what about 1-50, I figured out that it will only take 5 tries to always guess your number.
import java.util.Scanner;
public class ThinkofaNumber {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Guess a number between 1 and 100");
System.out.println();
int input = 0;
//guess is equal to half the highest number
int guess = 50;
//low is equal to the lowest
int low = 1;
//high is equal to the highest number
int high = 101;
int tries = 1;
while (input != 2) {
System.out.println("Is your number " + guess + "?");
System.out.println("1: No, my number is lower");
System.out.println("2: Yes, that is my number");
System.out.println("3: No, my number is higher");
System.out.println();
input = in.nextInt();
if (input == 1) {
high = guess;
guess = low + (guess - low) / 2;
tries++;
} else if(input == 3) {
low = guess;
guess = guess + (high - guess) / 2;
tries++;
}
}
System.out.println("Your number is " + guess + "!");
if (tries == 1) {
System.out.println("It took 1 try to guess " + guess);
} else {
System.out.println("It took " + tries + " guesses to get " + guess);
}
}
}
The problem is the question then goes on to ask how many do you think the maximum number of guesses would be if the number was between 1 and 400? What if it were between 1 and 800? Between 1 and 1600? I think it's trying to get me to find a pattern or a algorithm but I don't see it. What do you guys think?
The algorithm you are talking about is a binary search algorithm. https://en.wikipedia.org/wiki/Binary_search_algorithm
It is a binary search algorithm as Wojciech said. The number 7 comes from the following log2 (100) = 6.6 round up to 7.
So you can do log base 2 to find the number of guesses
Just to provide a little more breakdown from #Wael's answer.
More discussion on the binary search algorithm can be found here and in this answer we know that 2N+1-1 gives us the range (1..X) for any number of guesses N.
So we can further break this down by saying:
2N+1-1 = 800
2N+1 = 801
log2801 = N+1
log2801 -1 = N
i.e. 8.646 = N, N = 9
So it will take a maximum of 9 guesses to guess a number between 1 and 800.
I should also point out that 2N+1-1 is the worst case, and so when trying to find the number of guesses for a given input, it will vary depending on the input.
I'm new to this so sorry if I am a bit confusing
So this is my code, its a game based around 2 players adding 1 or 2 to the variable "counter" the one who puts the final 1 or 2 adding all the numbers up to 21 wins.
So what I would like to have help with is that I want to lock the user input to only be able to select 1 or 2, not anything else because that would break the rules of the game. Also I would like to have a way to determine who won, player 1 or player 2. Like counting the amount of times the loop happens, so I can distinguish if player 1 or 2 one.
Any help would be appreciated! Thanks!
package hemtenta;
import java.util.Scanner;
public class Hemtenta {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter = 0;
int addcounter = 0;
int sum;
System.out.println("Welcome to 21");
System.out.println("The game revolves about you or your opponent getting to 21 ");
System.out.println("You both start on the same number 0, ");
System.out.println("adding 1 or 2 to see which one of you will put the final number adding it all up to 21 and winning.");
System.out.println("Think smart!");
while(counter <= 20) {
System.out.println("Please choose to add 1 or 2");
addcounter = input.nextInt();
counter += addcounter;
System.out.println("We are now on a total of " + (counter));
}
if (counter==21) {
System.out.println("Congratulations x! you won");
}
else {
System.out.println("Something went wrong! Try again");
}
}
}
You could look towards adding a
while (addcounter != 1 && addcounter != 2) {
// Prompt for values
}
To check that the value input by the user is either a 1 or a 2. If it isn't, then don't accept it and continue prompting till a valid input is registered.
And a
int turnCounter = 0;
...
// Within the loop
turnCounter += 1;
...
// At the end
if (turnCounter % 2 == 0) {
//Player Y wins
} else {
//Player X wins
}
To identify the turns, since turn 1s will be by player X, and turn 2s will be player Y. All turns by player Y will be in multiples of 2.
I am a Java newbie and have been working on this program for about a month. My program is a graduation planner that shows the student how much time and money it would take to finish a college degree. I would like my program to be able to recognize that the minimum # of CUs could be < than 12 if the student only has 6 or so CUs left until graduation, but I also need it to recognize if I enter a letter or negative number which I somehow managed to pull off at the top of the code. I tried to use sum == sum which isn't giving me the desired output. I think I need to put the while (loop) somewhere in there.
package gradplanner13;
import java.util.ArrayList;
import java.util.Scanner;
public class GradPlanner13 {
public static void main(String[] args) {
int sum = 0;
Scanner input = new Scanner(System.in);
ArrayList<Integer> array = new ArrayList<>();
boolean loop = true;
System.out.println("Enter the individual CUs for your remaining courses. Enter 0 when done entering your individual CUs.");
while (loop) {
System.out.print("Enter CUs for individual course then press enter: ");
if (!input.hasNextInt()) {
input.nextLine();
System.out.println("Only positive numbers are valid inputs. Please try again. ");
continue;
}
if (!input.hasNextInt()) {
input.nextLine();
System.out.println("Only postive numbers are valid inputs. Please try again.");
continue;
}
int check = input.nextInt();
input.nextLine();
if (check == 0) {
loop = false;
continue;
} else if (check < 0) {
System.out.println("CU values must be positive. Try again.");
continue;
}
array.add(check);
}
for (Integer CUs : array) {
sum += CUs;
}
System.out.println("Total number of CUs for all courses: " + sum);
double rounded = 0;
do {
System.out.print("How many CUs you are planning to take each term: ");
rounded = input.nextInt();
if (sum == sum) {
break;
}
if (rounded < 12 || rounded > sum) {
System.out.println("Take each term with a minimum of 12 CUs or the CUs you have left to complete your program if less than 12 : ");
}
} while (rounded < 12 || rounded > sum);
double numTermsToCompletion = Math.ceil(sum / rounded);
System.out.println("Number of terms to completion: " + numTermsToCompletion);
System.out.println("Tuition cost based on number of terms to completion: $" + (numTermsToCompletion * 2890));
System.out.println("Number of months to completion: " + (numTermsToCompletion * 6));
}
}
The below code is the section that I think I am having trouble with because I need it to recognize that sometime a student may not have the minimum (12) CUs left and I would like it to check to make sure the minimum is met or recognize that less than the minimum is left and still process the input. I tried to reuse while (loop) cause I know that part of the program responds correctly when I try to enter a letter or negative number at the beginning of the code, but I obviously was not implementing the loop correctly when I tried to put it on the below code, the program runs but doesn't produce anything when it gets to that point in the code. It just runs and doesn't produce any errors. In summary, I would appreciate some assistance getting my code to realize that a student may not have the minimum CUs left (12) and may need < than that to graduate, but also not accept negative numbers or letters as input.
do {
System.out.print("How many CUs you are planning to take each term: ");
rounded = input.nextInt();
if (sum == sum) {
break;
}
if (rounded < 12 || rounded > sum) {
System.out.println("Take each term with a minimum of 12 CUs or the CUs you have left to complete your program if less than 12 : ");
}
} while (rounded < 12 || rounded > sum);
So I moved sum == sum and I am a little closer to where I need to be. I still need to do some research because I am how getting the statement that tells me that I need to have a minimum of 12, but it still gives me the correct output.
do {
System.out.print("How many CUs you are planning to take each term: ");
rounded = input.nextInt();
if (rounded < 12 || rounded > sum) {
System.out.println("Take each term with a minimum of 12 CUs or the CUs you have left to complete your program if less than 12 : ");
}
if (sum == sum) {
break;
}
} while (rounded < 12 || rounded > sum);
This is the output:
Total number of CUs for all courses: 8
How many CUs you are planning to take each term: 8
Take each term with a minimum of 12 CUs or the CUs you have left to complete your program if less than 12 :
Number of terms to completion: 1.0
Tuition cost based on number of terms to completion: $2890.0
Number of months to completion: 6.0
BUILD SUCCESSFUL (total time: 12 seconds)
Ok. From the recommendations I have received, I rethought the process and rewrote some of the code and it works a lot better. The problem now is if the user enters 0 from the beginning, this is the output:
Enter the individual CUs for each individual remaining course. Enter 0 when done entering your individual CUs for each course.
Enter CUs for individual course then press enter: 0
Total number of CUs for all courses: 0
Number of terms to completion: 1
Tuition cost based on number of terms to completion: $2890
Number of months to completion: 6
BUILD SUCCESSFUL (total time: 2 seconds)
If you have 0 CUs left, you shouldn't have any terms left. It looks like I need to either change where my loop is false, or do something similar like I did here:
if (sum >= 12) {
do {
System.out.print("How many CUs you are planning to take each term? Minimum of 12 CUs required per term: ");
numOfCUs = input.nextInt();
} while (numOfCUs < 12);
numTermsToGraduation = (int) Math.ceil(sum / (double) numOfCUs);
Below is the complete new code:
System.out.println("Enter the individual CUs for each individual remaining course. Enter 0 when done entering your individual CUs for each course.");
package gradplanner13;
import java.util.ArrayList;
import java.util.Scanner;
public class GradPlanner13 {
public static void main(String[] args) {
int sum = 0;
Scanner input = new Scanner(System.in);
ArrayList<Integer> array = new ArrayList<>();
boolean loop = true;
// Student enters the individual credits for each course remaining in their degree program
System.out.println("Enter the individual CUs for each individual remaining course. Enter 0 when done entering your individual CUs for each course.");
// loop checks to make sure inputs are positive numbers
while (loop) {
System.out.print("Enter CUs for individual course then press enter: ");
if (!input.hasNextInt()) {
input.nextLine();
System.out.println("Only positive numbers are valid inputs. Please try again. ");
continue;
}
if (!input.hasNextInt()) {
input.nextLine();
System.out.println("Only postive numbers are valid inputs. Please try again.");
continue;
}
int check = input.nextInt();
input.nextLine();
if (check == 0) {
loop = false;
continue;
} else if (check < 0) {
System.out.println("CU values must be positive. Try again.");
continue;
}
// Calculates inputs from user
array.add(check);
}
for (Integer CUs : array) {
sum += CUs;
}
System.out.println("Total number of CUs for all courses: " + sum);
int numOfCUs = 0;
int numTermsToGraduation = 0;
if (sum >= 12) {
do {
System.out.print("How many CUs you are planning to take each term? Minimum of 12 CUs required per term: ");
numOfCUs = input.nextInt();
} while (numOfCUs < 12);
numTermsToGraduation = (int) Math.ceil(sum / (double) numOfCUs);
} else {
numOfCUs = sum;
numTermsToGraduation = 1;
}
System.out.println("Number of terms to completion: " + numTermsToGraduation);
System.out.println("Tuition cost based on number of terms to completion: $" + (numTermsToGraduation * 2890));
System.out.println("Number of months to completion: " + (numTermsToGraduation * 6));
}
}
From what I could tell, you are trying to use "sum == sum" to tell you if the input value is an negative number or a letter. This is not correct, as sum==sum will always return true.
For checking if it is a number is positive, you should just use sum > 0.
As for checking if its actually a letter, and not a number, this is handled by your scanners when you check if the input is a number (hasNextInt).
It looks like you are using if (sum == sum) {...} to error check the value of sum. That is not what you want to do, because it is always going to equate to true. What you want to do is use a try {...} catch (InputMismatchException e) {...}. In your case, it would be set up as follows:
...
System.out.println("Enter the individual CUs for your remaining courses. Enter 0 when done entering your individual CUs.");
int exception = 1;
while (exception = 1) {
try {
int someNum = input.nextInt();
...
}
catch (InputMismatchException e) {
exception = 1;
System.out.println("Please enter the correct data type!");
}
}
...
At the first moment the InputMismatchException is thrown, the program will execute the code in the catch block.