Showing posts with label while loop. Show all posts
Showing posts with label while loop. 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 Programming :How to add ten numbers using while loop and arrays.
Java Programming :How to add ten numbers using while loop and arrays.
Step 1:
declare and initialize 3 variables. integer i as counter and integer sum.
Step 2:
declare and initialize array integer type, size of the array is ten.
Step 3: while loop to generate the numbers and add the numbers.
Step 4:
Print out the result.
Full code below :
// How to add 10 numbers using while
public class AddTenNumbers{
public static void main(String[] args){
int i = 0 ; // as counter
int sum = 0 ; // sum up the total
int number[] = new int[10]; // use array to generate ten numbers
// use while to generate the numbers and sum up the numbers
while( i < 10){
// Generate the 10 numbers
number[i] = i + 1 ;
// SUm the numbers
sum = sum + number[i];
i++; // forget this
}
// Print the sum
System.out.println("SUmmation of 1 till 10 is : " + sum);
}
}
Step 1:
declare and initialize 3 variables. integer i as counter and integer sum.
Step 2:
declare and initialize array integer type, size of the array is ten.
Step 3: while loop to generate the numbers and add the numbers.
Step 4:
Print out the result.
Full code below :
// How to add 10 numbers using while
public class AddTenNumbers{
public static void main(String[] args){
int i = 0 ; // as counter
int sum = 0 ; // sum up the total
int number[] = new int[10]; // use array to generate ten numbers
// use while to generate the numbers and sum up the numbers
while( i < 10){
// Generate the 10 numbers
number[i] = i + 1 ;
// SUm the numbers
sum = sum + number[i];
i++; // forget this
}
// Print the sum
System.out.println("SUmmation of 1 till 10 is : " + sum);
}
}
Subscribe to:
Posts (Atom)