Download Lab Module JAVA 2

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Universiti Malaysia Perlis
EKT420: SOFTWRE ENGINEERING
Lab 2: Introduction to JAVA Programming
Pusat Pengajian Kejuruteraan Komputer Dan Perhubungan
Universiti Malaysia Perlis
1
INTRODUCTION TO JAVA
My Fist Program
/*My first JAVA program
*hello.java
*/
public class hello
{
public static void main(String args[])
{
System.out.println("Hello World!");
System.out.print("I am a ");
System.out.print("UniMAP’s student.");
}
}
Output:
Hello World!
I am a UniMAP’s student.
Declaring variables and using Math functions
/*
* MathsComputation.java
*
*
*/
public class MathsComputation {
/* This program performs some mathematical computations and
displays
the results. It then reports the number of seconds that the
computer spent on this task.
*/
public static void main(String[] args) {
long startTime; // Starting time of program, in milliseconds.
long endTime; // Time when computations are done, in
// milliseconds.
double time; // Time difference, in seconds.
startTime = System.currentTimeMillis();
double width, height, hypotenuse; // sides of a triangle
width = 42.0;
2
height = 17.0;
hypotenuse = Math.sqrt( width*width + height*height );
System.out.print("A triangle with sides 42 and 17 has hypotenuse ");
System.out.println(hypotenuse);
System.out.print("\nHere is a random number: ");
System.out.println( Math.random() );
endTime = System.currentTimeMillis();
time = (endTime - startTime) / 1000.0;
System.out.print("\nRun time in seconds was: ");
System.out.println(time);
} // end main()
} // end class
Output:
A triangle with sides 42 and 17 has hypotenuse 45.31004303683677
Here is a random number: 0.33951324221369317
Run time in seconds was: 0.06
3
java.util.Scanner
The Scanner
A Scanner object can parse user input entered on the console or from a file. A Scanner
breaks its input into separate tokens (which are typically separated by white space),
and then returns them one at a time. The scanner provides methods to convert the
tokens into values of different types. For example, this code reads two numbers from
the console and prints their sum:
Scanner in = new Scanner(System.in);
int i = in.nextInt();
int j = in.nextInt();
System.out.println(i+j);
The scanner also provides methods to test whether there is any input left, and if there is,
what type of token appears next. This functionality is provided through methods like
hasNextInt, hasNextDouble. For example, the following code reads integers and adds
them up until there is no more input or a non numeric token is encountered:
Scanner in = new Scanner(System.in);
int sum = 0;
while (in.hasNextInt()) {
sum += in.nextInt();
}
Creating Scanners
Whenever using scanners, be sure to include the proper import line:
import java.util.Scanner;
We will create scanners in two ways:
1.
To read from the console, use the following:
2.
To read from a file, use the following:
Scanner input = new Scanner(System.in);
Scanner input = new Scanner(new FileStream("filename.txt"));
4
Scanner Methods
Method
nextBoolean() nextInt()
nextLong() nextDouble()
nextString() or next() nextLine()
hasNextBoolean() hasNextInt()
hasNextLong() hasNextDouble()
hasNextString() or hasNext()
hasNextLine()
Computes
reads and converts next token to a boolean value
reads and converts next token to a integer value reads
and converts next token to a long value reads and
converts next token to a double value reads next
token and returns it as a String reads until the next
new line and returns a String
returns true iff the next token is either “true” or
“false” returns true iff the next token is an integer
returns true iff the next token is a long returns true iff
the next token is a real number returns true iff there
is at least one more token of input returns true iff
there is another line of input
Inputting integer and string with Scanner
import java.util.Scanner;
public class readData {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int number1;
System.out.println("Enter name:"); //input strings
String name = input.nextLine(); //use nextLine()
System.out.println("Enter first integer:"); //input integer
number1 = input.nextInt(); //use nextInt()
System.out.println("The name is:" +name);
System.out.println("The integer is :"+ number1);
} }
Output:
Enter name : Ali Abu
Enter first integer : 20
The name is Ali Abu
The integer is 20
5
Inputting character with Scanner
import java.util.Scanner;
public class readData {
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
System.out.println("Enter a character:"); //input character
char c = input.charAt(0); //use charAt(0)
System.out.println("The character is :"+ c);
}
}
Output:
Enter a character: a
The character is a
Inputting double with Scanner
import java.util.Scanner;
public class readData {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double number1;
System.out.println("Enter a double number:"); //input double
number1 = input.nextDouble(); //use nextDouble()
System.out.println("The double is :"+ number1);
}
}
Output:
Enter a double number : 23.89
The double is 23.89
6
Input a number then prints it’s square
import java.util.Scanner;
public class PrintSquare {
public static void main(String[] args) {
// A program that computes and prints the square
// of a number input by the user.
Scanner input = new Scanner(System.in);
int userInput; // the number input by the user
int square;
// the userInput, multiplied by itself
System.out.println("Please type a number: ");
userInput = input.nextInt();
square = userInput * userInput;
System.out.print("The square of that number is ");
System.out.println(square);
} // end of main()
} //end of class PrintSquare
Output:
Please type a number:
100
The square of that number is 10000
7
EXERCISE 1
Design a program that reads an input temperature in degrees Fahrenheit, converts it to an
absolute output temperature in Kelvin, and writes out the result. The relationship is :
T (in kelvin) = [(5/9) T(in Fahrenheit) – 32.0] + 273.15
Below is the design of the algorithm and write the program:
Prompt the user to enter an input temperature in Fahrenheit
Read the input temperature (tempF)
Calculate the temperature in kelvin
tempK (5. / 9.) * (tempF - 32.) + 273.15
Write out the result
Example output:Enter the temperature in degrees Fahrenheit :
100
100.0 degrees Fahrenheit = 310.92777777777775 Kelvin
EXERCISE 2
Write a program to calculate number of cents into number of RM. 1000 cents
equals to RM10, 500 cents equals to RM5 and 100 cents equals to RM1.
Example output:
Enter the number of cents : 1600
1600 cents equals to
1 RM 10
1 RM 5
1 RM 1
8
Introduction to swing
Swing library is an official Java GUI toolkit released by Sun Microsystems.
The main characteristics of the Swing toolkit
•
•
•
•
•
platform independent
customizable
extensible
configurable
lightweight
Swing consists of the following packages
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
javax.swing
javax.swing.border
javax.swing.colorchooser
javax.swing.event
javax.swing.filechooser
javax.swing.plaf
javax.swing.plaf.basic
javax.swing.plaf.metal
javax.swing.plaf.multi
javax.swing.plaf.synth
javax.swing.table
javax.swing.text
javax.swing.text.html
javax.swing.text.html.parser
javax.swing.text.rtf
javax.swing.tree
javax.swing.undo
Java Swing dialogs
Dialog windows or dialogs are an indispensable part of most modern GUI applications. A
dialog is defined as a conversation between two or more persons. In a computer
application a dialog is a window which is used to "talk" to the application. A dialog is
used to input data, modify data, change the application settings etc. Dialogs are important
means of communication between a user and a computer program.
In Java Swing toolkit, we can create two kinds of dialogs. Custom dialogs and standard
dialogs. Custom dialogs are dialogs, created by the programmer. They are based on the
JDialog class. Standard dialogs preedefined dialogs available in the Swing toolkit.
These are dialogs for common programming tasks like showing text, receiving input ,
loading and saving files etc. They save programmer's time and enhance using some
standard behaviour.
9
/*
* Welcome.java
*
*
*/
import javax.swing.*;
public class Welcome {
public static void main(String args[])
{
JOptionPane.showMessageDialog(null,"Welcome\nto\nUniMAP!");
System.exit(0); //terminate application with window
}
}
Output:
10
import javax.swing.*;
public class Addition {
public static void main(String args[])
{
String firstNum;
//first string enter by user
String secondNum; //second string enter by user
int num1;
int num2;
int sum;
//fisrt number to add
//second number to add
//sum of num1 and num2
//read in first num from user as String
firstNum = JOptionPane.showInputDialog("Enter first number:");
//read in second number from user as String
secondNum = JOptionPane.showInputDialog("Enter second number:");
//Convert numbers from type String to type int
num1 = Integer.parseInt(firstNum);
num2 = Integer.parseInt(secondNum);
//add numbers
sum = num1 + num2;
//Display result
JOptionPane.showMessageDialog(null,"The sum is " + sum,
"Results", JOptionPane.PLAIN_MESSAGE);
System.exit(0);
}
}
Output:
11
if else statement
/**
* Using if statement
*
*/
import javax.swing.*;
public class ifelse {
public static void main(String[] args) {
String pass;
String pass2="12345";
int passwd;
int passwd2;
pass = JOptionPane.showInputDialog("Enter Password:");
passwd = Integer.parseInt(pass);
passwd2 = Integer.parseInt(pass2);
if(passwd == passwd2)
JOptionPane.showMessageDialog(null,"Login Successfull");
If(passwd != passwd2)
JOptionPane.showMessageDialog(null, "Wrong Password");
System.exit(0);
}
}
Output:
12
/**
* Using if..else statement
*/
import javax.swing.*;
public class classification {
public static void main(String[] args) {
String s1, inMessage, outMessage;
int classCode;
inMessage
+
+
+
+
+
= "Enter your classification code:\n"
" 1. A-Level\n"
" 2. Matriculation\n"
" 3. STPM\n"
" 4. Diploma\n"
" 5. Bachelor\n";
//To put inMessage in a dialog box
s1 = JOptionPane.showInputDialog(inMessage);
//To input a string s1 and convert to Integer
classCode = Integer.parseInt(s1);
if (classCode == 1)
outMessage = "You are an A-Level student.";
else if (classCode == 2)
outMessage = "You are a Matriculation student.";
else if (classCode == 3)
outMessage = "You are a STPM student.";
else if (classCode == 4)
outMessage = "You are diploma student.";
else if (classCode == 5)
outMessage = "You are a bachelor student.";
else
outMessage = "You're not in the list";
JOptionPane.showMessageDialog(null,outMessage,
"The answer is.....",
JOptionPane.WARNING_MESSAGE);
System.exit(0);
}
}
Output:
13
switch statement
import javax.swing.*;
public class switchDemo {
public static void main(String[] args) {
char alphabet;
String myString;
do{
myString = JOptionPane.showInputDialog("Enter an alphabet:");
alphabet = myString.charAt(0);
switch(alphabet)
{
case 'a': case 'A':
case 'e': case 'E':
case 'i': case 'I':
case 'o': case 'O':
case 'u': case 'U':
JOptionPane.showMessageDialog(null,"The alphabet is a
vowel");
break;
default: JOptionPane.showMessageDialog(null,"The alphabet is a
consonant");
break;
}
}while(alphabet != '#');
}
}
Output:
14
import javax.swing.*;
public class switchDemo2 {
public static void main(String[] args) {
int month;
String myString;
do{
myString = JOptionPane.showInputDialog("Enter number:");
month = Integer.parseInt(myString);
switch(month)
{
case 1: JOptionPane.showMessageDialog(null,"January");
break;
case 2: JOptionPane.showMessageDialog(null,"February");
break;
case 3: JOptionPane.showMessageDialog(null,"March");
break;
case 4: JOptionPane.showMessageDialog(null,"April");
break;
case
5: JOptionPane.showMessageDialog(null,"May");
break;
case
6: break;
default: JOptionPane.showMessageDialog(null,"Invalid Month");
break;
}
}while(month < 6 );
}
}
Output:
./
15
for loop
The for loop is a looping construct which can execute a set of instructions a
specified number of times. It’s a counter controlled loop.
The syntax of the loop is as follows:
•
•
for(<initialization>;
<loop condition>; <increment expression>)
<loop body>
The first part of a for statement is a starting initialization, which executes once
before the loop begins.
The second part of a for statement is a test expression. As long as the expression
is true, the loop will continue. If this expression is evaluated as false the first
time, the loop will never be executed.
The third part of the for statement is the body of the loop. These are the
instructions that are repeated each time the program executes the loop.
The final part of the for statement is an increment expression that automatically
executes after each repetition of the loop body. Typically, this statement changes
the value of the counter, which is then tested to see if the loop should continue.
•
•
•
•
public class ForLoopDemo {
public static void main(String[] args) {
System.out.println("Printing Numbers from 1 to 10");
for(int count =1; count <=10; count++){
System.out.println(count);
}
}
}
Output:
Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
10
16
public class forDemo {
public forDemo() {
}
public static void main(String[] args) {
int sum=0;
for(int x = -10; x <= 0; x++)
{
System.out.println(x);
sum = sum + x;
}
System.out.println("The sum of x is "+ sum);
}
Output:
-10
-9
-8
-7
-6
-5
-4
-3
-2
-1
0
The sum of x is -55
Nested for loop
public class pyramid {
public static void main(String[] args) {
int i, j;
for( i = 1; i <= 5; i++) //number of rows printed
{
for(j = 1; j <= 5-i; j++)
System.out.print(" "); //side space
for(j = 1; j <= 2*i - 1; j++)
System.out.print("*"); //number of * printed
System.out.print("\n");
}
}
}
Output:
17
*
***
*****
*******
*********
while loop
The while statement is a looping construct control statement that executes a block
of code while a condition is true.
You can either have a single statement or a block of code within the while loop.
The loop will never be executed if the testing expression evaluates to false.
The loop condition must be a boolean expression.
The syntax of the while loop is
•
•
•
•
•
while (<loop condition>)
<statements>
public class WhileLoopDemo {
public static void main(String[] args) {
int count = 1;
System.out.println("Printing Numbers from 1 to 10");
while( count <= 10){
System.out.println(count++);
}
}
}
Output:
Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
10
18
do..while loop
The do-while loop is similar to the while loop, except that the test is performed at
the end of the loop instead of at the beginning.
This ensures that the loop will be executed at least once.
A do-while loop begins with the keyword do, followed by the statements that
make up the body of the loop.
Finally, the keyword while and the test expression completes the do-while loop.
When the loop condition becomes false, the loop is terminated and execution
continues with the statement immediately following the loop.
You can either have a single statement or a block of code within the do-while
loop.
The syntax of the do-while loop is
•
•
•
•
•
•
do
<loop body>
while (<loop condition>);
public class DoWhileLoopDemo {
public static void main(String[] args) {
int count = 1;
System.out.println("Printing Numbers from 1 to 10");
do{
System.out.println(count++);
}while( count <= 10);
}
}
Output:
Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
10
19
break
•
•
•
The break statement transfers control out of the enclosing loop ( for, while, do or
switch statement).
You use a break statement when you want to jump immediately to the statement
following the enclosing control structure.
The Syntax for break statement is as shown below;
break;
public class BreakExample {
public static void main(String[] args) {
System.out.println("Numbers 1 - 10");
for (int i = 1; ; ++i) {
if (i == 11) //stop at 10
break;
System.out.println(i);
}
}
}
Output:
Numbers 1 - 10
1
2
3
4
5
6
7
8
9
10
20
continue
•
•
•
A continue statement stops the iteration of a loop (while, do or for) and causes
execution to resume at the top of the nearest enclosing loop.
You use a continue statement when you do not want to execute the remaining
statements in the loop, but you do not want to exit the loop itself.
The syntax of the continue statement is
continue;
public class ContinueExample {
public static void main(String[] args) {
System.out.println("Odd Numbers");
for (int i = 1; i <= 10; ++i) {
if (i % 2 == 0) continue;
// Rest of loop body skipped when i is even
System.out.println(i + "\t");
}
}
}
Output:
Odd Numbers
1
3
5
7
9
21
Exercise 1(if else)
Write a program that can determine whether a number is even or odd. Hint: Use the %
(Modulus/Remainder) operator. If Number % 2 == 0, it’s an even number, else it’s an
odd number.
Example output:
Input a number : 4
4 is an even number
Exercise 2(switch)
Write a simple calculator program where you can input 2 operands and 1 operator
(+,-,*,/) and then gets its result.
Example output:Please input first number: 10
Please input the operator : +
Please input second number : 20
The answer is 30
Exercise 3(for loop)
Write a program that calculates the squares and cubes of the numbers from 0 to 10
and uses tabs to print the following table of values.
Number
0
1
2
3
4
5
6
7
8
9
10
Square
0
1
4
9
16
25
36
49
64
81
100
Cube
0
1
8
27
64
125
216
343
512
729
1000
22
Exercise 4(swing)
Write a JAVA program for exponential raised to power of the user entered value
n(the value of Math.expn(n)). This is the base of natural algorithms ‘e’ raised to the
power n. User only allowed to enter any integer number between -1 and 20,
Sample output:
23
Exercise 5(swing)
Write a program that can produce the following output as below. Use if or switch
statements to do your selection and loop to repeat the selection. The formula for
converting Celsius to Fahrenheit is Celsius * 9/5 + 32. The formula for
calculating BMI is weight (kg)/height (meter) * height (meter).
24
25