Monday, June 13, 2011

JAVA Programming

JAVA Sample Problem:


A program that takes input from user and computes the sum of each digit of the number. For instance, the user inputs 310, the program will add 3, 1, and 0. Therefore, the sum of the digits of 310 is equal to 4.

PROGRAM:

import javax.swing.*;

public static void main (String arg[]){
int sum, inputVal, rem1, rem2, val1, val2, val3, val4;


inputVal = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter Value:"));
val1 = inputVal/1000;
rem1 = inputVal%1000;

val2 = rem1/100;
rem2 = rem1%100;

val3 = rem2/10;
val4 = rem2%10;

sum = val1 + val2 + val3 + val4;

System.out.println("You entered " + inputVal);
System.out.println("The sum of your input is: " + sum);

}

In this example, division and modulu is used to extract each digit from the number entered by the user. Netbeans IDE was used to program this sample problem. Here are some screenshots of the program: