Advanced Programming Using Java - Section 1

pheasantarrogantΛογισμικό & κατασκευή λογ/κού

15 Αυγ 2012 (πριν από 4 χρόνια και 11 μήνες)

344 εμφανίσεις

1


El
-
Shorouk Academy


Acad. Year
: 2010 / 2011

Higher Institute for Computer &

Term : 1
st

Information Technology


Year

:
3rd

Computer Science Department




Professor
:
Mohammed Zeweedy


Advanced Programming Using (Java)


Section (1)

Section Contents:

-

Overview of The NetBeans IDE

-

C# Vs. Java

-

Java Syntax

-

Sample Programs


Overview of the NetBeans IDE:

Setting u
p the Project

To create an IDE project:

1.

Start NetBeans IDE.

2.

In the IDE, choose File > New Project (Ctrl
-
Shift
-
N), as

shown in the figure below.


3.

In the New Project wizard, expand the Java category and select Java Application as shown in the figure
below. Then click Next.

2



4.

In the Name and Location page of the wizard, do the following (as shown in the figure below):

o

In
the Project Name field, type

HelloWorldApp
.

o

Leave the Use Dedicated Folder for Storing Libraries checkbox unselected.

o

In the Create Main Class field, type

helloworldapp.HelloWorldApp
.

o

Leave the Set as Main Project checkbox selected.


3


5.

Click Finish.

The
project is created and opened in the IDE. You should see the following components:



The Projects window, which contains a tree view of the components of the project, including source files,
libraries that your code depends on, and so on.



The Source Editor w
indow with a file called

HelloWorldApp

open.



The Navigator window, which you can use to quickly navigate between elements within the selected class.



The Tasks window, which lists compilation errors as well other tasks that are marked with keywords such as
XXX and TODO.


Adding Code to the Generated Source File

Because you have left the Create Main Class checkbox selected in the New Project wizard, the IDE has created a
skeleton main class for you. You can add the "Hello World!" message to the skeleton code

by replacing the line:


// TODO code application logic here


with the line:

System.out.println("Hello World!");


Save the change by choosing File > Save.

The file should look something like the following code sample.

/*


* To change this template, choose Tools | Templates


* and open the template in the editor.

4



*/


packagehelloworldapp;


/**


*


* @author <your name>


*/

public class HelloWorldApp {



/**


* @paramargs the command line arguments


*/

public

static void main(String[] args) {

System.out.println("Hello World!");


}


}



Compiling and Running the Program

Because of the IDE's Compile on Save feature, you do not have to manually compile your project in order to run
it in the IDE. When you save
a Java source file, the IDE automatically compiles it.

The Compile on Save feature can be turned off in the Project Properties window. Right
-
click your project, select
Properties. In the Properties window, choose the Compiling tab. The Compile on Save chec
kbox is right at the
top. Note that in the Project Properties window you can configure numerous settings for your project: project
libraries, packaging, building, running, etc.

To run the program:



Choose Run > Run Main Project (F6).

The next figure shows
what you should now see.


Congratulations! Your program works!

If there are compilation errors, they are marked with red glyphs in the left and right margins of the Source Editor.
The glyphs in the left margin indicate errors for the corresponding lines.
The glyphs in the right margin show all
of the areas of the file that have errors, including errors in lines that are not visible. You can mouse over an error
mark to get a description of the error. You can click a glyph in the right margin to jump to the
line with the error.

Building and Deploying the Application

5


Once you have written and test run your application, you can use the Clean and Build command to build your
application for deployment. When you use the Clean and Build command, the IDE runs a buil
d script that
performs the following tasks:



Deletes any previously compiled files and other build outputs.



Recompiles the application and builds a JAR file containing the compiled files.

To build your application:



Choose Run > Clean and Build Main Project
(Shift
-
F11)

You can view the build outputs by opening the Files window and expanding the

HelloWorldApp

node. The
compiled bytecode file

HelloWorldApp.class

is within the
build/classes/helloworldapp

subnode. A deployable
JAR file that contains the

HelloWorldApp.class

is within the

dist

node.


















6



C# vs. Java:

C# and Java are both new
-
generation languages descended from a line including C and C++. Each includes
advanced features, like garbage collection, which remove some of the low level maintenance tasks from the
programmer. In a lot of areas they are syntacti
cally similar.

