Input & Selection
This tutorial will show you how to apply an input in Java in which a user has to enter a value to get a return in the console.
AgeCalculation
This example is a quick calculation that works out how old a person is depending on their age. (It works out the age by the year, so it may be a year out depending on when you were born in the year.)
[java]import java.util.*;
public class AgeCalc
{
public static void main ( String args [ ] )
{
final int currentYear = 2011; // intialise current year
int ageInYears = 0 ; // initialise variable
Scanner sc = new Scanner (System.in); // create new scanner
System.out.println("What year were you born in ?");
int yearOfBirth = sc.nextInt(); // accept keyboard input
ageInYears = currentYear - yearOfBirth ; // calculate year of birth
System.out.println( "If were born in " + yearOfBirth + " . ") ;
System.out.print( "That means you are "+ageInYears) ;
System.out.println( " years old. " ) ;
}
}[/java]
Thats pritty simple and you should beable to make quite alot just from this tutorial.
Try to take what you have learnt in the above code and apply it to the following tasks below.
Tasks
Try and amend the code below so that customers who are 14 or under get a ticket for £3.99 instead of £9.99.
[java]import java.util.*;
public class Selection
{
public static void main ( String args [] )
{
double price = 9.99;
Scanner sc = new Scanner(System.in);
System.out.print("Enter your age : ");
int age = sc.nextInt();
// code to reduce p r i c e f o r c h i l d r e n
System.out.println("Ticket price= £" + price + ".");
}
[/java]
Hint: It goes along the lines of "If age is equal to or less than 14, price equals 3.99."
Let me know how you get on.
Dont forget to PM with any questions you might have.
First person to figure out what to do gets 1000 bytes.