AST10106辅导、讲解Java程序、Java编程语言辅导、辅导Java设计

- 首页 >> Java编程

AST10106 Introduction to Programming

Lab 03

Basic Java Input / Output and Arithmetic Operations

Submission Details

In this lab, you are to write THREE Java programs to solve the given problems in the Lab Exercises

section. After your coding completes, submit three source files named Shapes.java, Face.java and

Cylinder.java to the assignment page of Canvas. The deadline is TWO weeks after your lab session

is conducted. Please verify your solution to ensure that everything is correct before submission.

Note: You are required to write down your name, student id, and lab section id in a comment block at

the beginning of your source file.

Objectives

The objectives of this lab are (1) to reinforce your programming concepts (e.g. variable declarations)

taught in the last lecture; (2) to introduce how to get user input from the keyboard; (3) to show you how

to display information on screen; (4) to demonstrate some basic arithmetic operations.

Software Required

1. Java Development Kit, e.g. Java SE 8

2. An Integrated Development Environment, e.g. Eclipse

Please start your lab PC with Windows 10 and refer to the previous lab exercise for the installation and

operation guide of Eclipse.

Introduction

In this lab, you will practice how to:

1. Obtain input values from the user with the aid of the Scanner class and store them in variables.

2. Display output to the user using the print and println methods of the System.out object.

3. Perform simple arithmetic operations on numeric variables.

Background

1. Display information to the user (console):

Java provides the following two methods to display information on the monitor’s screen. (Note:

there is indeed one more method called printf, which was added since JDK 1.5 to resemble Cstyle

output, but we only focus on the following two now).

i. System.out.print()

ii. System.out.println()

For your information,

? System is a class under the java.lang package. By default, all this package is implicitly

imported for every Java program by the Java compiler. So, you can use this class readily.

? out is a static field (also known as class variable) of the System class. Its data type is a

standard library class called PrintStream. Currently, you can ignore the meaning of static,

but try to remember that there is only a single copy of out that is associated with the class

(System) rather than with many instances of the class.

AST10106 Introduction to Programming

2

? Finally, print() and println() are methods associated with the PrintStream object

whose name is out. By using the <object name>.<method name> notation, we say we

are calling a method of the object, e.g. out.println(). But since out is a static field of the

class System, it should be referenced as System.out. So, to call the method, we need to

write System.out.println(). Note that there are several versions of println (or print)

provided by the PrintStream class, which accept different types (boolean, char, int, long,

float, double, String, etc.) of input parameters, e.g. we can call

o System.out.println("Hello!") to print a text string;

o System.out.println(100) to print an integer value.

The Java compiler will detect which println method should be used based on the data type

of the input parameter value.

To use these operations, you can follow the syntax below

Syntax:

// Print data on screen, the cursor will stay at the end of the string printed

System.out.print(<data> [+ <data>]);

// Print data on screen and move the cursor to the next line's beginning

System.out.println(<data> [+ <data>]);

// Print nothing

System.out.print("");

// Print nothing, but move the cursor to the beginning of the next line

System.out.println("");

Example:

public class DataOutputDemo

{

public static void main(String[] args)

{

byte val1 = 10;

short val2 = 412;

int val3 = 58123;

long val4 = 313123152;

float val5 = 1.2345f;

double val6 = 2.331256451313;

char val7 = 'A';

boolean val8 = true;

System.out.println("val1 = " + val1 + ",\t val2 = " + val2);

System.out.println("val3 = " + val3 + ",\t val4 = " + val4);

System.out.println("val5 = " + val5 + ",\t val6 = " + val6);

System.out.println();

System.out.print("Character in val7 is " + val7 + ".\n");

System.out.println("Boolean value in val8 is " + val8 + ".");

System.out.println();

System.out.print("This line ... ");

System.out.println("continues to display ...");

}

}

\t means the tab character

(useful for text alignment)

\n means “new line” character;

print("\n") has same effect as println().

AST10106 Introduction to Programming

3

More to Learn:

This example code aims to show you the relation between char primitive type and ASCII code.

ASCII stands for American Standard Code for Information Interchange. Computers can only

understand numbers, so an ASCII code is the numerical representation of a character such as 'a' or

'@' or some control characters like tab and line feed. You can see an ASCII code table via this link:

http://www.asciitable.com.

Let’s guess the output of each of the above println() operations. Check your guesses against the

answers given by the execution of this program.

Note that char’s are stored as 2-byte unsigned Unicode values in Java; they are just some numbers,

so you can increment or decrement them.