Both C# and Java compile initially to an intermediate language: C# to Microsoft Intermediate Language (MSIL),
and Java to Java bytecode. In each case the intermediate language can be run
-

by interpretation or just
-
in
-
time
compilation
-

on
an appropriate 'virtual machine'. In C#, however, more support is given for the further
compilation of the intermediate language code into native code.

C# contains more primitive data types than Java and also allows more extension to the value types. For
example,
C# supports 'enumerations', type
-
safe value types which are limited to a defined set of constant variables and
'structs', which are user
-
defined value types

Unlike Java, C# has the useful feature that we can overload various operators.

Like Java
, C# gives up on multiple class inheritance in favour of a single inheritance model extended by the
multiple inheritance of interface. However, polymorphism is handled in a more complicated fashion, with derived
class methods either 'overriding' or 'hiding
' super class methods

C# also uses 'delegates'
-

type
-
safe method pointers. These are used to implement event
-
handling.

In Java, multi
-
dimensional arrays are implemented solely with single
-
dimensional arrays (where arrays can be
members of other arrays.
In addition to jagged arrays, however, C# also implements genuine rectangular array.



Below is a list of features C# and Java share, which are intended to
improve on C++
, but it is very important to be
aware of the similarities.



Compiles into machine
-
independent language
-
independent code which runs in a
managed execution
environment
.



Garbage Collection coupled with the elimination of pointers (in C# restricted use is permitted within code
marked unsafe)



Powerful reflection capabilities



No header files, all code scoped to packages or assemblies, no problems declaring one class before
another with circular dependencies



Classes all descend from object and must be allocated on the heap with new keyword



Thread support by putting a lock on objects when entering code marked as locked/synchronized



Interfaces, with multiple
-
inheritance of i
nterfaces, single inheritance of implementations



Inner classes



No concept of inheriting a class with a specified access level



No global functions or constants, everything belongs to a class



Arrays and strings with lengths built
-
in and bounds checking



The '.' operator is always used, no more
-
>, :: operators



null and boolean/bool are keywords

7




All values are initialized before use



Can't use i
ntegers to govern if statements.



Try Blocks can have a finally clause


Features of C# Absent in Java



C# includes more primitive types and the functionality to catch arithmetic exceptions.



Includes a large number of notational conveniences over Java, many of which, such as operator
overloading and user
-
defined casts, are already familiar to the large comm
unity of C++ programmers.



Event handling is a "first class citizen"

it is part of the language itself.



Allows the definition of "structs", which are similar to classes but may be allocated on the stack (unlike
instances of classes in C# and Java).



C# im
plements properties as part of the language syntax.
.



C# allows anonymous methods providing closure functionality.



C# allows iterator that employs co
-
routines via a functional
-
style
yield

keyword.



C# has support for output parameters, aiding in the return of multiple values, a feature shared by C++ and
SQL.



C# has the ability to alias namespaces.



C# has "Explicit Member Implementation" which allows a class to specifically implement methods of an
i
nterface, separate from its own class methods. This allows it also to implement two different interfaces
which happen to have a method of the same name. The methods of an interface do not need to be
public
;
they can be made to be accessible only via that i
nterface.



C# provides integration with COM.



Following the example of C and C++, C# allows call by reference for primitive and reference types.

Features of Java Absent in C#



Java's
strict

keyword guarantees that the result of floating point operations re
main the same across
platforms.



Java supports checked exceptions for better enforcement of error trapping and handling.













8


Access Modifiers

JAVA

C#


public

Access not limited

protected


Access limited to the package or


subclass in a different package

(no access modifier)


Access limited to the package

private


Access limited to the containing type






Public


Access not limited

protected


Access limited to the containing class or


types derived from the conta
ining class

protected internal


Access limited to this program or


types derived from the containing class

(no access modifier)


by default it is private

internal


Access limited to this program

private


Access limited to the containing type

Pass By Value vs. Pass By Reference

JAVA

C#

Primitive types are passed to methods by value (a
copy is made),

while reference types are passed by reference.


Java cannot pass a primitive type as

a reference type. If you want to do so,

wrap

the primitive type into a class.


Value types are passed to methods by value (a copy is
made),

while reference types are passed by reference.


C# can pass a value type as

a reference type by marking it

with a ref keyword.


public void aMethod(ref int
age, ref int ID){}


Note that you need to use the ref keyword in both

the method declaration and the actual call to the
method.


aRef.aMethod(ref age, ref ID);

Types

JAVA

C#


type:


primitive types


reference types


numeric
-
type:


integral types


floating
-
point types



type:


value types


reference types



numeric
-
type:


integral types


floating
-
point types


decimal


integral
-
type:

9


integral
-
type:


byte


short


int


long


char






floating
-
point
-
type:


float


double


reference
-
type:


class types


interface types


array types



Primitive types(8)

boolean


byte


char


short


int


long


float


double


sbyte


byte


short

ushort


int

uint


long

ulong


char


floating
-
point
-
type:


float


double


reference
-
type:


class types


interface types


array types


delegate types


Predefined types or

system
-
provided types:


object



string


sbyte



short



int



long



byte


ushort


uint


ulong



float



double


bool



char



decimal



NOTE: value types include simple types,

enum types(derived from System.Enum)

andstruct types.

Converting a string to a number

JAVA

C#

String s = "123.45";

int i = new
Double(s).intValue(); //123

int i2 = (int)new Double(s).doubleValue(); //123

string s = "123.45";

int i = (int)s.ToSingle();// 123

int i2 = s.ToInt16(); // 123

10


String vs. string

String is a reference type but immutable.

for example,(Note: the Upper
-
calse

S for String)


String s1 = "hello";

String s2 = s1;

s1 = "goodbye";

System.out.println(s2);//hello

System.out.println(s1);//goodbye


string path = "C:
\
\
My Documents
\
\
";

There is no verbatim string in Java


string is a reference type but immutable.

for
example,(Note: the lower
-
case s for string)


string s1 = "hello";

string s2 = s1;

s1 = "goodbye";

System.Console.WriteLine(s2);//hello

System.Console.WriteLine(s1);//goodbye


string path = "C:
\
\
My Documents
\
\
";

can be written with verbatim string like:

st
ring path = @"C:
\
My Documents
\
";

Primitives vs. Objects

JAVA

C#


Java primitives cannot be assigned to

reference types directly before Java 5.

class Test

{


public static void main(String[] args) {


int i = 123;


Object o = i; // error


int j = (int) o; // error

System.out.println(3.toString());//error


}

}



C# provides a "unified type system".

All types derive from the type object

class Test

{


static void Main() {


int i = 123;


object o = i; // boxing


int j = (int) o; // unboxing

Console.WriteLine(3.ToString());


}

}

Primitive Type vs. Value Type

Java has two types:

primitive types and

reference types


All classes including arrays and interfaces

are reference types.

There are only eight(8) primitive types:

boolean

byte

short

char


C# has two types:

value types and

reference types


All classes including delegate, arrays

and interfaces are reference types.

Value types include simple types, enum types

andstruct types(15).

sbyte

byte

short

11


int

long

float

double



ushort

int

uint

long

ulong

float

double

bool

char

decimal

enum

structs


Pointer

JAVA

C#


There is no pointer concept in Java


int i = 5;

int p;

p = i;

p = 10;

System.out.print(i);//5




Using pointer in C# is not safe.


unsafe

{


int i = 5;


int *p;


p = &i;


*p = 10;

System.Console.Write(i);//10

}

Operators


{ } [ ] ( ) . , : ;

+
-

* / % & | ^ !

~

= <> ? ++
--

&& || <<>>

== != <= >= +=
-
= *= /= %= &=

|= ^= <<= >>= >>>

Java doesn't have operator
-
>


{ } [ ] ( ) . , : ;

+
-

* / % &

| ^ ! ~

= <> ? ++
--

&& || <<>>

== != <= >= +=
-
= *= /= %= &=

|= ^= <<= >>=
-
>

C# doesn't have operator >>>

12




Pre
-
processing directives

None



Pre
-
processing directives


#

Objects

JAVA

C#


Everything derives from Object.

This
includes classes you create,

not including primitive types.


Everything ultimately derives from Object.

This includes classes you create,

as well as value types such as int or structs.

new

JAVA

C#


With reference types, the new keyword instantiate
objects on the heap.

You cannot use new to instantiate a primitive type.



With reference types, the new keyword instantiate
objects on the heap,

but with value types such as structs, the object is
created

on

the stack and a constructor is called. You can, in
fact,

create a struct on the stack without using new,

but you must initialize all the values in the struct by
hand

before you use it (before you pass it to a method)

or it won't compile.

namespace vs
. package

JAVA

C#


Packages are used to organize files or public types to
avoid

type conflicts.

Package constructs can be mapped to a file system.



System.Security.Cryptography.AsymmetricAlgorithm
aa;

may be replaced:

import System.Security.Crypography;

class xxx { ...

AsymmetricAlgorithmaa;


There is no alias for packages.

You have to use import statement

or fully
-
qualified name to

mention the specific type.




Namespaces are used to organize programs,

both as an "internal" organization system for a
pro
gram,

and as an "external" organization system.



System.Security.Cryptography.AsymmetricAlgorith
maa;

may be replaced:

using System.Security.Crypography;

AsymmetricAlgorithmaa;


Alternatively, one could specify an alias

for the the namespace, eg


using myAlias = System.Security.Crypography;

and then refer to the class with


myAlias.AsymmetricAlgorithm

13




pacakge N1.N2;


class A {}


class B {}

or

package N1.N2;


class A {}


//another source file

package N1.N2;


class B {}


package cannot be nested.

One source file can only

have one package statement.



namespace N1.N2

{


class A {}


class B {}

}

or

namespace N1

{


namespace N2


{


class A {}


class B {}


}

}

Method

Modifiers

JAVA

C#

public

protected

no modifier

private

static

final

abstract

native

synchronized

strictfp


public

protected

internal

private

static

sealed

abstract

extern

virtual

override

new

Maximums and Minimums

JAVA

C#


To get maximum and minimum
values:

Byte.MAX_VALUE

Byte.MIN_VALUE

Short.MAX_VALUE

Short.MIN_VALUE

Integer.MAX_VALUE

Integer.MIN_VALUE

Long.MAX_VALUE

Long.MIN_VALUE

Float.MAX_VALUE

Float.MIN_VALUE

Double.MAX_VALUE

Double.MIN_VALUE



To get maximum and minimum values:

System.Byte.MaxValue

System.Byte.MinValue

System.Int16.MaxValue

System.Int16.MinValue

System.Int32.MaxValue

System.Int32.MinValue

System.Int64.MaxValue

System.Int64.MinValue

System.Single.MaxValue

System.Single.MinValue

System.Double.MaxValue

System.Double
.MinValue

System.Decimal.MaxValue

14




System.Decimal.MinValue

Keywords & Reserved Words

JAVA

C#

52

abstract do if package synchronized

boolean double implements private this

break else import protected throw

byte extends instanceof public throws

case false int return transient

catch final interface short true

char finally long static try

class float native strictfp void

const for new super volatile

continue goto null switch while

default assert(1.4)

enum(1.5)








C# doesn't have

assert boolean extends final implements

instanceof native package strictfp super

synchronized throws transient






77

abstract as base bool

break

byte case catch char checked

class const continue decimal default

delegate do double else enum

event explicit extern false finally

fixed

float for foreachgoto

if implicit in int interface

internal is lock long namespace

new null object operator out

override params private protecte
d public

readonly ref return sbyte sealed

short sizeofstackalloc static string

struct switch this throw true

try typeofuintulong unchecked

unsafe ushort using

virtual void

volatile while



Java doesn't have

as base bool checked decimal

delegate event explicit extern

fixed foreach implicit int internal

is lock

namespace object operator

out override paramsreadonly ref

sbyte sealed sizeofstackalloc string

structtypeofuintulong unchecked

unsafe ushort using virtual

Common Escape Sequences

JAVA

C#


Character Escape Sequence

single quote
\
'

double quote
\
"

backslash
\
\




Backspace
\
b

Form feed
\
f

New Line
\
n

Carriage Return
\
r

Horizontal Tab
\
t



Character Escape Sequence

single quote
\
'

double quote
\
"

backslash
\
\




Alert
\
a

Backspace
\
b

Form feed
\
f

New Line
\
n

Carriage Return
\
r

Horizontal Tab
\
t

Vertical Tab
\
v

15


Unicode
\
u

hexadecimal
\
x


Unicode
\
u

hexidecimal
\
x

null
\
0 (zero)


Class Modifiers

JAVA

C#


for outer class


public


abstract


final


no modifier


for nested class


public


abstract


final


private


no modifier




for outer class


public


abstract


sealed


internal(default/no modifier)


for nested class


public


abstract


sealed


protected


internal


protected internal


private


new

Array Type

JAVA

C#


Java has two kinds of arrays:




single
-
dimensional



multi
-
dimensional or jagged arrays (arrays of
arrays).


Note that the declaration has big difference from C#

int[] myIntArray = new int[5]; //create a single
-
dimensional array

int[] myIntArray = { 2, 4, 6, 8, 10 }; // initialize an
array


int[,] myRectangu
larArray = new int[rows, columns];
//illegal

int[,] myRectangularArray =

{


{0,1,2}, {3,4,5}, {6,7,8}, {9,10,11} //illegal

};


int [,,] array = new int [3, 4, 5];//illegal


C# has three kinds of arrays:




single
-
dimensional



multi
-
dimensional rectangular arrays



jagged arrays (arrays of arrays).


Note that the declaration has big difference from Java

int[] myIntArray = new int[5]; //create a single
-
dimensional array

int[] myIntArray = { 2, 4, 6, 8, 10 }; // i
nitialize an
array


int[,] myRectangularArray = new int[rows, columns];
//create a rectangular array

int[,] myRectangularArray =

{


{0,1,2}, {3,4,5}, {6,7,8}, {9,10,11} //intialize
array

};


16


int [1,1,1] = 5;//illegal

int [][][] array = new int [3][4][5]; // ok

int [1][1
][1] = 5; //ok



class Test

{


public static void main(String[] args) {


int[] a1; // single
-
dimensional array of int


int[][] a2; // 2
-
dimensional array of int


int[][][] a3; // 3
-
dimensional array of int


int[][] j2; // "jagged" array: array of (array of
int)


int[][][] j3; // array of (array of (array of int))


}

}



class Test

{


public static void main(String[] args) {


int[] a1 = new int[] {1, 2, 3};


int[][] a2
= new int[][] {{1, 2, 3}, {4, 5, 6}};


int[][][] a3 = new int[10][20][30];


int[][] j2 = new int[3][];


j2[0] = new int[] {1, 2, 3};


j2[1] = new int[] {1, 2, 3, 4, 5, 6};


j2[2] = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9};



}

}


class Test

{


public static void main(String[] args) {


int[] arr = new int[5];


for (int i = 0; i <arr.length; i++)

arr[i] = i * i;


for (int i = 0; i <arr.length; i++)

System.out.println("arr[" + i + "] = " + arr[i]);



}

}



int[][] jag = new int[][] {new int[] {1, 2, 3, 4}, new int[]
{5, 6, 7, 8, 9, 10}};

//access elements

for (int i = 0; i <jag.length; i++)


for (int j = 0; j < jag[i].length; j++)

int [,,] array = new int [3, 4, 5]; // creates a 3x4x5
array

int [1,1,1] = 5;

int [][][] array = new int [3][4][5]; // creates
1+3+12=16 arrays

int [1][1][1] = 5;


class Test

{


static void Main() {


int[] a1; // single
-
dimensional array of int


int[,] a2; // 2
-
dimensional array of int



int[,,] a3; // 3
-
dimensional array of int


int[][] j2; // "jagged" array: array of (array of
int)


int[][][] j3; // array of (array of (array of int))


}

}



