• Tidak ada hasil yang ditemukan

Java with BlueJ

N/A
N/A
Nguyễn Gia Hào

Academic year: 2023

Membagikan "Java with BlueJ"

Copied!
209
0
0

Teks penuh

2015 - awarded the IEEE John von Neumann Medal for "the Java programming language, Java Virtual Machine, and other contributions to programming languages ​​and environments".[3]. When someone develops a Java program, they must first enter the Java code into a text file.

BlueJ

A First Program

Using BlueJ to Run HelloWorld

Double click on the image in the project representing HelloWorld ..the BlueJ editor opens and shows you the content. Finally, to run the program, you must close the editor by clicking the close button.

Literals

Variables

Two example programs follow; in Listing 2.1, the program defines and uses a variable, and in Listing 2.2, the program changes the value stored in a variable. Java variable names are case sensitive, so two variables named Message and message do not refer to the same thing.

Primitive Data Types

Numeric Data Types: byte, short, int, long

Integer Arithmetic

The following program example uses division and modulo to obtain the last two digits of an integer. Modify the program in Listing 2.3 so that each of the four digits is displayed on separate lines.

Figure 2.1: Last two digits
Figure 2.1: Last two digits

Numeric Data Types: float, double

Most people use the decimal number system where we can write the fraction 1/4 exactly as 0.25. Modify the program in Listing 2.4 to calculate and display fuel consumption as the number of kilometers traveled per liter of fuel.

Numeric Expressions

In the following program (see line 12), the value s, a 2-byte integer, will be converted to the value int, a 4-byte integer. A subexpression is evaluated before the expression of which it is a part, and that value is substituted in its place.

Conditional Operator ?

Operator Priorities

If you look at the priorities of the operators, you will see that the additions will be performed first, followed by the relational operators, followed by. What is often referred to as the assignment statement is actually a Java expression followed by a semicolon.

The String Class

Maybe you want to do this when you develop a program and you want to look up the string methods. Several example programs that show how to use the various methods of the String class follow.

Table 2.1: Some of the useful String methods
Table 2.1: Some of the useful String methods

Implied declarations using var

Output

JOptionPane

When receiving input from the user, the program waits for the user to respond by clicking a button. When a pop-up window appears, the program is suspended until the user clicks the OK button.

Input

The Scanner Class

Write a program that prompts the user for their birthday as the day (as an integer), followed by the month (as text), followed by the year (as an integer) with at least one space between the values.

The JOptionPane Class

In line 13, the values ​​retrieved from the dialogs are displayed in the BlueJ terminal window.

3 Control Structures

Compound Statements

Consider the following program that displays one of two messages depending on the value of the expression number > 0. Write a program that retrieves two numbers from the user and displays the larger of the two numbers. The first approach is to code an if statement for each row of the table, where the logical expression refers to the letter grade value in the row.

When reviewing this program, notice the nesting of the ifs - every else clause contains an if.

This is the last time the compound statement is executed as the logical expression evaluates to false - the JVM will move on to the statement after the while statement (line 14) where normal sequential execution resumes. To do this, the program has a for loop (lines 14-17) that is executed once for each character in the string. The variable count is defined in the for statement and so the scope of count is the for statement.

Correctly edit the example to display the value of counter in the print statement (line 11).

Write a program where the user enters the name of the month and the program displays the number of days in that month. The program uses two methods from the String class: toLowerCase() and equals(..). a) (line 31) toLowerCase() converts the user's response to all lowercase letters. Change example 2 so that the user gets a report at the end of the program: the number of correct and the number of incorrect answers.

Write a program that picks a random number between 1 and 100 and then asks the user to guess what the number is.

4 Introduction to Methods

Void Methods

Value-returning Methods

Parameters

1 the keynote value is copied to the memory locations reserved for s in the convert method;. 2 the code that includes the conversion is executed and during its execution the variable num in the conversion will be assigned a value;. 3 finally, the conversion return statement is executed causing the value of num to be passed back to where the conversion was called (and so nGrade gets a value).

Note that the variables inside the method are independent of the variables outside it, so the variables in the conversion could just as easily be named nGrade and grade instead of num and s.

Summary

Write a program that displays the French translation of an English word obtained from the user. 129 Write a program that gets a word from the user and shows whether or not the word is a palindrome. To calculate the check digit, we need to know the sum of the digits of the check digit.

Write a program that receives a check number from the user and prints the check number followed by its check digit.

5 Classes in the Java Class Libraries

Random

If a player rolls a 1, that player draws nothing for that turn and it becomes the next player's turn. If a player rolls any other number, that number is added to the player's turn total and the player's turn continues. If a player chooses to "hold", that player's turn total is added to the player's total score, and it becomes the next player's turn.

