Lab Manual - 2: CLO No. Learning Outcomes Assessment Item BT Level PLO

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

UET TAXILA

CLO Learning Outcomes Assessment Item BT Level PLO


No.

1 Construct the experiments / projects of Lab Task, Mid Exam, Final


varying complexities. Exam, Quiz, Assignment, P2 3
Semester Project

2 Use modern tool and languages. Lab Task, Semester Project P2 5

3 Demonstrate an original solution of Lab Assignment, Lab Task,


A2 8
problem under discussion. Semester Project

4 Work individually as well as in teams Lab Task, Semester Project A2 9

Lab Manual - 2
OOP
3rdSemester Lab-02: Input Methods and Command Line arguments in Java

Laboratory 02: Input Methods and Command Line arguments in


Java
Lab Objectives: After this lab, the students should be able to

1. Understand Java Program


2. Take input from user using different methods
3. Use command line arguments in Java

1. Understanding Java Program


Write the following program and check the output.

class First
{
public static void main(String args[])
{
System.out.println("Which one is your favourite programming language?");
System.out.println("java");
}
}

Perform the following Variations in above program:

i. Change the word System in the source program to system and try to compile the altered version.
How does your compiler inform you of this error?

ii. Change the word class in the source program to Class and try to compile the altered version.
How does your compiler inform you of this error?

iii. Change the word public in the source program to Public and try to compile the altered version.
How does your compiler inform you of this error?

iv. Remove the semicolon from the end of the line


System.out.print("Which one is your favourite programming language?");

Try to compile this altered version. How does your compiler respond?

v. Remove the closing brace} at the end of the program. Try to compile this altered version. How
does your compiler respond?

vi. Place a third closing brace} at the end of the program. Try to compile this altered version. How
does your compiler respond?

vii. Change the spelling of main to maine or Main. Compile and execute the program. What run-
time error message did you get?

viii. Remove String args[] array from main method and check the output.

Engr. Sidra Shafi Lab-02 1


3rdSemester Lab-02: Input Methods and Command Line arguments in Java

2. Methods for taking input from user


i. Dialog Boxes
ii. Console input using Scanner class

i. Java: JOptionPane - Simple Dialogs

Here are two useful static methods from javax.swing.JOptionPane that allow you to easily create
dialog boxes for input and output. The Java API documentation has many more JOptionPane
options, but these are sufficient for many uses. In the code below userInput and text are Strings.

Value Method call


userInput = JOptionPane.showInputDialog(component, text);
JOptionPane.showMessageDialog(component, text);

Use null for the component parameter if you don't have a window

The dialog box will be centered over the component given in the first parameter. Typically you would
give the window over which it should be centered. If your program doesn't have a window, you may
simply write null, in which case the dialog box will be centered on the screen.

To use this input dialog we import the library called javax.swing, this library contains classes that deal
with GUI.

Example: 1

This program produces the following Dialog Box.

import javax.swing.*;
public class Dialog {

public static void main(String[] args){


String userInput;
userInput = JOptionPane.showInputDialog("your name: ");
System.out.println("Hello " + userInput + " !");
}
}

Output:

On Console it shows

Engr. Sidra Shafi Lab-02 2


3rdSemester Lab-02: Input Methods and Command Line arguments in Java

Notice that we do not declare any objects and no exceptions to throw. An easy and straight forward
method. The output of the above code is a dialog box like the one shown above. If user clicks OK the
input is read and returned as String, if he clicks Cancel dialog box closes without returning any input
entered.

Example 2:

This program produces the dialog boxes below.

import javax.swing.JOptionPane;

public class input{


public static void main(String [] args)
{
String a;
int b;
int c=80;
a=JOptionPane.showInputDialog("Enter Number");
b=Integer.parseInt(a);
if(b>c)
{
System.out.println(a+ " is greater than 80");
System.exit(0);
}
if(b<c)
{
System.out.println(a+ " is less than 80");
System.exit(0);
}
else
{
//System.out.println(a+ " is equal to 80");
JOptionPane.showMessageDialog(null, a+ " is equal to 80");
System.exit(0);
}

}
}

Output on Console:

Engr. Sidra Shafi Lab-02 3


3rdSemester Lab-02: Input Methods and Command Line arguments in Java

Output on Dialog Box:

Methods for converting Strings to Numbers:

showMessageDialog:
Displays a modal dialog with one button, which is labeled "OK". You can easily specify the message,
icon, and title that the dialog displays. Here are some examples of using showMessageDialog:

Engr. Sidra Shafi Lab-02 4


3rdSemester Lab-02: Input Methods and Command Line arguments in Java

Code:
import javax.swing.JOptionPane;
public class MessageTypes {

public static void main(String[] args) {


JOptionPane.showMessageDialog(null,
"Eggs are not supposed to be green.");
JOptionPane.showMessageDialog(null,
"Eggs are not supposed to be green.",
"warning",
JOptionPane.WARNING_MESSAGE);
JOptionPane.showMessageDialog(null,
"Eggs are not supposed to be green.",
"error",
JOptionPane.ERROR_MESSAGE);
//custom title, no icon
JOptionPane.showMessageDialog(null,
"Eggs are not supposed to be green.",
"A plain message",
JOptionPane.PLAIN_MESSAGE);
}
}

ii. Reading Input from Console: Scanner input


To read input from console we can use the scanner class. Java uses System.out to refer to the standard
output device and System.in to the standard input device. To perform console output, you simply use the
println method to display a primitive value or a string to the console. Console input is not directly
supported in Java, but you can use the Scanner class to create an object to read input from System.in, as
follows:

Engr. Sidra Shafi Lab-02 5


3rdSemester Lab-02: Input Methods and Command Line arguments in Java

Scanner input = new Scanner(System.in);

The syntax new Scanner(System.in) creates an object of the Scanner type. The syntax Scanner input
declares that input is a variable whose type is Scanner. The whole line Scanner input = new
Scanner(System.in) creates a Scanner object and assigns its reference to the variable input. An object
may invoke its methods. To invoke a method on an object is to ask the object to perform a task.

Methods for Scanner Objects

Example

This program demonstrates the use of Scanner Class.

import java.util.Scanner; // Scanner is in the java.util package import class

public class ComputeAreaWithConsoleInput {


public static void main(String[] args) {
// Create a Scanner object
Scanner input = new Scanner(System.in); //create a Scanner

//Prompt the user to enter a radius


System.out.print("Enter a number for radius: ");
double radius =input.nextDouble(); // read a Double

// Compute area
double area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}

Output:

1.

Engr. Sidra Shafi Lab-02 6


3rdSemester Lab-02: Input Methods and Command Line arguments in Java

2.

Example

The following Program gives another example of reading input from the keyboard. The example reads
three numbers and displays their average.
import java.util.Scanner;
public class Avg {

public static void main(String[] args) {


// Create a Scanner object
Scanner input = new Scanner(System.in);

// Prompt the user to enter three numbers


System.out.print("Enter three numbers: ");
double number1 = input.nextDouble();
double number2 = input.nextDouble();
double number3 = input.nextDouble();

// Compute average
double average = (number1 + number2 + number3) / 3;

// Display result
System.out.println("The average of " + number1 + " " + number2
+ " " + number3 + " is " + average);
}
}
}

Output:

iii. Console Input using BufferedReader:

BufferedReader reads input from the character-input stream and buffers characters so as to
provide an efficient reading of all the inputs. The default size is large for buffering. When the
user makes any request to read, the corresponding request goes to the reader and it makes a
read request of the character or byte streams, thus BufferedReader class is wrapped around
another input streams such as FileReader or InputStreamReaders.