class Test

{


static void Main() {


int[] a1 = new int[] {1, 2
, 3};


int[,] a2 = new int[,] {{1, 2, 3}, {4, 5, 6}};


int[,,] a3 = new int[10, 20, 30];


int[][] j2 = new int[3][];


j2[0] = new int[] {1, 2, 3};


j2[1] = new int[] {1, 2, 3, 4, 5, 6};


j2[2] = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9};


}

}


class Test

{


static void Main() {


int[] arr = new int[5];


for (int i = 0; i <arr.Length; i++)

arr[i] = i * i;


for (int i = 0; i <arr.Length; i++)

Console.WriteLine
("arr[{0}] = {1}", i, arr[i]);


}

}



int[][] jag = new int[][] {new int[] {1, 2, 3, 4}, new
int[] {5, 6, 7, 8, 9, 10}};

for (int i = 0; i <jag.Length; i++)

17


System.out.println(jag[i][j]);


for (int j = 0; j < jag[i].Length; j++)

System.Console.WriteLine(jag[i][j]);

or

for (int i

= 0; i <jag.GetLength(0); i++)


for (int j = 0; j < jag[i].GetLength(0); j++)

System.Console.WriteLine(jag[i][j]);

Application Startup

JAVA

C#

Only one: public static void main(String[] args) {...}