Concept of Casting: The operation represented by a data type within a pair of parentheses, e.g.

(char), that comes before a literal or a variable or an expression is known as casting, which

means data type conversion. For example,

char c = (char) n;

means casting integer n to a character, and assign the result to the char variable c.

char b3 = (char)(a2 + 1);

means casting the result of the expression (a2 + 1) to a character, and assign it to the char variable

b3. Note that the expression results in an integer value that needs casting to char before assignment.

System.out.println("ASCII code of 'C' is " + (int) c + ".");

For this statement, the casting operation (int) converts variable c of char type to an integer value,

which just equals the ASCII code of the character 'C'; the integer is further implicitly converted to

a String value, concatenated with the double-quoted strings before printing to the output stream.

public class AsciiCodeDemo

{

public static void main(String[] args)

{

char a1 = 'A';

char a2 = 65; // ASCII code of 'A'

char b1 = 'A' + 1;

char b2 = (char)(a1 + 1);

char b3 = (char)(a2 + 1);

int n = 67; // ASCII code of 'C'

char c = (char) n;

System.out.println("Character in a1 is " + a1 + ".");

System.out.println("Character in a2 is " + a2 + " too.");

System.out.println("Character in b1 is " + b1 + ".");

System.out.println("Character in b2 is " + b2 + " too.");

System.out.println("Character in b3 is " + b3 + " too.");

System.out.println("Character in c is " + c + ".");

System.out.println("ASCII code of 'C' is " + (int) c + ".");

}

}

AST10106 Introduction to Programming

4

2. Obtain input from the user and store them in variables:

The Java standard library provides a class named Scanner to ease getting user input from various

input devices, e.g. keyboard. The Scanner class is part of the package java.util. A package in

Java is a named collection of classes. You can think of “java.util” this way: “java” is the name of

a root folder which contains a subfolder called “util”, and there are many class files under it. In

this example, java.util is a package containing many classes in it; one of which is the Scanner

class. You need to import the class into your program before you can use it.

Syntax:

// Get the class definition of the Scanner class from java.util package

import java.util.Scanner;

// Create a Scanner object with name <object name>

// System.in is the standard input stream, which is the keyboard

Scanner <object name> = new Scanner(System.in);

// Use the Scanner class’s operations (methods) to read input

<variable name> = <object name>.<method name>();

Summary of Scanner’s operations:

Method name Description

boolean nextBoolean() Returns the next input token as a boolean value

byte nextByte() Returns the next input token as a byte value

short nextShort() Returns the next input token as a short value

int nextInt() Returns the next input token as a int value

long nextLong() Returns the next input token as a long value

float nextFloat() Returns the next input token as a float value

double nextDouble() Returns the next input token as a double value

String next() Returns the next input token as a String value

String nextLine() Returns all input remaining on the current line as a String value

Example:

import java.util.Scanner;

public class DataInputDemo

{

public static void main(String[] args)

{

Scanner sc = new Scanner(System.in);

System.out.print("Please enter your full name: ");

String fullName = sc.nextLine();

System.out.println("Your name is " + fullName + ".");

System.out.print("Please enter your age (nearest to integer): ");

int age = sc.nextInt();

System.out.println("Your age is " + age + ".");

if (age > 40) System.out.println("Oh! You are too old :P");

}

}

AST10106 Introduction to Programming

5

The last statement of the above code is a peek ahead of a control flow statement made using the

keyword if, which follows by a computable condition defined in the bracket. If the condition is

evaluated to be true, i.e. the age value entered by the user via the console is greater than 40, then

the statement to follow will run, printing “Oh! You are too old :P”.

3. Perform calculation using arithmetic operations:

Java provides five basic operations for arithmetic calculation.

i. Addition (The operator used is +)

ii. Subtraction (The operator used is -)

iii. Multiplication (The operator used is *)

iv. Division (The operator used is /)

v. Remainder (The operator used is %)

Syntax:

// Add the values stored in variable 1 and variable 2

<result variable name> = <name of variable 1> + <name of variable 2>;

// Subtract the value stored in variable 2 from variable 1

<result variable name> = <name of variable 1> - <name of variable 2>;

// Multiply variable 1’s value by variable 2’s value

<result variable name> = <name of variable 1> * <name of variable 2>;

// Divide variable 1’s value by variable 2’s value

<result variable name> = <name of variable 1> / <name of variable 2>;

// Find the remainder of variable 1’s value divided by variable 2’s value

<result variable name> = <name of variable 1> % <name of variable 2>;

Example:

public class ArithmeticOperationsDemo