To do console input, you create an object of the class BufferedReader using the
following syntax
new BufferedReader(new InputStreamReader(System.in)

Engr. Sidra Shafi Lab-02 7


3rdSemester Lab-02: Input Methods and Command Line arguments in Java

and you assign this object to a variable of type BufferedReader, so that the whole process is
done with
BufferedReader input=new BufferedReader(new InputStreamReader(System.in));

Once you have an object of type BufferedReader created in this way, you can use the method
readLine to read a line of input, as illustrated in the following example:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Buff_Input {


public static void main(String[] args) throws IOException {

BufferedReader input=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter number of pods");


String podString=input.readLine();
int numberOfPods=Integer.parseInt(podString);

System.out.println("Enter number of peas in a pod");


String peaString=input.readLine();
int peasPerPod=Integer.parseInt(peaString);

int totalNumberOfPeas =numberOfPods*peasPerPod;


System.out.println(numberOfPods+ " pods and");
System.out.println(peasPerPod + " peas Per Pod +");
System.out.println("The total number of Pods = " +
totalNumberOfPeas);
//you don not need System.exit(0);
}
}
Output:

BufferedReader has no methods for reading numbers. With BufferedReader you read input as
a value of type String. If you want a value of type int, you must convert the String to an int as
in the following line:

Int numberOfPods= Integer.parseInt(podString);

The object System.in does not have a readLine method. The statement takes System.in as an
argument and uses it as a basis for creating an object of the class BufferedReader, which has
the method readLine();

The three import statements make the three classes we use in the program. They are in package
java.io, you can replace those three import statements with the entire java.io. package.

Engr. Sidra Shafi Lab-02 8


3rdSemester Lab-02: Input Methods and Command Line arguments in Java

Import java.io.*;

Note that when your program doesnot use JOptionPane (or one of the other windowing
interfaces), you do not need

System.exit(0);

The program will automatically end when it runs out of statements to execute.

If you want to input numbers, you must read the number as a string and convert the string to a
number.

When reading keyboard input either with JOptionPane or with BufferedReader and readLine,
the input is always produced as a string value corresponding to a complete line of input. The
class StringTokenizer can be used to decompose this string into words so that you can treat
input as multiple items on a single line.

2. Command Line Arguments:

The java command-line argument is an argument i.e. passed at the time of running the java
program.

The arguments passed from the console can be received in the java program and it can be used
as an input.

So, it provides a convenient way to check the behavior of the program for the different values.
You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.

Below is the example code that displays the command line arguments.

class showArgs
{
public static void main(String abc[])
{
for(int i=0; i<abc.length; i++)
{
System.out.println("Argument " + i + " = " + abc[i]);
}
}
}

Giving command line arguments while running the java code:

You can give any number of arguments after giving the .class file name separated by space. Space is
used as a delimiter to specify the number of command line arguments to the interpreter.

Example:

In order to run the above code mentioned:

We will compile the code using


Engr. Sidra Shafi Lab-02 9
3rdSemester Lab-02: Input Methods and Command Line arguments in Java

Javac showArgs.java

Run the .class file as:

Java showArgs

Output: code will execute without any output, as no command line arguments are passed in it.

To pass the command line arguments, we will re-run the code as follows:

Java showArgs hello world

Argument 0=hello

Argument 1=world

Java showArgs “hello world” “my first program”

Argument 0=hello world

Argument 1=my first program

By default Arguments are passed as a String array to the main method of a class.

Try to run the following code 3 times. Firstly by giving two arguments as input during run time.
Secondly by giving three arguments and for the last time by giving four number of arguments
and compare the outputs.

class showArgs
{
public static void main(String args[])
{
for(int i=0; i<3; i++)
{
System.out.println("Argument " + i + " = " + args[i]);
}
}

Setting command line arguments in Eclipse

Right click on class in Project -> Run As -> Run Configurations.

The following window opens. Give arguments separated by space as shown below.

Then select Run.

Engr. Sidra Shafi Lab-02 10


3rdSemester Lab-02: Input Methods and Command Line arguments in Java

Output on Console:

Run the following program and check the output by entering user name and password. Display
the user name and password entered by the user.
class user
{
public static void main(String abc[])
{
System.out.println("user name:" +" " +abc[0]);
System.out.println("password:" +" " +abc[1]);
}
}

LAB TASKS
Task 1: Marks: 5

Take miles and gallons of fuel from the user as inputs using Scanner class and calculate
fuel efficiency based on values entered by the user using the formula mpg = miles /gallons.

Engr. Sidra Shafi Lab-02 11


3rdSemester Lab-02: Input Methods and Command Line arguments in Java

Task 2: Marks: 5

Take quality points and credits as inputs using JOptionPane class and calculates GPA
using formula qp / credits.

Example:

Here's an example student's transcript with credit hours, grade earned, and grade points:

***************

Engr. Sidra Shafi Lab-02 12

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy