this is guess number programme using constructor but the issue which I am facing
is not able to express user input in loop.I tried to look for it but not good explanation.
import java.util.Scanner;
import java.lang.Math;
class guessnumber{
public int getRandomNumber(int min, int max) {
return (int) ((Math.random() * (max - min)) + min);
}
public String userinput(int repeats,int rand){
String e;
e="that's it";
if(repeats<rand){
String z="choose higher number";
System.out.println(z);
}
else if (repeats>rand){
String z="choose lower number";
System.out.println(z);
}
return e;
}
public String iscorrect(){
String correct="correct number";
return correct;
}
}
public class guessthenumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
guessnumber gun = new guessnumber();
System.out.println("enter number ");
int number = sc.nextInt();
System.out.println("enter max and min number");
int min = sc.nextInt();
int max = sc.nextInt();
int o=gun.getRandomNumber(min,max);
System.out.println(o);
if (number < o || number > o) {
System.out.println(gun.userinput(number, o));}
else if(number==o){
String correct= gun.iscorrect();
System.out.println(correct);
}
}
}
I want to user to keep entering data till correct number is hit
Here's a solution that behaves like you're describing, and how your code currently behaves:
ask for a few numbers up front (minimum, maximum)
determine a random "target" number for the user to guess
ask the user to guess – if they're correct, show a message; if they're incorrect, ask for another guess
repeat until their guess is correct
A few things I did:
introduce a "getNumber()" helper that will make sure the numbers make sense – put some guardrails around what a user can enter to minimize unexpected results if user enters unexpected input
use a "while" loop, go forever – while (true)
if their guess matches the target, use break to stop the loop
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int minimum = getNumber(scanner, 0, "minimum");
int maximum = getNumber(scanner, minimum + 1, "maximum");
int target = (int) ((Math.random() * (maximum - minimum)) + minimum);
while (true) {
System.out.print("enter a guess: ");
int guess = scanner.nextInt();
if (guess == target) {
System.out.println("correct guess! the number was " + target);
break;
} else {
System.out.print("nope, please try again.. ");
}
}
}
static int getNumber(Scanner scanner, int minimumAllowed, String numberType) {
while (true) {
System.out.print("enter " + numberType + " number: ");
int minimum = scanner.nextInt();
if (minimum >= minimumAllowed) {
return minimum;
} else {
System.out.println("too small, must be at least " + minimumAllowed);
}
}
}
Here's a sample run:
enter minimum number: 1
enter maximum number: -3
too small, must be at least 2
enter maximum number: 5
enter a guess: 1
nope, please try again.. enter a guess: 2
nope, please try again.. enter a guess: 3
nope, please try again.. enter a guess: 4
correct guess! the number was 4
You can use while and break statements
Related
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter your salary per hour: ");
int salary = input.nextInt();
System.out.print("Enter number of hours: ");
int hours = input.nextInt();
int sum = salary * hours;
if (hours == 0) {
System.out.println("Stop!");
break;
}
System.out.println("Total salary " + sum);
}
}}
I want to be able to enter numbers until I press 0, and then I want the program to stop. It stops after two zeros, but how can I make it stop after pressing only one zero? I have tried this while-if loop and different do-while loops, I just can't make it work.
Your code does exactly what you tell it to do.
You tell it to:
first ask for TWO numbers
to then compare the first number, and stop on 0
So, the solution is:
ask for one number
compare the number, stop on 0
ask for the second number
If you want to exit whenever you type 0, then you have to check every value after its input.
There is the code example:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("What's your salary per hour? ");
int salary = scanner.nextInt();
if (salary == 0)
exit();
System.out.print("How many hours did you worked today? ");
int hours = scanner.nextInt();
if (hours == 0)
exit();
int sum = salary * hours;
System.out.println("Your total salary is " + sum);
}
}
private static void exit() {
System.out.println("Have a nice day!");
System.exit(0);
}
Please write a comment if that doesn't match your expectation
Hi guys I'm writing a program which plays a guessing game with the user. You need to think of a number and the program will guess it. Here's my code:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Guess a number between 1 do 100 and i'll guess it");
int min = 0;
int max = 100;
int guess = (max-min)/2 + min;
boolean end = false;
while(!end){
System.out.println("zgaduje " + guess);
String userInput = scan.next();
if(userInput.equalsIgnoreCase("too much")){
max = guess;
}
else if(userInput.equalsIgnoreCase("too small")){
min=guess;
}
else if(userInput.equalsIgnoreCase("correct")){
end = true;
}
guess = (max-min)/2 + min;
}
}
}
So the program guesses a number, and then based on the user input (too small or too much) it guesses again. It does not work as it supposed to, it only displays the first guess over again. Do you have any idea what might be wrong here?
You use scan.next();. For input too much, that will return only too.
To read the whole line, you need to use scan.nextLine();
You should use NextLine instead of next:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Guess a number between 1 do 100 and i'll guess it");
int min = 0;
int max = 100;
int guess = (max-min)/2 + min;
boolean end = false;
while(!end){
System.out.println("guess is" + guess);
String userInput = scan.nextLine();
if(userInput.equalsIgnoreCase("too much")){
max = guess;
}
else if(userInput.equalsIgnoreCase("too small")){
min=guess;
}
else if(userInput.equalsIgnoreCase("correct")){
end = true;
}
guess = (max-min)/2 + min;
}
}
This is my code:
public static void main(String[] args) {
int number;
System.out.println("Enter here: ");
Scanner sc = new Scanner(System.in);
number = sc.nextInt();
int reverse=0;
while(number!=0) {
int rel = number%10;
reverse = (reverse*10)+ rel;
number = number/10;
}
if (number == reverse ) {
System.out.println("the number is palaindrome " + reverse);
} else {
System.out.println("the number is not palaindrome " + reverse);
}
}
Every time I am getting the number is not palindrome output even if the input is palindrome.
You are updating the origial number (number) in the while loop as well.
So in the if statement number will never be equal to the reverse.
Save your number in a temporary variable to use it in a while loop.
Your final code should look like this.
int temp = number;
while(temp!=0) {
int rel = temp%10;
reverse = (reverse*10)+ rel;
temp= temp/10;
}
if (number == reverse ) {
System.out.println("the number is palaindrome "+reverse );
}else
System.out.println("the number is not palaindrome "+reverse);
Hope this solves your problem.
Because you are updating the number.
Store it locally and then operate it in while loop.
int lNum = number;
while(number!=0) {
int rel = number%10;
reverse = (reverse*10)+ rel;
number= number/10;
}
if (lNum == reverse ) {
System.out.println("the number is palaindrome "+reverse );
}else
System.out.println("the number is not palaindrome "+reverse);
See here working after correction.
You need to keep current value (temp) and then compare actual value which you saved (temp) with reverse one, below I am sharing code which I tried locally.
import java.util.Scanner;
public class Stack1 {
public static void main(String[] args) {
int number;
System.out.println("Enter here: ");
Scanner sc = new Scanner(System.in);
number = sc.nextInt();
int reverse = 0;
int temp = number;
while (number != 0) {
int rel = number % 10;
reverse = (reverse * 10) + rel;
number = number / 10;
}
String resMessage = temp == reverse ? "the number is palaindrome " + reverse
: "the number is not palaindrome " + reverse;
System.out.println(resMessage);
}
}
And just a suggestion, if you are asking question on SO then try to put brief description of what you are looking for. This will help other folks here to provide you best solution.
Hope this will help.
This is happening because you reassign number here number = number/10;.
you can save a reference to number and work with that here if (numberRef == reverse ) {, like this:
public static void main(String[] args) {
int number;
System.out.println("Enter here: ");
Scanner sc = new Scanner(System.in);
number = sc.nextInt();
int numberRef = number;
int reverse=0;
while(number != 0) {
int rel = number%10 == 0 ? 0 : number % 10;
reverse = (reverse*10) + rel;
number= number/10;
}
if (numberRef == reverse ) {
System.out.println("the number is palaindrome "+reverse );
} else
System.out.println("the number is not palaindrome " + reverse);
/*Everytime I am getting the number is not palaindrome output even if the input is palaindrome.*/
}
Because the number variable is 0 after while loop. And you also check it like. 0 == reverse .
Its the problem in your code. Is it possible to input as a String? Then have a small solution.
i'm learning Java with the book think Java : how to think like a computer scientist ? and there is no exercise answers in the book, usually i end up finding similar exercices on different websites but not for this one because i have precise instructions. Can you please tell me if it's correct.
I think the problem is solved, the job is done, but is there an easier way to do it ?
Thanks a lot
Exercise 5-7.
Now that we have conditional statements, we can get back to the “Guess My Number” game from Exercise 3-4.
You should already have a program that chooses a random number, prompts the user to guess it, and displays the difference between the guess and the chosen number.
Adding a small amount of code at a time, and testing as you go, modify the program so it tells the user whether the guess is too high or too low, and then prompts the user for another guess.
The program should continue until the user gets it right. Hint: Use two methods,
and make one of them recursive.
import java.util.Random;
import java.util.Scanner;
public class GuessStarter {
public static void Lower(int number,int number2) {
Scanner in = new Scanner(System.in);
System.out.print("Too Low , try again ");
number2 = in.nextInt();
if (number2==number) {
System.out.println("You're right");}
else if (number2>number)
Higher(number,number2);
else
Lower(number,number2); }
public static void Higher(int number,int number2) {
Scanner in = new Scanner(System.in);
System.out.print("Too high , try again ");
number2 = in.nextInt();
if (number2==number) {
System.out.println("You're right");}
else if (number2>number)
Higher(number,number2);
else
Lower(number,number2); }
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random random = new Random();
int number = random.nextInt(100) + 1;
int number2;
System.out.print("Type a number: ");
number2 = in.nextInt();
if (number2==number) {
System.out.println("You're right");}
else if (number2>number)
Higher(number,number2);
else
Lower(number,number2);}
}
Don't know if it'll be useful now or not, but, as I was solving the same solution, thought of letting it know if someone finds it useful:
import java.util.Random;
import java.util.Scanner;
/**
* Created by RajU on 27-Jun-17.
*/
public class GuessNumber2 {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
message("I'm thinking of a number between 1 and 10 (including both).\n" +
"Can you guess what it is?\n" +
"Type a number: ");
int userNumber = input.nextInt();
tryAgain(userNumber, calculateRandom(10));
}
public static int calculateRandom(int n) {
Random random = new Random();
return random.nextInt(n) + 1;
}
public static void tryAgain(int userNumber, int generateRandom) {
if (userNumber == generateRandom) {
message("You're absolutely right!");
} else {
if (userNumber > generateRandom) {
message("Think of a lesser number: ");
} else {
message("Think of a greater number: ");
}
userNumber = input.nextInt();
tryAgain(userNumber, generateRandom);
}
}
public static void message(String m) {
System.out.print(m);
}
}
I just completed this exercise. It's pretty interesting to see some different approaches! Here's my take on it:
import java.util.Random;
import java.util.Scanner;
public class GuessGameLevelUp {
/*
* A guessing game where you try to guess a random number between and including 1 and 100.
* This version allows you to continue guessing until you get the right answer.
* When you're off, a hint will let yet know whether your most recent guess was too high or low.
*/
public static void main (String [] args) {
//Generates a random number for the game
Random random = new Random();
int answer = random.nextInt(100) +1;
//Introduces the game and gives a prompt
System.out.println("I'm thinking of a number between and including "
+ "1 and 100, can you guess which?");
System.out.print("Take a guess: ");
//Enables guess value input and parrots guess
Scanner in = new Scanner(System.in);
int guess;
guess = in.nextInt();
System.out.println("Your guess is: "+guess);
//Stacks a new class to determine the outcome of the game
tooHighTooLow(answer, guess);
}
public static void tooHighTooLow(int a, int g) {
//Triggers and parrots guess if correct
if (a==g) {
System.out.print("Correct! The number I was thinking of was: "+g);
//Triggers "Too Low" prompt and uses recursive to offer another attempt
} else if (a>g) {
System.out.print("Too Low! Try again: ");
Scanner in = new Scanner(System.in);
g = in.nextInt();
System.out.println("Your guess is: "+g); //Parrots guess
tooHighTooLow(a, g);
//Triggers "Too High" prompt and uses recursive to offer another attempt
}else
System.out.print("Too high! Try again: ");
Scanner in = new Scanner(System.in);
g = in.nextInt();
System.out.println("Your guess is: "+g); //Parrots guess
tooHighTooLow(a, g);
}
}
I got stuck on this one too, but your code helped me in arriving at a solution. Here's what I came up with:
import java.util.Random;
import java.util.Scanner;
public class Ch5Ex7 {
public static void compareNumbers(int userNumber,int randomNumber) {
if(userNumber == randomNumber) {
System.out.println("You got it!");
} else if ( userNumber > randomNumber ) {
System.out.println("Too high. Guess again: ");
Scanner in = new Scanner(System.in);
userNumber = in.nextInt();
compareNumbers(userNumber, randomNumber);
} else {
System.out.print("Too low. Guess again: ");
Scanner in = new Scanner(System.in);
userNumber = in.nextInt();
compareNumbers(userNumber,randomNumber);
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random random = new Random();
int randomNumber = random.nextInt(100) + 1;
int userNumber;
System.out.print("Type a number: ");
userNumber = in.nextInt();
compareNumbers(userNumber, randomNumber);
}
}
Thanks for pointing me in the right direction!
new here and in java world and I am a student. I just keep getting a wrong product for this question.
Write a Java application that asks the user to input an integer between 1 and 9
inclusive, 10 times, and then prints their product. Your program should use a for loop.
When an integer less than 1 or larger than 9 is input, your application should disregard
it.
You should NOT use logical AND or logical OR operators.
here is what I have done so far:
import java.util.Scanner;
public class newtest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter;
int product = 1;
int number;
System.out.print("Enter number 1-9: ");
number = input.nextInt();
for (counter=1; counter<=10; counter++){
System.out.print("Enter number 1-9: ");
number = input.nextInt();
if (number<10){
if (number>0) product*=number;
else System.out.println ("number is disregarded");
}
else System.out.println ("number is disregarded");
}
product *= number;
System.out.println (product);
}
}
if (number<10){
if (number>0) product*=number;
else System.out.println ("number is disregarded");}
else System.out.println ("number is disregarded");
} product *= number;
System.out.println (product);
Your problem is here, remove the product *= number; that follows the outer if block.