I am making a lottery program where I am asking if basically they would like a quick pick ticket. The numbers for their ticket of course would be random since it is a quick pick but the first four numbers range from 0-9 while the fifth number only goes up to 0-4. I am trying to ask them to input a button such as either "1" for no or "2" for yes if they don't want one then it would skip this step. But I am doing the boolean part incorrectly though. Could someone help me out?
Here is an example
System.out.println("Do you want Quick pick, 1 for no or 2 for yes? The first four numbers is from a separate set of 0 to 9 and the fifth number is from a set of 0 to 4.");
QuickPick=keyboard.nextInt();
if((QuickPick==1)){
return false;
}
if((QuickPick==2)){
return true;
int n = (int)(Math.random()*9+0);
System.out.println("Your QuickPick numbers are: " + kickerNumbers + kickerPowerball);
}
I still haven't gotten around to making the line of code for the final number of 0-4, just the first four numbers, so I haven't forgotten that.
Your code for case 2 immediately does a return true; which ends the method (I assume this is in a method) right then and there. Your other lines don't get execute at all.
Consider using a switch() statement here, it'll make it easier to read:
switch(QuickPick)
{
case 1:
return false;
case 2:
int n = (int)(Math.random()*9+0); // Why is n here? You don't do anything with it?
System.out.println("Your QuickPick numbers are: " + kickerNumbers + kickerPowerball);
return true;
default:
// Uh oh - someone did something bad maybe just return false?
return false;
}
Also your code for case 2 is definitely wrong, you need to generate a total of five numbers, using bounds 0-9 for the first 4 and 0-4 for the last one. You'll want to use Java's Random to do this (not Math.Random) something like:
Random rand = new Random();
int somethingRandom = rand.nextInt(10);
// Will give you an integer value where 0 < val < 10
// You can call rand.nextInt as many times as you want
To avoid doing your homework for you -- I'll follow the typical CS textbook line and say "Implementation left as an exercise."
The code after return true will not be executed - you need to put that prior to the return statement
Like Marvo said, you dropped a brace in your if.
But you also have faulty logic. I'm not quite sure what the purpose of the method you're in is (that returns a boolean value). But your last few lines will never be reached unless the user types in something like 3 or 42.
Assuming the method is supposed to a) Ask if the user wants a Quick Pick b) Calculate the Quick Pick, if desired c) Return true/false depending on whether the Quick Pick happened or not, you should have:
public boolean doQuickPick()
{
System.out.println("Do you want Quick pick, 1 for no or 2 for yes? The first four numbers is from a separate set of 0 to 9 and the fifth number is from a set of 0 to 4.");
QuickPick=keyboard.nextInt();
if((QuickPick==1)){
return false;
}
if((QuickPick==2)){
int n = (int)(Math.random()*9+0);
System.out.println("Your QuickPick numbers are: " + kickerNumbers + kickerPowerball);
return true;
}
}
As a separate issue, it'd be much better style to break that into several methods. boolean yesNoPrompt(String message), generateQuickPick(), etc.
Your question is kind of unclear, so I'm afraid I can't be much more help than that. Do post any clarifications / further questions if you have them.
if((QuickPick==2)){
return true;
int n = (int)(Math.random()*9+0);
System.out.println("Your QuickPick numbers are: " + kickerNumbers + kickerPowerball);
}
In the above copied code from your question, I see that you will be getting compilation errors in your IDE. Your IDE will complain about "Unreachable Code" for the line that is just below the return statement. So, you need to put the return statement at the end of the if block.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
I'm beginner in Java, so hope you'll understand it. I tried a few different ways, but it always has a problem with the logic: it cannot save a variable and check it in while loop or cannot go right through the if else statements. There is supposed to be some trick and I cannot find it.
For example:
If input is 1, 47, 89, 98, 165,256,300 0, it stops and prints "End of the program, numbers been entered in regular order".
If input is 86,75,32,11,0, it stops and prints "End of the program, numbers been entered in reversed order".
If input is 43, 54,11,6,7,45,44,44,44,56,330, it stops and prints "End of the program, numbers been entered in mixed or same order"
Here is the updated version of the code(2):
boolean mixed;
boolean up =true;
boolean down =true;
int numToAdd;
System.out.println("Enter a Number:");
int previousNum = input.nextInt();
do {
System.out.println("Enter a Number:");
numToAdd = input.nextInt();
if (numToAdd == 0) break;
if (numToAdd > previousNum ) {
up = true;
}
if (numToAdd < previousNum) {
down = true;
}
mixed = !up && !down;
previousNum = numToAdd;
} while (numToAdd != 0);
if (up = true ) {
System.out.println("End of the program, numbers been entered in regular order");
}
if (down = true) {
System.out.println("End of the program, numbers been entered in reversed order");
}
if (mixed = true) {
System.out.println("End of the program, numbers been entered in mixed or same order");
}
We don't want to give the O/P a complete answer. If we did that, the O/P could hand in code he / she didn't write and doesn't understand. Instead, we want to guide the O/P toward a solution. We feel the O/P will learn more that way.
I'm looking at the 2nd version of the O/P code.
There are at least 3 problems with the 2nd attempt.
(1) It appears the code intends zero to be a sentinel value. When the user enters zero, the program is supposed to exit the loop and print the results. The problem is, the code processes the sentinel value before the terminating condition in the do { } while () loop is reached. This could make a strictly ascending sequence appear to be a mixed sequence.
There are several ways this can be fixed, but one has already been suggested in the comments:
do {
System.out.println("Enter a Number:");
numToAdd = input.nextInt();
if (numToAdd == 0) break;
(2) The variable loopFor is written as if it is a sum of the numbers entered. The sum of the numbers entered is irrelevant to what the program is supposed to be doing. From the rest of the code, it seems loopFor is intended to be the previous value entered.
To fix this, the loopFor += numToAdd; statement should be deleted. The statement loopFor = numToAdd should be added to the code, but in a different place. The proper place is after all comparison of loopFor with numToAdd has been completed.
Refactor suggestion: Rename loopFor to previousNum.
However, that change still leaves a problem. The variable loopFor needs an initial value. Because the programmer doesn't know if the user will enter an increasing sequence or a decreasing sequence, the initial value can be neither an artificially high value nor an artificially low value.
I'll leave it to the O/P to figure out how to solve that.
(3) The way the boolean values up, down, mixed are managed is not reliable. If, for example, up is set to true, it can later be set to false. Still later, it can be set to true again.
These should each be set to an initial value. Upon detection of an appropriate condition, the value is flipped, and is never set to the initial value again.
My suggestion is set up and down to true only at the beginning of the program. When a sequence of numbers is detected that shows one of them to be false, set that one to false.
Note that "mixed" can be detected at the end by something like this:
boolean mixed = !up && !down;
So, that variable isn't really needed.
Again, I'll leave it to the O/P how to make the change.
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.
Okay, this is part of the full code of a guessing game.
public static void Game(){ //Second page of game with option of continue playing when guessed close enough to answer.
Scanner scan = new Scanner(System.in);
GuessingGame testgame=new GuessingGame();
testgame.Generator();
int num = testgame.GetGenNum();
//Produces a random number between 1 and 100 inclusive of 1 and 100
System.out.println("Guess the target integer which is between 1 and 100 inclusive");
int guess=scan.nextInt();
int difference=(guess-num);
while(guess!=num){
int yesCounter=0;
System.out.println("Guess again " +num+" "+difference);
guess=scan.nextInt();
difference=(guess-num);
///something wrong here, shouldnt repeat if difference too big
if(difference<=5||difference>=-5){ //something wrong with the condition, it says its close enough even tho it isnt.
while(yesCounter<1){
System.out.println("Close enough, do you want to keep Guessing? Y/N ");
yesCounter++;
String play = scan.nextLine();
//play=play1;
while(!(play.equalsIgnoreCase("y")))
{
if(play.equalsIgnoreCase("n")){
System.exit(1);
}
else{
if((play.equalsIgnoreCase("y"))){
invalid();
guess=scan.nextInt();
}
else{
Game(); ///TAKE note as it might restart the game with new random integer
}
}
}
}
}
}
output is:
.........................
Play? Y/N
y
Guess the target integer which is between 1 and 100 inclusive
50
Guess again 44 6
44
Close enough, do you want to keep Guessing? Y/N
Guess the target integer which is between 1 and 100 inclusive
..........................
the problem is, when user guess a number, the condition is if the difference between the guess and the generated number is 5 or smaller, tell user that its close enough, and ask if user wants to continue guessing, but the condition wasn't fulfilled and yet still runs, can someone help?
while(!(play.equalsIgnoreCase("y")))
{
if(play.equalsIgnoreCase("n")){
System.exit(1);
}
else{
if((play.equalsIgnoreCase("y"))){
invalid();
guess=scan.nextInt();
....
That isn't right, if((play.equalsIgnoreCase("y"))) can never be true, since the loop it is in, explicitely cannot be entered if it is true. That's where your problem is, it will always restart the game because it calls Game() in the else-branch. In short, this is what you do:
boolean _true = true;
while(! _true) {
if(_true) {
//impossible
}
else {
Game(); //ALWAYS
}
}
Since you tagged your question with homework, I will not give the full correction, but now you know where it goes wrong, you should be able to figure out what you need to change in order to advance :)
You mixed or and and (Note: The condition you used (difference<=5||difference>=-5) is always true.). You may use any of the following
if (difference<=5 && difference>=-5) { ... } # difference is 5 or less
or
if (difference<=-5 || difference>=5) { ... } # difference is 5 or more
Better readable if you use Math.abs(...) instead:
if (Math.abs(difference)<=5) { ... } # difference is 5 or less
and
if (Math.abs(difference)>=5) { ... } # difference is 5 or more
resp.
if(difference<=5||difference>=-5) This says if the difference is less than 5 or greater than -5. All numbers are less than 5 or greater than -5, so this is always true.
I'm assuming what you want is something like if(Math.abs(difference)<=5). This will tell you if the absolute value of your difference variable is less than or equal to 5.
Using loop I want to calculate the average of n numbers in Java and when user enters 0 the loop ends.
Here is the code that I have written:
public class start {
public static void main(String[] args) {
System.out.println("Enter an int value, the program exits if the input is 0");
Scanner input = new Scanner (System.in);
int h = 0;
while (input.nextInt() == 0){
int inp = input.nextInt();
int j = inp;
int i = 0;
h = j + i;
break;
}
System.out.println("The total is: "+ h);
}
}
Am I making any logical error?
Don't name the sum h, but sum.
The while-condition is wrong
Why do you use inp and j and i?
There is an unconditional break - why?
You talk about the average. Do you know what the average is?
Your output message is not about average - it is about the sum.
"Am I making any logical error?"
Yes. This looks like a homework problem so I won't spell it out for you, but think about what the value of i is, and what h = j + i means in this case.
You also need to be careful about calling input.nextInt(). What will happen when you call it twice each time through the loop (which is what you are doing)?
Homework, right?
Calling input.nextInt() in the while loop condition and also to fill in int inp means that each trip through the loop is reading two numbers (one of which is ignored). You need to figure out a way to only read one number per loop iteration and use it for both the == 0 comparison as well as for inp.
Additionally, you've done the right thing having h outside the while loop, but I think you're confusing yourself with j and i inside the loop. You might consider slightly more descriptive names--which will make your code much easier to reason about.
You need to keep a counter of how many numbers you read so you can divide the total by this number to get the average.
Edited the while loop:
while(true){
int e=input.nextInt();
if(e==0) break;
h+=e;
numberOfItems++;
}
Your original implementation called nextInt() twice, which has the effect of discarding every other number (which is definitely not what you intended to do).
Assuming that you asking the user only once, to enter and if the number if zero you simply want to display the average. you need a variable declared outside the while loop that will keep adding different numbers entered by the user, along with a second variable which track the number of cases entered by the user and keep incrementing itself by one till number is not zero as entered by the user. And as the user Enters 0, the loop will break and here our Average will be displayed.
import java.util.Scanner;
public class LoopAverage
{
public static void main(String[] args0)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter any Integer value : ");
int value = -1, sum = 0, count = 0;
while((value = scan.nextInt()) != 0)
{
count++;
sum = sum + value;
}
System.out.println("Average : " + (sum / count));
}
}
Hope that might help,
Regards
yes, oodles of logical errors.
your while loop condition is wrong, you're consuming the first value
you enter and unless that number is 0 you never enter the loop at all
i var has no purpose
you're breaking after one iteration
you're not calculating a running total
you're not incrementing a count for the average dividend
you're not calculating an average
This looks like you threw some code together and posted it. The most
glaring errors would have been found just by attempting to run it.
Some other things to consider:
Make sure to check for divide by 0
If you do an integer division, you might end up with an incorrect
average, as it will be rounded. Best to cast either the divisor or
dividend to a float
variable names should be helpful, get into the habit of using them
I recommend you to refer to the condition of "while" loop: if condition meets, what would the program do?
(If you know a little bit VB, what is the difference between do...until... and do...while...?)
Also, when you call scanner.nextInt(), what does the program do? For each input, how should you call it?
Last but not least, when should you use "break" or "continue"?
For the fundamentals, if you are in a course, recommend you to understand the notes. Or you can find some good books explaining details of Java. e.g. Thinking in Java
Enjoy learning Java.
Sooo I started taking my second computer science class ever! For my first class we used python and for this class we're using Java. Our first assignment (pretty much just practice) is to convert this craps program from Python to Java and I'm just having a hell of a time.
Could someone please help with what I've done and umm give me some advice? Maybe a good site for a beginner.... Someone that kinda knows Python (only from a first CS course perspective).
1) In python
def winCraps():
roll = rollDice()
if roll == 7 or roll == 11:
return True
elif roll == 2 or roll == 3 or roll == 12:
return False
else:
return rollForPoint(roll)
This is my attempt at the conversion of it over to java
public int winCraps{
roll = rollDice();
if (roll = 7 && 11){
return (true);
}
else (roll =2 && 3 && 12){
return(false);
}
else{
return rollforPoint(roll);
}
}
2) Python
def rollDice():
raw_input("Press <Enter> to roll...")
die1 = randrange(1,7)
die2 = randrange(1,7)
sum = die1 + die2
print "You rolled", die1, "+", die2, "=", sum
return sum
This one confused the hell out of me. What would randrange be in Java??
Java
static int rollDice(){
System.out.print("Press <Enter> to roll...");
double die1 = Math.random();
double die2 = Math.random();
die1 = (int) die1*6+1;
die2 = (int) die2*6+1;
int sum = (int)die1 + (int)die2;
System.out.println("You rolled "+die1+ " + "+die2+ " = "+sum+".");
return sum;
}
*please bear in mind that I'm just learning this stuff lol
You need to fix your if statements the "==" operator checks for equality, and you must put the variable you are checking against in each section of the statement.
public int winCraps{
roll = rollDice();
if (roll == 7 || roll == 11) {
return true;
}
else if(roll == 2 || roll == 3 || roll == 12) {
return false;
}
else{
return rollforPoint(roll);
}
}
In you rollDice() method, the way you assign values to each die is incorrect. I recommend reading up on random numbers (since this is homework, I'll leave that to you).
Also, remember in java you must always end each statement with a semicolon
What would randrange be in Java?
You can get a random integer in a specific range from Java's Random class by calling the nextInt(int n) method. For example,
Random rand = new Random();
int a = rand.nextInt(7);
will give you a random integer >= 0 and < 7. This isn't exactly the same as randrange in Python, but you could use it as the index to an array of objects, or as the value of a roll of a single die.
Randrange can be replaced by methods in java.util.Random. Like Python, Java has an extensive standard library which you should reference.
1) In Java "OR" operator is "||" not "&&" and comparison operator is "==" as in Python
So
if roll == 7 or roll == 11:
Should be
if( roll == 7 || roll == 11 ) {
and not
if( roll = 7 && 11 ){
2) randrange is : random generator from there you can search: Random in Java
Which will lead you to something like: Random.nextInt()
Use this algorithm ( a) search Internet for Python function, b) understand what it does c) search it in java ) for the next assignment you have and you're done.
You can always ask here again, that's what this site is all about after all
I'd recommend that you look up the docs on randrange(). Once you know exactly what it does, google for the those keywords, plus the word Java.
One thing you'll quickly discover in working with languages is that the APIs can be very different. There might not be an equivalent of randrange in Java, but you might be able to find two or three functions that you can combine to do the same thing.
System.out.print isn't going to cause the system to wait for someone to hit the enter key. For that, you need to do something with System.in, most likely System.in.read(), as it blocks while waiting for input.
Also, in Java, a program starts executing with the main method. To be exact, an executable class starts something like this:
// You'll need the Random class, as per other answers
import java.util.Random;
// assuming WinCraps is the class name
public class WinCraps {
// args in this example is a string array of command-line arguments
public static void main(String[] args) {
// This is where your main method (that calls winCraps?) would be
}
// Other methods
}
Also, any method in this class called directly from main must also be static.
Write out in English what the Python program does. Go through it line by line and explain to yourself what computations are evoked, in other words...what is happening?
Afterwards, write the Java program from that description.
Never ever try to convert the text of a program from one language to another. You'll run into a LOT of problems that way because every language is different, no matter how similar they look.
One major error in your first program that you have in the Java conversion is the conditionals.
Something like (roll =2 && 3 && 12) assigns 2 to roll and then applies AND operators. You also forgot the if. You have elseif in Python.
You want something like:
else if(roll==2 || roll==3 || roll==12)
As for random numbers, there is a function for that in Java.