Showing posts with label scanner class. Show all posts
Showing posts with label scanner class. Show all posts

Saturday, February 2, 2013


Java Programming, Do While, If, Miles To Kilometer , Part 2

Use do while loop to repeat the program, to exit user enters - 1.0 And also if clause

Code below :


// Miles to kilometer example
// In part two we use do while to repeat the program
// and also if and else

// Use scanner class

import java.util.Scanner;

public class MilesKilometer2 {
public static void main(String[] args){

double miles ;

// use constant
final double MILES_TO_KILOMETER = 1.609 ;

//Initialize scanner class
Scanner newscan = new Scanner(System.in);


// To repeat use do while loop

do {

System.out.println("Miles to kilometer program \n Enter -1.0 to terminate ");
System.out.print("Enter miles value : ");

// Read miles value
miles = newscan.nextDouble();

// Print out the value

// if miles not equal to -1 print the kilometer value
if( miles != -1.0 )
{
System.out.println("Kilometer value is : " + (miles * MILES_TO_KILOMETER ) + "\n");
}
// say good bye
else {  System.out.println("Thank you, bye");}

} while(miles != -1.0); // loop will terminate if miles value is -1.0


}
}



Java CONSTANT, How to convert miles to kilometer

Java Programming, Constant

To declare CONSTANT the syntax as stated below,

final datatype CONSTANTNAME = value;

In this example , we declare constant MILES_TO_KILOMETER as stated below

final double MILES_TO_KILOMETER = 1.609 ;

I use scanner class to read the miles value, the full code as stated below.

// Miles to kilometer example

// Use scanner class

import java.util.Scanner;

public class MilesKilometer {
public static void main(String[] args){
double miles ;
// use constant 
final double MILES_TO_KILOMETER = 1.609 ;
//Initialize scanner class
Scanner newscan = new Scanner(System.in);
System.out.print("Enter miles value : ");
// Read miles value
miles = newscan.nextDouble();
// Print out the value
System.out.println(" Kilometer value is : " + ( miles *  MILES_TO_KILOMETER ) + "\n");

}
}

How to read input using Java Scanner Class

This tutorial is how you can read inputs for command prompt. You will be using Scanner class to read the input from keyboard.

You import Scanner class using > import java.util.Scanner ; statement

You create scanner object using the statement ;
Scanner myscan = new Scanner(System.in);

myscan can be any name.

To read integer number , you use the following statement.

x = myscan.nextInt();

The full code the program is stated below;


// How to read input from console

import java.util.Scanner;

public class ScannerInput2 {
public static void main(String[] args){
int x ;
Scanner myscan = new Scanner(System.in);

// Ask input
System.out.print("Enter an integer number :");

// Read from console
x = myscan.nextInt();

//Print out the number
System.out.println("Your integer number is :" + x );


}
}