combining several if statement for one input in java - java

im begginer in java , could anyone tell me how to combine several if in one input.
I mean something like this "
how old are you?"
when user answer this it works with several if forexample my code is :
public static void main(String[] args) {
int age = 40;
Scanner ageField = new Scanner (System.in);
System.out.print("How old are you? ");
if(ageField.nextDouble() > age ){
System.out.print("you are over than 40 years old");
}else if(ageField.nextDouble() < age ){
System.out.print("you are less than 40");
}else if(ageField.nextDouble() < 20 ){
System.out.print("you are less than 20");
}else {
System.out.print("enter your age");
}
}
}
i mean the answer should based on the given value,hope you get what im saying

Your code is not working because you are discarding the user input ate checking the 1st conditional if...
Store the user input (which BTW should be an integer instead of a double)
ageField.nextInt()
In a variable and use that in the if else conditions... no need to call get Double several times

Here's actually one of possible optimization OP has asked for. One if statement that can be reused as much as needed. The program will ask for input for the number of your items in ages list:
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
public class Main
{
public static void main(String[] args) throws IOException
{
List<Integer> ages = Arrays.asList("20", "40").stream().map(Integer::valueOf).collect(Collectors.toList());
try (Scanner ageField = new Scanner(System.in))
{
System.out.print("How old are you? ");
ages.forEach(e -> analyzeAge(ageField.nextInt(), e));
}
}
private static void analyzeAge(int ageInput, int ageCompared)
{
String answer = null;
if (ageInput > ageCompared)
{
answer = "You are older than " + ageCompared;
}
else if (ageInput < ageCompared)
{
answer = "You are younger than " + ageCompared;
}
else
{
answer = "You are exactly " + ageCompared + " years old";
}
System.out.println(answer);
}
}

Your code will not work because you are calling nextDouble() several times. Instead, store the age variable in an int and perform your if statements against this age variable.
Scanner sc = new Scanner (System.in);
System.out.print("How old are you? ");
int age = sc.nextInt();
if(age > 40){
System.out.print("You are more than 40");
}else if(age < 40 && age >= 30){
System.out.print("You are less than 40");
} else if(age < 30) {
System.out.print("You are less than 30");
}
....

Related

how do i implement user input in loop in the following code?

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

How can I make this code stop after the first input

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

How to apply operations on scanner inputs in java?

I have the following code:
import java.util.Scanner;
public class Calculator{
public static void main(String[]args){
Scanner keyboard = new Scanner(System.in);
boolean go = true;
System.out.println("PLEASE ENTER YOUR GRADES");
double grade = keyboard.nextDouble();
while (go){
String next = keyboard.next();
if (next.equals("done") || next.equals("calculate")){
System.out.print(grade);
go = false;
}else{
grade+=keyboard.nextInt();
}
}
I am trying to find the average as it is a grade calculator, what i want to know is how would I apply The addition operation only to scanner inputs, and then ultimately find the average by how mnay inputs were entered.
Sample input:
60
85
72
done
Output:
72 (average) ===> (217/3)
You need a counter (e.g. count as shown below). Also, you need to first check the input if it is done or calculate. If yes, exit the program, otherwise parse the input to int and add it to the existing sum (grade).
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
boolean go = true;
System.out.println("PLEASE ENTER YOUR GRADES");
double grade = 0;
int count = 0;
while (go) {
String next = keyboard.nextLine();
if (next.equals("done") || next.equals("calculate")) {
go = false;
} else {
grade += Integer.parseInt(next);
count++;
}
}
System.out.println((int) (grade / count) + " (average) ===> (" + (int) grade + "/" + count + ")");
}
}

Guess My number exercice 5-7 in think Java

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!

Having trouble adding a for loop to program

I'm having trouble adding a for loop into my older program. I have to make it so at the end the user has an option to ask the question again. This is what I have so far
Also just started learning for loops sorry if the question is stupid
http://gyazo.com/a71e2a0b06ed41c47d62ccc05d8ffec8
Your question isn't stupid, I think you just have the wrong idea here.
Anyways, here's your code, editable, and copyable
import java.util.Scanner;
public class DogYears
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter your dog's age in human years: ");
int age = scan.nextInt();
int dogAge = age * 7;
System.out.println("Your dog is " + age + " in human years and " + dogAge
+ " in dog years!");
// scan.close(); <--- don't close it, you want to be able to do it again, right??
if(dogAge>=150)
{
System.out.println("Likely story");
}
else if(dogAge>=80 && dogAge<150)
{
System.out.println("Hello grand-dog");
}
else if(dogAge>=40 && dogAge<80)
{
System.out.println("Boring!");
}
else if(dogAge>=20 && dogAge<40)
{
System.out.println("Get a job!");
}
else if(dogAge<20)
{
System.out.println("Just a pup!");
}
}
}
/*
this is the code you had trouble including
for(int age = scan.nextInt(); int dogAge = age * 7; i++);
{
System.out.print("Enter your dog's age in human years: ");
}
*/
Anyways, so that's your code. All you ever need to do is copy paste, and then highlight all the code, then press the 2 brackets symbols in the little box above the text field.
Now, as to your actual question, a simple way to make all this possible would be, throw that for loop around everything that you want the program to repeat (and a method I added in to ensure it's numeric), here is what I mean.
import java.util.Scanner;
public class DogYears
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter your dog's age in human years. ");
int age = scan.nextInt();
for(int i = 0; i < 10000; i++)
{
int dogAge = age * 7;
System.out.println("Your dog is " + age + " in human years and " + dogAge
+ " in dog years!");
// scan.close(); <--- don't close it, you want to be able to do it again, right??
if(dogAge>=150)
{
System.out.println("Likely story");
}
else if(dogAge>=80 && dogAge<150)
{
System.out.println("Hello grand-dog");
}
else if(dogAge>=40 && dogAge<80)
{
System.out.println("Boring!");
}
else if(dogAge>=20 && dogAge<40)
{
System.out.println("Get a job!");
}
else if(dogAge<20)
{
System.out.println("Just a pup!");
}
System.out.print("Enter your dog's age in human years. (Enter a negative number to stop the program)\n");
String response = scan.next();
age = Integer.parseInt(response);
if(age < 0)
{
i = 10001;
}
}
}
}

Categories