One of these: static void Main(
) {...} static void
Main(string[] args) {...} static int Main() {...} static
int Main(string[] args) {...}





Java Syntax:

Java syntax is very close to that of "C" and C++. This is true for


• Comments (+ documentation comment).


• Variable names, declarations and initialisations.


• Most keywords, with a few new ones.


• Control flow ("if", "while", "for",)


• etc.



Variable declarations


Standard primitive types in Java:

boolean

true or false

char

16 bit character, coded
using Unicode 1.1.5

byte

8 bit signed integer, using
2's complement

short

16 bit signed integer, using
2's complement

int

32 bit signed integer, using
2's complement

long

64 bit signed integer, using
2's complement

18


float

floating point real number,
32 bit IEEE 754
-
1985

double

floating point real number,
64 bit IEEE 754
-
1985

Variable declarations consist of three parts: modifiers, followed by a type, followed by a list of identifiers. The
modifiers are optional,

but the type and list of identifiers is not.

Example: public

int

a, b, c; //"public"

is

a

modifier.

Variables may be initialised as in "C", e.g. "inta=0;"

A
rrays


Arrays are NOT declared as in "C". To declare an array of integers, we would write "int [] ia;" This means that ia
is a reference (compare with reference and pointer in "C" and C++) to an array of integers.

