user2208501
user2208501

Reputation: 15

Java: Can i use a boolean with a input in java

am new to learning java and I have set myself a task of creating a shopping basket.

Here is my code:

System.out.println("Grapes " + "£" + grapes + "    Quantity:");
    input= amount.nextLine();
    System.out.println("You Selected " + input + " Grapes");

How can i add a boolean so when someone says they want to order 1 bunch of grapes it comes up with "Bunch of Grapes", and when someone orders 2+ bunches of grapes it comes up with "Bunches of grapes" .

Thank you for you help,

Peter

Upvotes: 0

Views: 86

Answers (2)

RiaD
RiaD

Reputation: 47658

int num = Integer.parseInt(input);
if(num == 1){
    // do whatever you want
}
else {
    // another action
}

Actually, you can even compare string representation without parsing

if(input.equals("1"))

but I guess you will need integer representation anyway

Upvotes: 1

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 71009

You would do something like:

boolean multiple_grapes = (Integer.valueOf(input) > 1);
if (multiple_grapes) {
  System.out.println("You Selected " + input + " Bunches of Grapes");
} else {
  System.out.println("You Selected " + input + " Bunch of Grapes");
}

You need to parse input to Integer in order to be able to compare it with the integer value 1.

Upvotes: 1

Related Questions