im having some trouble with my validation. Here is my code
int a = keyboard.nextInt();
int b = keyboard.nextInt();
while(x < -50 || x > 50 && y < -50 || y > 50)
{
System.out.println("Error " + a + " is out of range");
System.out.println("Error " + b + " is out of range");
System.out.println();
System.out.print("Input two integers in the range [-50, + 50]: ");
a = keyboard.nextInt();
b = keyboard.nextInt();
}
while( x < -50 || x > 50)
{
System.out.println("Error " + a + " is out of range");
System.out.println();
System.out.print("Input two integers in the range [-50, + 50]: ");
a = keyboard.nextInt();
b = keyboard.nextInt();
}
while( y < -50 || y > 50)
{
System.out.println("Error " + b + " is out of range");
System.out.println();
System.out.print("Input two integers in the range [-50, + 50]: ");
a = keyboard.nextInt();
b = keyboard.nextInt();
}
My problem, is that the user input needs to be a & b from [-50, 50]
But when i input -100 and 100 I only get a is out of range or b is out of range not both.
Input: a= -100 b = 100
Output:
System.out.println("Error " + -100 + " is out of range"); // CORRECT
System.out.println("Error " + 23 + " is out of range"); // ? INCORRECT
What am i doing wrong
You're being naughty with your operator precedence.
x <= -50 || x >= 50 && y <= -50 || y > 50
is evaluated as
x <= -50 || (x >= 50 && y <= -50) || y > 50
You need to put in some parentheses:
(x <= -50 || x >= 50) && (y <= -50 || y > 50)
Also, check the precise relationship between a, b, x, and y. Why do you assign to a and b, yet then immediately test x and y?
Use absolute values, remember |a| < x means -x < a < x
so both a and b must meet the criteria, or another way, you will ask as long as **a > 50** or **b > 50**
int a = -100;
int b = -100;
Scanner scan = new Scanner(System.in);
while (Math.abs(a) > 50 || Math.abs(b) > 50) {
System.out.println("need a:");
a = scan.nextInt();
System.out.println("need b:");
b = scan.nextInt();
}
scan.close();
System.out.println("am gone!");
check the while loop.
while( x <= -50 || x >= 50 && y <= -50 || y > 50)
both conditions need to be true to execute succesfully.check the &&
As explained in the comments, you are testing x and y but reading a and b.
Additionally, your code can be simplified:
boolean valid = true;
do {
System.out.print("Input two integers in the range [-50, + 50]: ");
int a = keyboard.nextInt();
int b = keyboard.nextInt();
if ( (a < -50) || (a > 50) ) {
valid = false;
System.out.println("Error " + a + " is out of range");
}
if ( (b < -50) || (b > 50) ) {
valid = false;
System.out.println("Error " + b + " is out of range");
}
} while (!valid);
while( x <= -50 || x >= 50 && y <= -50 || y > 50) Java uses "short circuit evaluation" of logical operators. So if x = -100 and y = 0, the loop will be entered because -100 <= -50 and no other conditions matter because true || anything is always true. Use parentheses to control how logical operations are processed. I suggest putting the Boolean condition controlling the while loop into a nicely named method.
private boolean bothParamsAreOutOfRange(int x, int y) {
boolean rtn = false;
if ((x <= -50 || x >= 50) && (y <= -50 || y > 50)) {
rtn = true;
}
return rtn;
}
while(bothParamsAreOutOfRange(x, y)) {
... as before ...
}
Related
I have tried using casting with my variables as well as some of the other tips that I have read on here about getting percentages and its not working here is the code. There is a lot more to it, of course. I have tried all ways from casting, to what I have displayed.
(EDITED AGAIN 2nd time)
Here is the whole code. You were right is was working but in this, it is not! Even if the grade variables are float or int, still not working. Changed the grade variables so they don't display a decimal!. Output (BELOW) shows the grade but not the percentage. Thanks for the feedback.
OUTPUT:
Please enter a grade from 0 - 100! Enter -1 to end the program! 99
Please enter a grade from 0 - 100! Enter -1 to end the program! -1
The total number of grades is 2
Number of A's = 1 which is %0.0
Number of B's = 0 which is %0.0
Number of C's = 0 which is %0.0
Number of D's = 0 which is %0.0
Number of F's = 0 which is %0.0
Code:
public class Main {
public static void main(String[] main) {
Scanner input = new Scanner(System.in) ;
int totalGrades = 1 ;
int gradeA = 0 ;
float gradeAPercentage = (gradeA * 100f) / totalGrades ;
int gradeB = 0 ;
float gradeBPercentage = gradeB / totalGrades ;
int gradeC = 0 ;
float gradeCPercentage = gradeC / totalGrades ;
int gradeD = 0 ;
float gradeDPercentage = gradeD / totalGrades ;
int gradeF = 0 ;
float gradeFPercentage = gradeF / totalGrades ;
int a = 0 ;
do{
System.out.println("Please enter a grade from 0 - 100! Enter -1 to end the program!") ;
int grade = input.nextInt() ;
if( (grade == -1) && (totalGrades == 0) ) {
System.out.println("You entered no grades!") ;
totalGrades--;
break ;
}
else if(grade == -1){
a++ ;
}
else if(grade <= 59){
gradeF++ ;
totalGrades++ ;
}
else if( (grade >= 60) && (grade <= 69) ){
gradeD++ ;
totalGrades++ ;
}
else if( (grade >= 70) && (grade <= 79) ){
gradeC++ ;
totalGrades++ ;
}
else if( (grade >= 80) && (grade <= 89) ){
gradeB++ ;
totalGrades++ ;
}
else if( (grade <= 100) && (grade >= 90) ){
gradeA++ ;
totalGrades++ ;
}
else{
System.out.println("Your input is Invalid") ;
continue ;
}
}while(a < 1 ) ;
System.out.println("The total number of grades is " + totalGrades) ;
System.out.println("Number of A's = " + gradeA + " which is %" + gradeAPercentage) ;
System.out.println("Number of B's = " + gradeB + " which is %" + gradeBPercentage) ;
System.out.println("Number of C's = " + gradeC + " which is %" + gradeCPercentage) ;
System.out.println("Number of D's = " + gradeD + " which is %" + gradeDPercentage) ;
System.out.println("Number of F's = " + gradeF + " which is %" + gradeFPercentage) ;
}
}
There is an implicit casting done, no additional casting to float is needed. The code you provided works fine. If you print the result with
System.out.println(gradeAPercentage);
you will get, what you have wanted to calculate.
I'm making a simple "Whack a mole" game in Java. For simplicity I have created a 10*10 box and placed 10 moles in random boxes. I want to exit the game when the user spent his 50 inputs or found all 10 moles, but there seems to be a problem in terminating the while loop even when the user attempts specified inputs.
Is it Instance variable scope problem? Why it is not working?
public class WhackAMole {
int score = 0, molesLeft = 10, attempts;
char[][] moleGrid = new char[10][10];
int numAttempts, gridDimension;
public WhackAMole(int numAttempts, int gridDimension) {
// TODO Auto-generated constructor stub
this.numAttempts = numAttempts;
this.gridDimension = gridDimension;
}
boolean place(int x, int y) {
return (x == 2 && y == 5)
|| (x == 1 && y == 3)
|| (x == 8 && y == 4)
|| (x == 5 && y == 10)
|| (x == 6 && y == 9)
|| (x == 10 && y == 7)
|| (x == 3 && y == 7)
|| (x == 2 && y == 9)
|| (x == 4 && y == 8)
|| (x == 9 && y == 5);
}
void whack(int x, int y) {
if (place(x, y)) {
if (moleGrid[x - 1][y - 1] == 'W') {
System.out.println("Already attempted! \'try other co-ordinates\' \n");
} else {
moleGrid[x - 1][y - 1] = 'W';
this.score ++;
this.molesLeft --;
}
}
}
void printGridToUser() {
System.out.println("your score is " + score + " and " + molesLeft + " moles are left. \n");
System.out.println("input x = -1 and y = -1 to quit the game! \n");
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
System.out.print(" " + moleGrid[i][j] + " ");
}
System.out.println("\n");
}
}
void printGrid() {
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
this.moleGrid[i][j] = '*';
}
}
}
public static void main(String[] args) {
WhackAMole game;
System.out.println("Lets play the Whack A Mole!\n");
game = new WhackAMole(50, 100);
game.printGrid();
game.printGridToUser();
Scanner scanner = new Scanner(System.in);
while ((game.numAttempts > 0) || (game.molesLeft > 0)) {
System.out.println("Enter box co-ordinate\n");
System.out.println("x co-ordinate: \n");
int x = scanner.nextInt();
System.out.println("y co-ordinate: \n");
int y = scanner.nextInt();
if (x == -1 && y == -1) {
break;
} else if ((x < 1 || y < 1) || (x > 10 || y > 10)) {
System.out.println("please enter values of x and y greater than 0 and less than 11! \n");
} else {
game.whack(x, y);
game.numAttempts--;
game.gridDimension--;
System.out.println("you can have upto " + game.numAttempts + " out of " + game.gridDimension + " boxes \n");
game.printGridToUser();
}
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (game.place(i+1, j+1) && game.moleGrid[i][j] != 'W'){
game.moleGrid[i][j] = 'M';
}
}
}
game.printGridToUser();
scanner.close();
System.out.println("game over!!!\n");
}
}
Your while loop is not ending because you are using || in your while loop. The || is making your loop run until the attempts allowed i.e. 50 and the right guessing i.e. finding moles correct both are met. So even when a gamer has finished his allowed attempts and hasn't guessed all the right moles positions, the loop will not end
The simple solution would be to replace || with &&
while ((game.numAttempts > 0) && (game.molesLeft > 0))
And avoid using fixed numbers i.e. 10 in your for loops instead use
for (int i = 0; i < game.gridDimension; i++) {
for (int j = 0; j < game.gridDimension; j++) {
I hope it helps
Your loop is using an or for the test function. This means both condition mist be false in order for it to stop. In your case. How its written you must exhaust the numtries and have no moles left.
Change to use && vs ||.
public static void notDivisible(int n, int x, int y)
{
Scanner kb = new Scanner(System.in);
System.out.println("These are the ints from 1 to" + n + "that are not divisible by" + x + "or" + y);
n = kb.nextInt();
x = kb.nextInt();
y = kb.nextInt();
if((n%x) == 0)
{
}
else
{
System.out.println()
}
if((n%y) == 0)
{
}
else
{
System.out.println();
}
So this is all I have so far. I know that I have to use modulus and print out the numbers that aren't divisible by the number, but how can I do it?
Reading "not divisible by x or y" as "divisible by neither x nor y":
for (int i = 1; i <= n; ++i) {
if (i%x!=0 && i%y!=0) {
System.out.println(i);
}
}
Make a loop from 1 to the limit (n).
for(int i = 1; i < n; i++)
{
if(i % x != 0 || i % y != 0)
{
System.out.println(i);
}
}
The modulus (%) is the rest of the division. If i % x is different from 0 that means i cannot be divided by x.
First of all you will need to ask the user the numbers n, x and y before printing them.
Then what you want to achieve is a typical job for for loops:
for(int i=0; i<n; ++i) {
if(i%x != 0 && i%y != 0) {
System.out.println(i);
}
}
Try doing your next exercise alone ;)
This reeks of homework. But against my better judgment:
for(int z=1; z<n; z++) { // Test all numbers from 1 to n
if((z % x) == 0) {
System.out.println(z + " is divisible by " + x);
} else System.out.println(z + " isn't divisible by " + x);
if((z % y) == 0) {
System.out.println(z + " is divisible by " + y);
} else System.out.println(z + " isn't divisible by " + y);
}
So I am doing a code for girl scout cookies. My array length is how many girl scouts there are and they each have a certain number of cookies. The program gets those two variables from the user and then at the end it shows with four different criteria how many girls sold how many cookies. My question is if there is another for loop I can use at the end where I assign girls into different categories. So what else can I do instead of for(int x : cookiesSold)?
import java.util.Scanner;
public class girlScoutCookies {
public static void main(String[] args) {
int cookies1 = 0;
int cookies2 = 0;
int cookies3 = 0;
int cookies4 = 0;
int numOfGirls = 0;
Scanner n = new Scanner(System.in);
System.out.println("How many girls are in the girl scouts?");
numOfGirls = n.nextInt();
if(numOfGirls <= 0){
System.out.println("There should be at least one girl selling cookies");
}else{
numOfGirls = numOfGirls;
}
int[] cookiesSold = new int[numOfGirls];
for(int i = 0; i<numOfGirls;i++){
System.out.println("What is the number of cookies the girl has sold");
cookiesSold[i] = n.nextInt();
}
for(int x : cookiesSold){
System.out.println("This is x: " +x);
if(x >= 0 && x <= 10 ){
cookies1++;
}else if(x >= 11 && x<=20 ){
cookies2++;
}else if(x >= 21 && x<=30 ){
cookies3++;
}else if(x >= 31 ){
cookies4++;
}
}
System.out.println("The number of girls that sold the following cookies are:\n 0 to 10 cookies:\t " + cookies1 + "\n 11 to 20 cookies:\t " + cookies2 + "\n 21 to 30 cookies:\t " + cookies3 + "\n 31 or more cookies: \t " +cookies4);
}
}
Instead of 4 variables, use an array:
// Remove these:
int cookies1 = 0;
int cookies2 = 0;
int cookies3 = 0;
int cookies4 = 0;
// Replace with this:
int[] cookies = new int[4];
Next, use integer arithmetic to find the index from the cookiesSold value. Note that you must cap the index at 3:
// Remove all this:
if(x >= 0 && x <= 10 ){
cookies1++;
}else if(x >= 11 && x<=20 ){
cookies2++;
}else if(x >= 21 && x<=30 ){
cookies3++;
}else if(x >= 31 ){
cookies4++;
}
// Replace with just this line:
cookies[Math.min(x / 10, 3)]++;
For a more robust solution, use the length of the array, so to increase the number of slots, just change the size of the array:
cookies[Math.min(x / 10, cookies.length - 1)]++;
I ran across this puzzle today. Obviously, this isn't correct style, but I'm still curious as to why no output is coming out.
int x = 9;
int y = 8;
int z = 7;
if (x > 9) if (y > 8) System.out.println("x > 9 and y > 8");
else if (z >= 7) System.out.println("SHOULD OUTPUT THIS x <= 9 and z >= 7");
else
System.out.println("x <= 9 and z < 7");
The above has no output when run. But, when we add in brackets for the if-statement, suddenly the logic behaves as I expect.
int x = 9;
int y = 8;
int z = 7;
if (x > 9) {
if (y > 8) System.out.println("x > 9 and y > 8");
}
else if (z >= 7) System.out.println("SHOULD OUTPUT THIS x <= 9 and z >= 7");
else
System.out.println("x <= 9 and z < 7");
This outputs "SHOULD OUTPUT THIS x <= 9 and z >= 7". What is going on here?
Thanks!
If you rewrite the first way like this (which is how it is behaving), it is easier to understand
if (x > 9)
if (y > 8) System.out.println("x > 9 and y > 8");
else if (z >= 7) System.out.println("SHOULD OUTPUT THIS x <= 9 and z >= 7");
else
System.out.println("x <= 9 and z < 7");
Since x is not > 9, the block never executes.
This:
if (x > 9) ... if (y > 8) ... else if (z >= 7) ... else
is ambiguous, because during parsing the else could be bound to the first if or the second if. (This is called the dangling else problem). The way Java (and many other languages) deals with this is to make the first meaning illegal, so the else clauses always bind to the innermost if statements.
Just fix the indenting on your code and the issue becomes clear:
int x = 9;
int y = 8;
int z = 7;
if (x > 9)
if (y > 8)
System.out.println("x > 9 and y > 8");
else if (z >= 7)
System.out.println("SHOULD OUTPUT THIS x <= 9 and z >= 7");
else
System.out.println("x <= 9 and z < 7");
Because you are using the else block in inner most level
Your code is being treated as the following code
if (x > 9) // This condition is false, hence the none of the following statement will be executed
{
if (y > 8)
{
System.out.println("x > 9 and y > 8");
} else if(z >= 7)
{
System.out.println("SHOULD OUTPUT THIS x <= 9 and z >= 7");
}
else
{
System.out.println("x <= 9 and z < 7");
}
}
The first condition specified with the if statement is false and control in not entering into the code associated with that condition and simply reaching the end of the program and printing nothing.
That's why its normal practice is to enclose statements with brackets even if you are writing a single statement.