Write a program to simulate a player's turn, where the player's strategy is to continue rolling as long as the turn score is less than 25.

Character

If the user enters invalid characters and the program executes the nextInt() scanner method, the program crashes. 3 * A user-specified string is examined 4 * to determine whether or not it is numeric. Write a program that asks the user for a zip code and then determines whether it is valid or not.

Write a program to validate a zip code entered by the user where the user may have entered a standard zip code (5 characters) or a zip+4 code (10 characters including the hyphen representing the first 5 digits of the separate last 4 digits).

Scanner

To read a text file, we can declare a Scanner object associated with that file. For example, if a program uses nextInt() but the next token is a string, an exception will be thrown. Consider the following program that reads the Readme.txt file and displays the lines including line numbers.

The File class itself is quite complex, but for our purposes we simply name the file and instantiate a File object.

Math

The following program prompts the user for three int values ​​and reports the largest of the three. Write a program that takes the radius of a circle from the user and calculates the area of ​​the circle. Write a program that takes the radius of a sphere from the user and calculates the volume of the sphere.

Write a program that takes the x and y values ​​of a right triangle from the user and calculates the length of the hypotenuse.

Integer

155 Using a Scanner object, a program can use the Scanner nextLine() method to get a line of three things: an item name, a comma, and an integer. The program can find the location of the comma and know that what follows in the string is a quantity. Modify Example 1 to find the item for which the quantity on hand is the largest.

The program should print each value on a separate line and then display the maximum and minimum values.

6 ArrayLists

It can be used to remove either .. a) the element at a given position in this list, or.

The enhanced for

The user is prompted for names to be added to the list - the process stops when the user enters the word stop. This declaration has no angle brackets and thus no type specification, and thus it is possible to add any type of object to the ArrayList. 12 // No type specification for people 13 // So any old object will do 14 ArrayList people=new ArrayList();.

165 The output below shows two String objects, a System.out object and a Scanner object - all added to the ArrayList.

Sieve of Eratosthenes

Parallel Lists

ArrayListis part of the Java Collections framework and there is a sort(..) method in Collections that can be used to sort an ArrayList. Modify the previous program to use parallel arrays to define and display each word and its frequency. Remove all punctuation from the tokens and store the lowercase words in the ArrayList.

7 Designing Java Classes

The println() method is an example of a void method (a method that does not return a value). The above list is long and indicates that this chapter covers several new Java programming concepts.

Using Multiple Classes

Fields

In the top compartment we show a name for an object (e.g. Jill) and the class of the object (e.g. Student). We've seen many examples of this, including max() and min() in the Math class, and the nextInt() and nextBoolean() of the Random class. Because they are getters, every method name (except one) begins with "get" for a field name, where the first character of the field name is capitalized.

Since they are setters, each method name begins with "set" before the field name, where the first character of the field name is capitalized.

Figure 8.2: Class diagram with two compartments
Figure 8.2: Class diagram with two compartments

Constructors

In the parameter list of the constructor, the parameters have exactly the same name as the corresponding fields. The right side of the assignment statement is a reference to a parameter, and the left side of the assignment statement is a reference to the object's field. And so this assignment statement assigns a value passed in via the parameter to an object's field.

Note that we have left out some details such as field types and parameter types.

Figure 8.5: Student class with 3 compartments.
Figure 8.5: Student class with 3 compartments.

Visibility Specifications: Public, Private

When a method is designated as private, the method can only be called from the class in which it is defined. When a constructor is designated public, any other class can use that constructor to create an object. When a constructor is designated as private, the constructor can only be called from the class in which it is defined.

If you try to instantiate an instance of Math, your program will not compile; the message you get back from the compiler is "Math() has private access to java.lang.Math".

Overloading

Associations

For each student subject, there is a field that can be set to the student's major. In addition to the getters and setters, we include another addMajor() method, in lines 28-30, that allows adding a student to the existing list of major students. There is a getter for directions that returns directions and a setter where the parameter is of type ArrayList.

In addition to the getters and setters, we include one more method addMajor( ) that allows one to add a student to the existing list of major students.

Reusing code

Parameter lists and arguments

Gambar

Figure 2.1: Last two digits
Figure 2.4: Getting documentation on Java classes
Table 2.1: Some of the useful String methods
Figure 2.5: Showing the string and its length
+5

Referensi

Dokumen terkait

3.3 JAVA Socket 실습 : ChatHandler.java 1/3 예제: ChatHandler.java public class ChatHandler implements Runnable { private Socket socket; private DataInputStream dataIn; private