Lately , i have been practicing on my beginner tutorials on java,
However i got stuck with the if else statement ,
My main focus was to let user to write if user try greater than 5 times, it will return false , Else it will return true.
Any help will be greatly appreciated.
int userTry = 0;
double value1 = 0;
Scanner useranswer1 =new Scanner(System.in);
if(userTry == 5){
do{
System.out.println("What is 10 divided by 4?");
value1 = useranswer1.nextDouble();
}
while(value1 != 2.5);
System.out.println("You got the right answer");
} else {
} System.out.println("You have zero more tries");
}
Try the following:
int userTry = 0;
double value1 = 0;
Scanner useranswer1 =new Scanner(System.in);
for (int userTry = 5; userTry > 0; userTry--)
System.out.println("What is 10 divided by 4?");
value1 = useranswer1.nextDouble();
if (value1 == 2.5) break;
System.out.println(); // empty line
}
if (value1 == 2.5) {
System.out.println("You got the right answer");
} else {
System.out.println("You have zero more tries");
}
}
The key is to set the condition of your do-while loop based on the check that the user didn't get the right value and if they have enough retries.
If the user got the right value, they've done so in the required number of retries, otherwise, they've zero tries. Hope this helps.
int userTry = 0;
double value1 = 0.0;
Scanner useranswer1 = new Scanner(System.in);
do {
System.out.println("What is 10 divided by 4?");
value1 = useranswer1.nextDouble();
} while (value != 2.5 && ++userTry < 5); // NOTE: pre-increment and check. If you like to have a safer version, move this increment inside the while loop.
if (value1 != 2.5) {
System.out.println("You have zero more tries");
} else {
System.out.println("You got the right answer!");
}
int count = 0;
double trueAnwer = 6.66;
while (true) {
count++;
Scanner useranswer1 =new Scanner(System.in);
if (trueAnwer == useranswer1.nextDouble()) {
System.out.println("You got the right answer");
return;
}
if (count==5) {
System.out.println("You have zero more tries");
return;
}
System.out.println("This is "+count+" times");
}
Try this:
do{
System.out.println("What is 10 divided by 4?");
value1 = useranswer1.nextDouble();
userTry++;
}
while(value1 != 2.5 && userTry != 5);
if(userTry == 5){
System.out.println("You have zero more tries");
} else {
System.out.println("You got the right answer");
}
Related
I wrote a code about primes and would hear your opinion or any suggestions how i can improve my code. I'm a beginner in Java.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean a;
System.out.println("Please enter a number: ");
int zahl = s.nextInt();
if(zahl <= 0) {
System.out.println("Please enter a positive number without zero.");
return;
}
a = true;
for (int i = 2; i < zahl; i++) {
if (zahl % i == 0) {
a = false;
}
}
if (a == true) {
System.out.println("Is Prim");
}
if (a==false){
System.out.println("Not a prim");
}
}
The easiest thing to do is the following
Instead of
for (int i = 2; i < zahl; i++) {
if (zahl % i == 0) {
a = false;
}
}
change the for loop the
for (int i = 2; i < Math.sqrt(zahl); i++)
If no numbers up to the square root divide zahl, then no numbers beyond the square root will divide it either (they would have been the result of earlier divisions).
Also, for outputing the answer you could do:
System.out.println(zahl + " is " + ((a) ? "prime"
: "not prime"));
That's using the ternary operator ?:
some hints :
You do
System.out.println("Please enter a positive number without zero.");
return;
the println suggests the user can enter a new value, but no, in that case better to say the number was invalid so you exit
When you do a = false; it is useless to continue, no chance for a to be back true
It is useless to try to divide by more than sqrt the number
It is necessary to try to divide by 2 but not by an other even number, so add 2 to i rather than 1
If if (a == true) false it is useless to check if (a==false)
Your code is good. I have made three small improvements:
The input asks at once (and not only after a bad input) for a
positive int.
The input is repeated until correct.
The for loop runs only up to sqrt(zahl) which is sufficient.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean a;
int zahl = 0;
while (zahl <= 0) {
System.out.println("Please enter a positive int without zero.");
zahl = s.nextInt();
}
a = true;
for (int i = 2; i <= Math.sqrt(zahl); i++) {
if (zahl % i == 0) {
a = false;
break;
}
}
if (a == true) {
System.out.println("Is Prim");
} else {
System.out.println("Not a prim");
}
}
I'm writing code to let users guess the number. Thay have only two chance to got all
If user put wrong input (Beyond 1-4),
they can do it again. In this case, the user must answer 2 and 4 to get all.
System.out.println("you have only two chance to get all");
int guessnum[] = new int[2];;
for (int i = 0; i < guessnum.length; i++) {
System.out.print((i+1)+" Enter number 1-4 : ");
int num = sc.nextInt();
if (num == 1) {
System.out.println("not here");
}
else if (num == 2) {
System.out.println("wow!! you got it");
}
else if (num == 3) {
System.out.println("not here");
}
else if (num == 4) {
System.out.println("wow!! you got it");
}
else {
System.out.println("number must be 1-4 only, try again");
//how to repeat in same loop
}
}
Use the break statement
else if (num == 2) {
System.out.println("wow!! you got it");
break;
}
for (int i = 0; i < guessnum.length; i++) {
int count = 1;
System.out.print((i+1)+" Enter number 1-4 : ");
int num = sc.nextInt();
if (num == 1) {
System.out.println("not here");
}
else if (num == 2) {
System.out.println("wow!! you got it");
}
else if (num == 3) {
System.out.println("not here");
}
else if (num == 4) {
System.out.println("wow!! you got it");
} else {
if (i != 2) {
System.out.println("number must be 1-4 only, try again,and change another number");
} else {
break;
}
//do again in same loop
}
i++;
}
you can try this
Here is all my code, in two chance the user needs to put 2 and 4 to win.
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("you have only two chance to get all");
int guessnum[] = new int[2];
int x=0;
for (int i = 0; i < guessnum.length; i++) {
System.out.print((i+1)+" Enter number 1-4 : ");
int num = sc.nextInt();
if (num == 1) {
System.out.println("not here");
}
else if (num == 2) {
System.out.println("wow!! you got it");
x++;
}
else if (num == 3) {
System.out.println("not here");
}
else if (num == 4) {
System.out.println("wow!! you got it");
x++;
}
else {
System.out.println("number must be 1-4 only, try again");
--i;
}
}
if (x == 0)
System.out.println("\nyou don't get anything");
if (x == 1)
System.out.println("\nyou got 1 only");
if (x == 2)
System.out.println("\ncongrat!!!! you got all");
}
}
If you wanna use for loop you can write something like this --i; in the last else block after System.out.println("number must be 1-3 only, try again");
So, this code will solve your problem:
System.out.println("you have only two chance to get all");
int guessnum[] = new int[2];;
for (int i = 0; i < guessnum.length; i++) {
System.out.print((i+1)+" Enter number 1-4 : ");
int num = sc.nextInt();
if (num == 1) {
System.out.println("not here");
}
else if (num == 2) {
System.out.println("wow!! you got it");
}
else if (num == 3) {
System.out.println("not here");
}
else if (num == 4) {
System.out.println("wow!! you got it");
}
else {
System.out.println("number must be 1-4 only, try again");
--i;
}
}
UPDATE
In my answer above I just said, how to repeat for loop with minimal changes to the original code. As was asked in the title. But #JayPrakash said that it wasn't perfect answer and vote it down. Ok, lets try to find the perfect one:
public static void main(String[] args) {
guess(2, 1, 4, new int[]{2, 4});
}
/**
*
* #param tries tries count
* #param from from range, inclusive
* #param to to range inclusive
* #param puzzled array with puzzled values
* #return array, which contains only puzzled answers from a user
*/
public static int[] guess(int tries, int from, int to, int[] puzzled) {
if (puzzled == null || puzzled.length < 1) throw new IllegalArgumentException("puzzled");
if (Math.abs(from - to) < 1) throw new IllegalArgumentException("range");
if (tries < 1 || Math.abs(from - to) < tries - 1) throw new IllegalArgumentException("tries"); //`tries - 1` because `to` is inclusive
if (from > to) {
int tmp = from; from = to; to = tmp;
}
Scanner sc = new Scanner(System.in);
int answers[] = new int[tries], //all previous user answers
result[] = new int[tries];
System.out.printf("You have only %d chances to get all\n", tries);
int i = 0, j = 0;
while (i < tries && j < puzzled.length) { // `j < puzzled.length` break if all puzzled answers is found
System.out.printf("%d Enter number %d-%d: ", (i + 1), from, to);
int number = sc.nextInt();
if (number < from || number > to) {
System.out.printf("Number must be in %d-%d range only, try again\n", from, to);
continue;
}
if (contains(answers, number, i)) {
System.out.printf("Number %d is used before\n", number);
continue;
}
answers[i++] = number;
if (contains(puzzled, number)) {
System.out.println("Wow!! you got it");
result[j++] = number;
} else {
System.out.println("Not here");
}
}
if (j == puzzled.length)
System.out.println("You got all");
else
System.out.printf("You got %d only\n", j);
return Arrays.copyOfRange(result, 0, j);
}
private static boolean contains(int[] array, int value) {
return contains(array, value, array.length);
}
private static boolean contains(int[] array, int value, int lookTo) {
for (int i = 0; i < lookTo; i++)
if (array[i] == value)
return true;
return false;
}
int i = 1;
Scanner sc = new Scanner(System.in);
do {
System.out.println("you have only two chance to get all");
System.out.print((i) + " Enter number 1-4 : ");
int num = sc.nextInt();
switch (num) {
case 1:
System.out.println("not here");
break;
case 2:
System.out.println("wow!! you got it");
goItOrNot = false;
break;
case 3:
System.out.println("not here");
break;
case 4:
System.out.println("wow!! you got it");
break;
default:
System.out.println("number must be 1-4 only, try again");
break;
}
i++;
}
} while (i < 3);
When I click retry on this code, it work's and asks how many times to loop flip a coin but the just prints "Flipping Coin(s)" and does nothing. Anyone know how to fix it? I think the error might be coming from X already being less than numloop but I am not sure how to fix it.
Here is my code:
import java.util.Scanner;
public class coinFlip {
public static void main (String[]args)throws InterruptedException {
Scanner sc = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
int numloop;
int x = 0;
String choice;
Boolean bool = true;
while (bool=true){
System.out.println("How Many Coins Would You Like To Flip?");
numloop = sc.nextInt();
if (numloop == 13 || (numloop == 5 || (numloop == 8 || (numloop == 666)))) {
System.out.println("ILLUMINATI CONFIRMED ??????");
System.out.println();
}
System.out.println("Flipping Coin(s)...");
System.out.println();
while (x<numloop) {
int rng = (int)(Math.random()*10+1);
if (rng <= 5) {
System.out.println("You Flipped Heads");
}
else {
System.out.println("You Flipped Tails");
}
x=x+1;
}
System.out.println();
System.out.println("Would You Like To 'Quit' Or 'Retry'?");
choice = scan.nextLine();
if (choice.equalsIgnoreCase("Quit")) {
System.out.println ("Have A Nice Day");
Thread.sleep(1000);
System.exit(0);
}
if (choice.equalsIgnoreCase("Retry")) {
bool=true;
}
}
}
}
Thank You So Much!
If you move int x=0 from outside of your initial while loop to inside of it you won't have this issue. It will reset every time the user retries.
Scanner sc = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
int numloop;
String choice;
Boolean bool = true;
while (bool=true){
int x = 0;
System.out.println("How Many Coins Would You Like To Flip?");
numloop = sc.nextInt();
if (numloop == 13 || (numloop == 5 || (numloop == 8 || (numloop == 666)))) {
System.out.println("ILLUMINATI CONFIRMED ??????");
System.out.println();
}
System.out.println("Flipping Coin(s)...");
System.out.println();
while (x<numloop) {
int rng = (int)(Math.random()*10+1);
if (rng <= 5) {
System.out.println("You Flipped Heads");
}
else {
System.out.println("You Flipped Tails");
}
x=x+1;
}
System.out.println();
System.out.println("Would You Like To 'Quit' Or 'Retry'?");
choice = scan.nextLine();
if (choice.equalsIgnoreCase("Quit")) {
System.out.println ("Have A Nice Day");
Thread.sleep(1000);
System.exit(0);
}
if (choice.equalsIgnoreCase("Retry")) {
bool=true;
}
}
}
I wrote a small code :
System.out.println("Please enter a number");
int number = scan.nextInt();
if(number == 1) {
System.out.println("Number is 1");
} else if(number == 2) {
System.out.println("Number is 2");
} else {
System.out.println("Invalid selection");
}
When the user enters a number different than 1 and 2, user gets "Invalid selection" message and then code terminates. I don't want it to terminate, I want it to run again until user writes 1 or 2. I tried do-while loop but it become an infinite loop. What are your suggestions?
You can use while loop here
Scanner scanner = new Scanner(System.in);
boolean status = true;
while (status) { // this runs if status is true
System.out.println("Please enter a number");
int number = scanner.nextInt();
if (number == 1) {
System.out.println("Number is 1");
status=false; // when your condition match stop the loop
} else if (number == 2) {
System.out.println("Number is 2");
status=false;// when your condition match stop the loop
} else{
System.out.println("Invalid selection");
}
}
Try this...
int number;
do{
System.out.println("Please enter a number");
number = scan.nextInt();
if(number == 1)
{
System.out.println("Number is 1") ;
}
else if(number == 2)
{
System.out.println("Number is 2") ;
}
else
{
System.out.println("Invalid selection") ;
}
}while(number!=1 && number!=2);
I recommend you check if there is an int with Scanner.hasNextInt() before you call Scanner.nextInt(). And, that makes a nice loop test condition if you use it in a while loop.
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a number");
while (scan.hasNextInt()) {
int number = scan.nextInt();
if (number == 1) {
System.out.println("Number is 1");
break;
} else if (number == 2) {
System.out.println("Number is 2");
break;
} else {
System.out.println("Invalid selection");
}
}
// ...
#Dosher, reposting #Raj_89's answer with correction in while loop condition. Please notice While loop condition
int number = 0;
do{
System.out.println("Please enter a number");
Scanner scan = new Scanner(System.in);
number = scan.nextInt();
if(number == 1)
{
System.out.println("Number is 1") ;
}
else if(number == 2)
{
System.out.println("Number is 2") ;
}
else
{
System.out.println("Invalid selection") ;
}
}while(number==1 || number==2);
The title is probably not very informative. But here's the deal.
I want the user to execute a code if it's the second time he is passing there. What I did, was making a if statement, but now I've noticed, that with that, the rest isn't being executed.
Scanner input = new Scanner(System.in);
Random dice = new Random();
int counter = 1;
boolean playing = true;
boolean firstTimmer = true;
boolean got = true;
System.out.println("Welcome to numberMind! From 0 to x, you'll try to guess the random number!");
System.out.println("To quit, guess \"-1\".");
System.out.print("Insert x: ");
int x = 1+input.nextInt();
int objective = dice.nextInt(x);
System.out.print("Ok, I'm ready! What's your first guess? ");
int guess = input.nextInt();
while (playing){
if (guess == -1){
playing = false;
break;
}else if (!firstTimmer){
got = true;
System.out.print("Do you want to change the number range? Yes(1) No(2)");
guess = input.nextInt();
if (guess == 1){
System.out.print("Insert the new x: ");
x = 1+input.nextInt();
}else if(guess == 2){
System.out.println("Let's go then!");
}else{
System.out.print("I didn't ask for that number did I? x won't change.");
}
}else{
while(got){
if (objective == guess){
firstTimmer = false;
System.out.println("You guessed it in "+counter+" times!");
counter = 1;
System.out.print("Do you want to paly again? Yes(1) No(2) ");
guess = input.nextInt();
if (guess == 1){
System.out.println("Great! Here we go...");
got = false;
break;
}else if (guess == 2){
System.out.print("Thanks for playing!");
got = false;
playing = false;
}else{
System.out.println("We didn't ask for that. NOW YOU PLAY SOME MORE!");
got = false;
break;
}
break;
}else if (guess == -1){
System.out.println("You quited :(");
break;
}else if (guess == -2){
System.out.println("The correct answer is "+ objective);
}else if (counter >= 5 && (counter -5) % 3 == 0 ){
if (objective % 2 == 0){
System.out.println("The number is pair.");
}else{
System.out.println("The number is odd.");
}
}
System.out.println("You have tryed " + counter++ + " times.");
System.out.print("What's your guess? ");
guess = input.nextInt();
}
}
}
The code I want to run is after the last else. I'm not seeing anything to solve it. Thank you
Well start by asking yourself when the else will be fulfilled: when guess != -1 and firstTimmer == true. You don't ever set firstTimmer, which needs to be set to true to pass through the the else block. You also need to remove the break in your else if, otherwise it will never reach the else on the next iteration.
Also, having both playing = false and break in your if statement is redundant. Both will do the same thing individually.
while (playing){
if (guess == -1){
playing = false;
break;
}else if (!firstTimmer){
got = true;
System.out.print("Do you want to change the number range? Yes(1) No(2)");
guess = input.nextInt();
if (guess == 1){
System.out.print("Insert the new x: ");
x = 1+input.nextInt();
}else if(guess == 2){
System.out.println("Let's go then!");
}else{
System.out.print("I didn't ask for that number, x won't change.");
}
firstTimmer = true;
//break;
}else{
int counter = 0;
while(playing) {
counter++; //First iteration: was zero, now 1
if(counter == 2) {
//Do some special thing
}
}
(One) standard pattern for this sort of thing is:
boolean firstTime = true;
boolean playing = true;
int guess = 0;
while (playing) {
if (guess == -1) {
playing = false;
// NOTE: break is redundant with playing flag, here
} else if (!firstTime) {
got = true;
System.out.print("Do you want to change the number range? Yes(1) No(2)");
guess = input.nextInt();
if (guess == 1) {
System.out.print("Insert the new x: ");
x = 1+input.nextInt();
} else if(guess == 2) {
System.out.println("Let's go then!");
} else {
System.out.print("I didn't ask for that number, x won't change.");
}
firstTime = false;
} else {
//... do other work here.
}
}
Also, the pattern mentioned by aliteralmind is a more flexible version of the above, allowing you to present a different option for every "visit" through the loop. I can describe further if necessary, with a complete example.
You should try to solve a one problem per time in your code.
Now you have a lot of complicated code that is hard to read and work with.
The answer to your question, regarding the first time visit. Just move it before loop and then start the loop if necessary.
Try to divide the problem in sub programs (methods) and the solve them by once.
displayWelcomeScreen();
preapreGameContext();
do {
if(doUserWantToChange()) {
changeTheGameContext();
}
int gues = askForGues();
hasUserGuesCorrectly();
} while(isTheGameOn());
The final code should look more alike the example above.