{

public static void main(String[] args)

{

int val1 = 21;

int val2 = 10;

int sum = val1 + val2;

int diff = val1 - val2;

int prod = val1 * val2;

int quot = val1 / val2;

int rem = val1 % val2;

System.out.println("Addition: " + sum);

System.out.println("Subtraction: " + diff);

System.out.println("Multiplication: " + prod);

System.out.println("Division: " + quot);

System.out.println("Remainder: " + rem);

}

}

AST10106 Introduction to Programming

Lab Exercises

In this lab, you will be asked to solve THREE problems using Java. For these problems, write three

Java programs (one .java file for each) based on the following problem specifications.

1. Write a Java application (called Shapes.java) that displays a box, an oval, an arrow and a diamond

using asterisks (*). Please ensure your output is the same as the sample output below. Note that

there are two spaces between neighboring shapes.

The template of the program has been given for you as follow.

1 public class Shapes

2 {

3 public static void main(String[] args)

4 {

5 /* write a series of statements that will print the

6 shapes to the command window */

7 }

8 }

2. Write a Java application (called Face.java) to print the following face.

The template of the program has been given for you as follow.

1 public class Face

2 {

3 public static void main(String[] args)

4 {

5 /* write a series of statements that will print the

6 face to the command window */

7 }

8 }

Hint: For this problem, the main difficulty lies on how to print the double quote (") characters (the

hair part of this face).

2 spaces

AST10106 Introduction to Programming

If you simply write below for printing the hair part

System.out.println(" +"""""+ ");

then your program won’t compile, and you will see an error message like ')' expected, …

unclosed string literal.

You need to learn a concept called escape sequences here. During the demo time, we have indeed

demonstrated two escape sequences, namely \t and \n, which represent inserting a tab and a

newline (at this point) respectively. To learn more, please check this page:

https://docs.oracle.com/javase/tutorial/java/data/characters.html.

To print a double quote ("), you need to add a backslash (\) before it. This backslash is called the

escape character which causes the compiler to treat the next character’s semantics differently.

To print the sentence

She said "Hello!" to me.

you would write

System.out.println("She said \"Hello!\" to me.");

Alternative method: Apart from using escape characters, there is still another way to print the

double quote character – use its ASCII code (34). So, you can create a variable like

char dQuote = 34;

and use it along with the string concentration operator (+) to form the string of double quotes.

3. Write a Java program Cylinder.java that reads inputs from the user for the radius and the height

of a cylinder (both in double type) and prints the cylinder’s total surface area and volume using the

floating-point value 3.14159 for π. You may also use the predefined constant Math.PI for the

value of π. This constant is more precise than the value 3.14159. The class Math is defined in the

package java.lang which has been imported automatically, so you need not import the class Math

to use it. Use the following formulas (r is the radius; h is the height) for your calculations:

Total surface area = 2πr

2 + 2πrh = 2πr(r+h)

Volume = πr 2h

Sample Output:

(Note: The underlined text refers to the user input. Please also follow closely to the output format

as shown above.)

Hint: to compute r2

, you can write r * r, or use the pow method of the Math class. For example,

Math.pow(r, 2) gives the square of r.

Enter radius of cylinder: 3

Enter height of cylinder: 5

Total surface area is 150.79631999999998

Volume is 141.37154999999998

AST10106 Introduction to Programming

Marking Scheme

The marking of this exercise will be based on the following criteria.

Graded items Weighting

1. Correctness of program (i.e. whether your code is implemented

in a way according to the requirements as specified.) 70%

2. Presentation of the Java codes (i.e. whether the program is

properly indented, how close you follow the common

conventions as mentioned in class, etc.)

15%

3. Documentation (with reasonable amount of comments

embedded in the code to enhance the readability) 15%

100%

Be aware of plagiarism! DON’T copy the program file from your friends or classmates. If any

identical copy is found, 5% of the coursework marks will be deducted for each of the file owner.

Program Submission Checklist

Before submitting your work, please check the following items to see you have done a decent job.

Items to be checked ?

1. Did I put my name, student id and lab section id at the beginning of all the

source files as comment?

2. Did I put a reasonable amount of comments to describe my program? ?

3. Are they all in .java extension and named according to the specification? ?

4. Have I checked that all the submitted code can compile and run without any

errors? ?

5. Did I zip my source files using Winzip / zip provided by Microsoft Windows?

Also, did I check the zip file and see if it could be opened?

(Only applicable if the work has to be submitted in zip format.)

6. Did I submit my lab assignment to Canvas before the deadline? ?

(This checklist need not be submitted.)


站长地图