In order to actually create the array at the sam
e time, we would write:

int [] ia=newint [3];

This means that ia now references an array object which can contain an array of 3 integers.

Flow control

Flow controls which have an identical syntax to that of "C" are:


• if
-
else

• switch
-
case

• while



do
-
while

• for

• break, continue, return


But there is no “goto” statement! Instead, Java proposes labelled breaks, as shown in the following example.


Standard input and output

The global class "System" contains the fields "in", "out" and "err", which correspond to
standard i
nput, standard
output and standard error.


Scanner

import

java.util.Scanner;

String

name;


int

age;


Scanner

in

=

new

Scanner(System.in);



//

Reads

a

single

line

from

the

console



//

and

stores

into

name

variable


name

=

in.nextLine();



//

Reads

a

integer

from

the

console


//

and

stores

into

age

variable

19



age=in.nextInt();


in.close();



Buffer

BufferedReader

br

=

new

BufferedReader(new

InputStreamReader(System.in));


String

name

=

null;


try

{


name

=

br.readLine();


}

catch

(IOException

e)

{



Simple


userInput = TextIO.getInt();





Sample Programs:


(Computing GCD) Write a method that returns the greatest common divisor between two positive integers, using
the following header:

public static int

gcd(
int

m,
int

n)


Write a test program that computes
gcd(24, 16)

and
gcd(255, 25)
.




Problem Solution:


Public

class

Exercise5_10 {

Public

static

void

main(
String
[] args) {

System
.out.println(gcd(24, 16));

System
.out.println(gcd(255, 25));


}


publicstaticint

gcd(
int

m,
int

n) {

int

gcd = 1;

int

k = 1;


while

(k <= m && k <= n) {

if

(m % k == 0 &&

n % k == 0)


gcd = k;


k++;


}


return

gcd;


}

}



20


Poll A
nalysis
Program:

public class
StudentPoll


{

public static void

main( String args[] )


{

int

responses[] = {
1
,
2
,
6
,
4
,
8
,
5
,
9
,
7
,
8
,
10
,
1
,
6
,
3
,
8
,
6
,

10
,
3
,
8
,
2
,
7
,
6
,
5
,
7
,
6
,
8
,
6
,
7
,
5
,
6
,
6
,
5
,
6
,
7
,
5
,
6
,

4
,
8
,
6
,
8
,
10

};

int

frequency[] =
new int
[
11

];
// array of frequency counters


for

(
int

answer =
0
; answer <responses.length; answer++ )

++frequency[ responses[ answer ] ];


System.out.printf(
"%s%10s"
,
"Rating"
,
"Frequency"

);

for

(
int

rating =
1
; rating <frequency.length; rating++ )

System.out.printf(
"%d%10d"
, rating, frequency[ rating ] );


}


}


Rating Frequency


1 2


2 2


3 2


4 2


5 5


6 11


7 5


8 7


9 1


10 3