Showing posts with label java tips. Show all posts
Showing posts with label java tips. Show all posts

Tuesday, February 12, 2013

Tutorial 12 : Fahrenheit To Celsius Example JOption Input

Fahrenheit To Celsius Example.

Step 1 : I use JOptionPane.showInputDialog to get the fahrenheit reading

Step 2 : calculate celsius using the following calculate

double celsius = (5.0/9)*(fahrenheit- 32);

Step 3 : Show the result using JOptionPane.showMessageDialog

Code below :


// Celsius to Fahrenheit Converter Example


import javax.swing.JOptionPane;


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

String number = JOptionPane.showInputDialog(null, "Enter fahrenheit value : " , "Fahrenheit to Celsius Converter", JOptionPane.QUESTION_MESSAGE);

//convert string to number
double fahrenheit = Double.parseDouble(number);

double celsius = (5.0/9)*(fahrenheit- 32);


JOptionPane.showMessageDialog(null, "Fahrenheit value is " + fahrenheit + "\n" + "Celcius value is " + celsius ,
"Fahrenheit to Celsius", JOptionPane.INFORMATION_MESSAGE);

}

}

Monday, February 11, 2013

Tutorial 10 : If and Else, How to determine the number is even or odd

Java Tutorial For Beginners, Tutorial 9 : If and Else, How to determine the number is even or odd?

Program uses if and else condition. If the number when divided by 2, the remainder is 0 then is an even number. Else the number is an odd number.

Step 1 : Read the number. Use Scanner class to read the input.

Step 2 : Use if and else condition. If number % 2 == 0, then the number is an even number. Else it is an odd number.

Step 3 : Print out the statement.

Code below :


//Program to determine whether a number is even or odd
// Use if else condition
// It is even if the number remainder is 0 when divided by 2
// If the remainder is 1, then the number is odd

//use scanner class for read input

import java.util.Scanner;

public class TestIfTwo{
public static void main(String[] args){
int number = 0;

Scanner myscan = new Scanner(System.in);

//Read input
System.out.print("Enter a number : ");
number = myscan.nextInt();

//if and else condition
if (number % 2 == 0) {System.out.println(number + " is even");}
else {System.out.println(number + " is odd");}

}

}

Sunday, February 3, 2013

Java, Nested For Loops, To Generate Patterns

Java, Nested For Loops, To generate.

I use to for loops to generate the following output :


1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Step 1 ; Use for to generate the five rows,

Step 2 ; For each row, generate the numbers.

The code as stated below :


//Java Nested Loops

/* Program to generate the following output

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

*/

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

// I use two nested for loop to generate the pattern
// to generate 5 rows
for(int i = 1; i <= 5 ; i++){

//to generate the numbers
for(int j = 1 ; j <= i ; j++){
System.out.print(j + " ");
}

System.out.println(" ");
}

}
}