0% found this document useful (0 votes)
34 views26 pages

Java Basics-Páginas-3

Uploaded by

Johnson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views26 pages

Java Basics-Páginas-3

Uploaded by

Johnson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

1/9/25, 3:48 PM Java Basics - Java Programming Tutorial

average = (double)sum / count;


System.out.println("The sum of odd numbers is: " + sum);
//The sum of odd numbers is: 250000
System.out.println("The average of odd numbers is: " + average);
//The average of odd numbers is: 500.0
}
}

Using boolean Flag for Loop Control


Besides using an index variable for loop control, another common way to control the loop is via a boolean flag.

Example: Below is an example of using while-do with a boolean flag. The boolean flag is initialized to false to ensure that the loop is entered.
// Game loop
boolean gameOver = false;
while (!gameOver) {
// play the game
......
// Update the game state
// Set gameOver to true if appropriate to exit the game loop
if ( ...... ) {
gameOver = true; // exit the loop upon the next iteration test
}
}

Example: Suppose that your program prompts user for a number between 1 to 10, and checks for valid input. A do-while loop with a boolean flag could be more
appropriate as it prompts for input at least once, and repeat again and again if the input is invalid.

// Input with validity check


boolean isValid = false;
int number;
do {
// prompt user to enter an int between 1 and 10
......
// if the number entered is valid, set done to exit the loop
if (number >= 1 && number <= 10) {
isValid = true; // exit the loop upon the next iteration test
// Do the operations
......
} else {

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 53/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
// Print error message and repeat (isValid remains false)
......
}
} while (!isValid); // Repeat for invalid input

for-loop with Comma Separator


You could place more than one statement in the init and update, separated with commas. For example,

// for (init; test; update) { ...... }


for (int row = 0, col = 0; row < SIZE; ++row, ++col) {
// Process diagonal elements (0,0), (1,1), (2,2),...
......
}

The test, however, must be a boolean expression that returns a boolean true or false.

Terminating Program
System.exit(int exitCode): You could invoke the method System.exit(int exitCode) to terminate the program and return the control to the Java Runtime.
By convention, return code of zero indicates normal termination; while a non-zero exitCode indicates abnormal termination. For example,

if (errorCount > 10) {


System.out.println("too many errors");
System.exit(1); // Terminate the program with abnormal exit code of 1
}

The return statement: You could also use a "return" statement in the main() method to terminate the main() and return control back to the Java Runtime. For
example,

public static void main(String[] args) {


...
if (errorCount > 10) {
System.out.println("too many errors");
return; // Terminate and return control to Java Runtime from main()
}
...
}

Exercises on Decision and Loop

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 54/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
LINK

Input/Output

Formatted Output via "printf()" (JDK 5)


System.out.print() and println() do not provide output formatting, such as controlling the number of spaces to print an int and the number of decimal places for a
double.

Java SE 5 introduced a new method called printf() for formatted output (which is modeled after C Language's printf()). printf() takes the following form:

printf(formattingString, arg1, arg2, arg3, ... );

Formatting-string contains both normal texts and the so-called Format Specifiers. Normal texts (including white spaces) will be printed as they are. Format specifiers, in the
form of "%[flags][width]conversionCode", will be substituted by the arguments following the formattingString, usually in a one-to-one and sequential manner. A
format specifier begins with a '%' and ends with the conversionCode, e.g., %d for integer, %f for floating-point number (float and double), %c for char and %s for
String. An optional width can be inserted in between to specify the field-width. Similarly, an optional flags can be used to control the alignment, padding and others. For
examples,
%d, %αd: integer printed in α spaces (α is optional), right-aligned. If α is omitted, the number of spaces is the length of the integer.
%s, %αs: String printed in α spaces (α is optional), right-aligned. If α is omitted, the number of spaces is the length of the string (to fit the string).
%f, %α.βf, %.βf: Floating point number (float and double) printed in α spaces with β decimal digits (α and β are optional). If α is omitted, the number of spaces
is the length of the floating-point number.
%n: a system-specific new line (Windows uses "\r\n", Unix and macOS "\n").

Examples:

Example Output
// Without specifying field-width Hi,|Hello|123|45.600000|,@xyz
System.out.printf("Hi,|%s|%d|%f|,@xyz%n", "Hello", 123, 45.6);

// Specifying the field-width and decimal places for double Hi,| Hello| 123| 45.60|,@xyz
System.out.printf("Hi,|%6s|%6d|%6.2f|,@xyz%n", "Hello", 123, 45.6);

// Various way to format integers: Hi,|111| 222|333 |00444|,@xyz


// flag '-' for left-align, '0' for padding with 0
System.out.printf("Hi,|%d|%5d|%-5d|%05d|,@xyz%n", 111, 222, 333, 444);

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 55/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial

// Various way to format floating-point numbers: Hi,|11.100000| 22.20|33.30|44.40 |,@xyz


// flag '-' for left-align
System.out.printf("Hi,|%f|%7.2f|%.2f|%-7.2f|,@xyz%n", 11.1, 22.2, 33.3, 44.4);

// To print a '%', use %% (as % has special meaning) The rate is: 1.20%.
System.out.printf("The rate is: %.2f%%.%n", 1.2);

Take note that printf() does not advance the cursor to the next line after printing. You need to explicitly print a newline character (via %n) at the end of the formatting-
string to advance the cursor to the next line, if desires, as shown in the above examples.

There are many more format specifiers in Java. Refer to JDK Documentation for the detailed descriptions (@
https://docs.oracle.com/javase/10/docs/api/java/util/Formatter.html for JDK 10).

(Also take note that printf() take a variable number of arguments (or varargs), which is a new feature introduced in JDK 5 in order to support printf())

Input From Keyboard via "Scanner" (JDK 5)


Java, like all other languages, supports three standard input/output streams: System.in (standard input device), System.out (standard output device), and System.err
(standard error device). The System.in is defaulted to be the keyboard; while System.out and System.err are defaulted to the display console. They can be re-
directed to other devices, e.g., it is quite common to redirect System.err to a disk file to save these error message.

You can read input from keyboard via System.in (standard input device).

JDK 5 introduced a new class called Scanner in package java.util to simplify formatted input (and a new method printf() for formatted output described earlier). You
can construct a Scanner to scan input from System.in (keyboard), and use methods such as nextInt(), nextDouble(), next() to parse the next int, double and
String token (delimited by white space of blank, tab and newline).

import java.util.Scanner; // Needed to use the Scanner


/**
* Test input scanner
*/
public class ScannerTest {
public static void main(String[] args) {
// Declare variables
int num1;
double num2;
String str;

// Read inputs from keyboard


// Construct a Scanner named "in" for scanning System.in (keyboard)
Scanner in = new Scanner(System.in);
System.out.print("Enter an integer: "); // Show prompting message

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 56/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
num1 = in.nextInt(); // Use nextInt() to read an int
System.out.print("Enter a floating point: "); // Show prompting message
num2 = in.nextDouble(); // Use nextDouble() to read a double
System.out.print("Enter a string: "); // Show prompting message
str = in.next(); // Use next() to read a String token, up to white space
in.close(); // Scanner not longer needed, close it

// Formatted output via printf()


System.out.printf("%s, Sum of %d & %.2f is %.2f%n", str, num1, num2, num1+num2);
}
}

You can also use method nextLine() to read in the entire line, including white spaces, but excluding the terminating newline.

/**
* Test Scanner's nextLine()
*/
import java.util.Scanner; // Needed to use the Scanner
public class ScannerNextLineTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a string (with space): ");
// Use nextLine() to read entire line including white spaces,
// but excluding the terminating newline.
String str = in.nextLine();
in.close();
System.out.printf("%s%n", str);
}
}

Try not to mix nextLine() and nextInt()|nextDouble()|next() in a program (as you may need to flush the newline from the input buffer).

The Scanner supports many other input formats. Check the JDK documentation page, under module java.base ⇒ package java.util ⇒ class Scanner ⇒ Method (@
https://docs.oracle.com/javase/10/docs/api/java/util/Scanner.html for JDK 10).

Code Example: Prompt User for Two Integers and Print their Sum
The following program prompts user for two integers and print their sum. For examples,

Enter first integer: 8


Enter second integer: 9

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 57/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
The sum is: 17

import java.util.Scanner; // For keyboard input


/**
* 1. Prompt user for 2 integers
* 2. Read inputs as "int"
* 3. Compute their sum in "int"
* 4. Print the result
*/
public class Add2Integer { // Save as "Add2Integer.java"
public static void main (String[] args) {
// Declare variables
int number1, number2, sum;

// Put up prompting messages and read inputs as "int"


Scanner in = new Scanner(System.in); // Scan the keyboard for input
System.out.print("Enter first integer: "); // No newline for prompting message
number1 = in.nextInt(); // Read next input as "int"
System.out.print("Enter second integer: ");
number2 = in.nextInt();
in.close();

// Compute sum
sum = number1 + number2;

// Display result
System.out.println("The sum is: " + sum); // Print with newline
}
}

Code Example: Income Tax Calculator


The progressive income tax rate is mandated as follows:

Taxable Income Rate (%)


First $20,000 0

Next $20,000 10

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 58/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial

Next $20,000 20

The remaining 30

For example, suppose that the taxable income is $85000, the income tax payable is $20000*0% + $20000*10% + $20000*20% + $25000*30%.

Write a program called IncomeTaxCalculator that reads the taxable income (in int). The program shall calculate the income tax payable (in double); and print the
result rounded to 2 decimal places.

Enter the taxable income: $41234


The income tax payable is: $2246.80

Enter the taxable income: $67891


The income tax payable is: $8367.30

Enter the taxable income: $85432


The income tax payable is: $13629.60

Enter the taxable income: $12345


The income tax payable is: $0.00

import java.util.Scanner; // For keyboard input


/**
* 1. Prompt user for the taxable income in integer.
* 2. Read input as "int".
* 3. Compute the tax payable using nested-if in "double".
* 4. Print the values rounded to 2 decimal places.
*/
public class IncomeTaxCalculator {
public static void main(String[] args) {
// Declare constants first (variables may use these constants)
final double TAX_RATE_ABOVE_20K = 0.1;
final double TAX_RATE_ABOVE_40K = 0.2;
final double TAX_RATE_ABOVE_60K = 0.3;

// Declare variables
int taxableIncome;
double taxPayable;

// Prompt and read inputs as "int"


Scanner in = new Scanner(System.in);
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 59/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
System.out.print("Enter the taxable income: $");
taxableIncome = in.nextInt();
in.close();

// Compute tax payable in "double" using a nested-if to handle 4 cases


if (taxableIncome <= 20000) { // [0, 20000]
taxPayable = 0;
} else if (taxableIncome <= 40000) { // [20001, 40000]
taxPayable = (taxableIncome - 20000) * TAX_RATE_ABOVE_20K;
} else if (taxableIncome <= 60000) { // [40001, 60000]
taxPayable = 20000 * TAX_RATE_ABOVE_20K
+ (taxableIncome - 40000) * TAX_RATE_ABOVE_40K;
} else { // >=60001
taxPayable = 20000 * TAX_RATE_ABOVE_20K
+ 20000 * TAX_RATE_ABOVE_40K
+ (taxableIncome - 60000) * TAX_RATE_ABOVE_60K;
}

// Alternatively, you could use the following nested-if conditions


// but the above follows the table data
//if (taxableIncome > 60000) { // [60001, ]
// ......
//} else if (taxableIncome > 40000) { // [40001, 60000]
// ......
//} else if (taxableIncome > 20000) { // [20001, 40000]
// ......
//} else { // [0, 20000]
// ......
//}

// Print result rounded to 2 decimal places


System.out.printf("The income tax payable is: $%.2f%n", taxPayable);
}
}

Code Example: Income Tax Calculator with Sentinel


Based on the previous example, write a program called IncomeTaxCalculatorSentinel which shall repeat the calculations until user enter -1. For example,

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 60/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial

Enter the taxable income: $41000


The income tax payable is: $2200.00
Enter the taxable income: $62000
The income tax payable is: $6600.00
Enter the taxable income: $73123
The income tax payable is: $9936.90
Enter the taxable income: $84328
The income tax payable is: $13298.40
Enter the taxable income: $-1
bye!

The -1 is known as the sentinel value. (In programming, a sentinel value, also referred to as a flag value, trip value, rogue value, signal value, or dummy data, is a special
value which uses its presence as a condition of termination.)

import java.util.Scanner; // For keyboard input


/**
* 1. Prompt user for the taxable income in integer.
* 2. Read input as "int".
* 3. Compute the tax payable using nested-if in "double".
* 4. Print the values rounded to 2 decimal places.
* 5. Repeat until user enter -1.
*/
public class IncomeTaxCalculatorSentinel {
public static void main(String[] args) {
// Declare constants first (variables may use these constants)
final double TAX_RATE_ABOVE_20K = 0.1;
final double TAX_RATE_ABOVE_40K = 0.2;
final double TAX_RATE_ABOVE_60K = 0.3;
final int SENTINEL = -1; // Terminating value for input

// Declare variables
int taxableIncome;
double taxPayable;

Scanner in = new Scanner(System.in);


// Read the first input to "seed" the while loop
System.out.print("Enter the taxable income: $");
taxableIncome = in.nextInt();

while (taxableIncome != SENTINEL) {


https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 61/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
// Compute tax payable in "double" using a nested-if to handle 4 cases
if (taxableIncome > 60000) {
taxPayable = 20000 * TAX_RATE_ABOVE_20K
+ 20000 * TAX_RATE_ABOVE_40K
+ (taxableIncome - 60000) * TAX_RATE_ABOVE_60K;
} else if (taxableIncome > 40000) {
taxPayable = 20000 * TAX_RATE_ABOVE_20K
+ (taxableIncome - 40000) * TAX_RATE_ABOVE_40K;
} else if (taxableIncome > 20000) {
taxPayable = (taxableIncome - 20000) * TAX_RATE_ABOVE_20K;
} else {
taxPayable = 0;
}

// Print result rounded to 2 decimal places


System.out.printf("The income tax payable is: $%.2f%n", taxPayable);

// Read the next input


System.out.print("Enter the taxable income: $");
taxableIncome = in.nextInt();
// Repeat the loop body, only if the input is not the SENTINEL value.
// Take note that you need to repeat these two statements inside/outside the loop!
}
System.out.println("bye!");
in.close(); // Close Scanner
}
}

Notes:
1. The coding pattern for handling input with sentinel (terminating) value is as follows:

// Get first input to "seed" the while loop


input = ......;
while (input != SENTINEL) {
// Process input
......
......
// Get next input and repeat the loop
input = ......; // Need to repeat these statements

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 62/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
}
......

Code Example: Guess A Number


Guess a number between 0 and 99.

import java.util.Scanner;
/**
* Guess a secret number between 0 and 99.
*/
public class NumberGuess {
public static void main(String[] args) {
// Define variables
final int SECRET_NUMBER; // Secret number to be guessed
int numberIn; // The guessed number entered
int trialNumber = 0; // Number of trials so far
boolean done = false; // boolean flag for loop control
Scanner in = new Scanner(System.in);

// Set up the secret number: Math.random() generates a double in [0.0, 1.0)


SECRET_NUMBER = (int)(Math.random()*100);

// Use a while-loop to repeatedly guess the number until it is correct


while (!done) {
++trialNumber;
System.out.print("Enter your guess (between 0 and 99): ");
numberIn = in.nextInt();
if (numberIn == SECRET_NUMBER) {
System.out.println("Congratulation");
done = true;
} else if (numberIn < SECRET_NUMBER) {
System.out.println("Try higher");
} else {
System.out.println("Try lower");
}
}
System.out.println("You got in " + trialNumber + " trials");
in.close();

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 63/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
}
}

Notes:
1. The above program uses a boolean flag to control the loop, in the following coding pattern:
boolean done = false;

while (!done) {
if (......) {
done = true; // exit the loop upon the next iteration
.....
}
...... // done remains false. repeat loop
}

Exercises on Decision/Loop with Input


LINK

Input from Text File via "Scanner" (JDK 5)


Other than scanning System.in (keyboard), you can connect your Scanner to scan any input sources, such as a disk file or a network socket, and use the same set of
methods nextInt(), nextDouble(), next(), nextLine() to parse the next int, double, String and line. For example,

Scanner in = new Scanner(new File("in.txt")); // Construct a Scanner to scan a text file


// Use the same set of methods to read from the file
int anInt = in.nextInt(); // next String
double aDouble = in.nextDouble(); // next double
String str = in.next(); // next int
String line = in.nextLine(); // entire line

To open a file via new File(filename), you need to handle the so-called FileNotFoundException, i.e., the file that you are trying to open cannot be found.
Otherwise, you cannot compile your program. There are two ways to handle this exception: throws or try-catch.

/**
* Input from File.
* Technique 1: Declare "throws FileNotFoundException" in the enclosing main() method
*/
import java.util.Scanner; // Needed for using Scanner
import java.io.File; // Needed for file operation
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 64/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
import java.io.FileNotFoundException; // Needed for file operation
public class TextFileScannerWithThrows {
public static void main(String[] args)
throws FileNotFoundException { // Declare "throws" here
int num1;
double num2;
String name;
Scanner in = new Scanner(new File("in.txt")); // Scan input from text file
num1 = in.nextInt(); // Read int
num2 = in.nextDouble(); // Read double
name = in.next(); // Read String
System.out.printf("Hi %s, the sum of %d and %.2f is %.2f%n", name, num1, num2, num1+num2);
in.close();
}
}

To run the above program, create a text file called in.txt containing:

1234
55.66
Paul

/**
* Input from File.
* Technique 2: Use try-catch to handle exception
*/
import java.util.Scanner; // Needed for using Scanner
import java.io.File; // Needed for file operation
import java.io.FileNotFoundException; // Needed for file operation
public class TextFileScannerWithCatch {
public static void main(String[] args) {
int num1;
double num2;
String name;
try { // try these statements
Scanner in = new Scanner(new File("in.txt"));
num1 = in.nextInt(); // Read int
num2 = in.nextDouble(); // Read double
name = in.next(); // Read String
System.out.printf("Hi %s, the sum of %d and %.2f is %.2f%n", name, num1, num2, num1+num2);

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 65/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
in.close();
} catch (FileNotFoundException ex) { // catch and handle the exception here
ex.printStackTrace(); // print the stack trace
}
}
}

Formatted Output to Text File


Java SE 5.0 also introduced a so-called Formatter for formatted output (just like Scanner for formatted input). A Formatter has a method called format(). The
format() method has the same syntax as printf(), i.e., it could use format specifiers to specify the format of the arguments. Again, you need to handle the
FileNotFoundException.

/**
* Output to File.
* Technique 1: Declare "throws FileNotFoundException" in the enclosing main() method
*/
import java.io.File;
import java.util.Formatter; // <== note
import java.io.FileNotFoundException; // <== note
public class TextFileFormatterWithThrows {
public static void main(String[] args)
throws FileNotFoundException { // <== note
// Construct a Formatter to write formatted output to a text file
Formatter out = new Formatter(new File("out.txt"));
// Write to file with format() method (similar to printf())
int num1 = 1234;
double num2 = 55.66;
String name = "Paul";
out.format("Hi %s,%n", name);
out.format("The sum of %d and %.2f is %.2f%n", num1, num2, num1 + num2);
out.close(); // Close the file
System.out.println("Done"); // Print to console
}
}

Run the above program, and check the outputs in text file "out.txt".

/**
* Output to File.

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 66/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
* Technique 2: Use try-catch to handle exception
*/
import java.io.File;
import java.util.Formatter; // <== note
import java.io.FileNotFoundException; // <== note

public class TextFileFormatterWithCatch {


public static void main(String[] args) {
try { // try the following statements
// Construct a Formatter to write formatted output to a text file
Formatter out = new Formatter(new File("out.txt"));
// Write to file with format() method (similar to printf())
int num1 = 1234;
double num2 = 55.66;
String name = "Pauline";
out.format("Hi %s,%n", name);
out.format("The sum of %d and %.2f is %.2f%n", num1, num2, num1 + num2);
out.close(); // Close the file
System.out.println("Done"); // Print to console
} catch (FileNotFoundException ex) { // catch the exception here
ex.printStackTrace(); // Print the stack trace
}
}
}

Input via a Dialog Box


You can also get inputs from users via a graphical dialog box, using the JOptionPane class. For example, the following
program prompts the user to enter the radius of a circle, and computes the area.

/**
* Input via a Dialog box
*/
import javax.swing.JOptionPane; // Needed to use JOptionPane
public class JOptionPaneTest {
public static void main(String[] args) {
String radiusStr;
double radius, area;
// Read input String from dialog box

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 67/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
radiusStr = JOptionPane.showInputDialog("Enter the radius of the circle");
radius = Double.parseDouble(radiusStr); // Convert String to double
area = radius*radius*Math.PI;
System.out.println("The area is " + area);
}
}

Dissecting the Program:


In Line 4, the import statement is needed to use the JOptionPane.
In Line 10, we use the method JOptionPane.showInputDialog(promptMessage) to prompt users for an input, which returns the input as a String.
Line 11 converts the input String to a double, using the method Double.parseDouble().

java.io.Console (JDK 1.6)


Java SE 6 introduced a new java.io.Console class to simplify character-based input/output to/from the system console. BUT, the Console class does not run under IDE
(such as Eclipse/NetBeans)!!!

To use the new Console class, you first use System.console() to retrieve the Console object corresponding to the current system console.

Console con = System.console();

You can then use methods such as readLine() to read a line. You can optionally include a prompting message with format specifiers (e.g., %d, %s) in the prompting
message.

String inLine = con.readLine();


String msg = con.readLine("Enter your message: "); // readLine() with prompting message
String msg = con.readLine("%s, enter message: ", name); // Prompting message with format specifier

You can use con.printf() for formatted output with format specifiers such as %d, %s. You can also connect the Console to a Scanner for formatted input, i.e., parsing
primitives such as int, double, for example,

Scanner in = new Scanner(con.reader()); // Use Scanner to scan the Console


// Use the Scanner's methods such as nextInt(), nextDouble() to parse primitives
int anInt = in.nextInt();
double aDouble = in.nextDouble();
String str = in.next();
String line = in.nextLine();

Example:

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 68/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial

/*
* Testing java.io.Console class
*/
import java.io.Console;
import java.util.Scanner;
public class ConsoleTest {
public static void main(String[] args) {
Console con = System.console(); // Retrieve the Console object
// Console class does not work in Eclipse/NetBeans
if (con == null) {
System.err.println("Console Object is not available.");
System.exit(1);
}

// Read a line with a prompting message


String name = con.readLine("Enter your Name: ");
con.printf("Hello %s%n", name);
// Use the console with Scanner for parsing primitives
Scanner in = new Scanner(con.reader());
con.printf("Enter an integer: ");
int anInt = in.nextInt();
con.printf("The integer entered is %d%n", anInt);
con.printf("Enter a floating point number: ");
double aDouble = in.nextDouble();
con.printf("The floating point number entered is %f%n", aDouble);
in.close();
}
}

The Console class also provides a secure mean for password entry via method readPassword(). This method disables input echoing and keep the password in a
char[] instead of a String. The char[] containing the password can be and should be overwritten, removing it from memory as soon as it is no longer needed. (Recall
that Strings are immutable and cannot be overwritten. When they are longer needed, they will be garbage-collected at an unknown instance.)

import java.io.Console;
import java.util.Arrays;
/**
* Inputting password via Console
*/
public class ConsolePasswordTest {
static String login;
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 69/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
static char[] password;

public static void main(String[] args) {


Console con = System.console();
if (con == null) {
System.err.println("Console Object is not available.");
System.exit(1);
}

login = con.readLine("Enter your login Name: ");


password = con.readPassword("Enter your password: ");
if (checkPassword(login, password)) {
Arrays.fill(password, ' '); // Remove password from memory
// Continue ...

}
}

static boolean checkPassword(String login, char[] password) {


return true;
}
}

Writing Correct and Good Programs


It is important to write programs that produce the correct results. It is also important to write programs that others (and you yourself three days later) can understand, so that
the programs can be maintained. I call these programs good programs - a good program is more than a correct program.

Here are the suggestions:


Follow established convention so that everyone has the same basis of understanding. To program in Java, you MUST read the "Code Convention for the Java
Programming Language".
Format and layout of the source code with appropriate indents, white spaces and white lines. Use 3 or 4 spaces for indent, and blank lines to separate sections of code.
Choose good names that are self-descriptive and meaningful, e.g., row, col, size, xMax, numStudents. Do not use meaningless names, such as a, b, c, d. Avoid
single-alphabet names (easier to type but often meaningless), except common names likes x, y, z for coordinates and i for index.
Provide comments to explain the important as well as salient concepts. Comment your code liberally.
Write your program documentation while writing your programs.
Avoid unstructured constructs, such as break and continue, which are hard to follow.
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 70/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
Use "mono-space" fonts (such as Consolas, Courier New, Courier) for writing/displaying your program.

It is estimated that over the lifetime of a program, 20 percent of the effort will go into the original creation and testing of the code, and 80 percent of the effort will go into the
subsequent maintenance and enhancement. Writing good programs which follow standard conventions is critical in the subsequent maintenance and enhancement!!!

Programming Errors: Compilation, Runtime and Logical Errors


There are generally three classes of programming errors:
1. Compilation Error (or Syntax Error): The program cannot compile. This can be fixed easily by checking the compilation error messages. For examples,

// System instead of Sys


Sys.out.print("Hello");
error: package Sys does not exist
Sys.out.print("Hello");
^

// Missing semi-colon
System.out.print("Hello")
error: ';' expected
System.out.print("Hello")
^

2. Runtime Error: The program can compile, but fail to run successfully. This can also be fixed easily, by checking the runtime error messages. For examples,
// Divide by 0 Runtime error
int count = 0, sum = 100, average;
average = sum / count;
Exception in thread "main" java.lang.ArithmeticException: / by zero

// Wrong conversion code, %d for integer


System.out.printf("The sum is: %d%n", 1.23);
Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.Double

3. Logical Error: The program can compile and run, but produces incorrect results (always or sometimes). This is the hardest error to fix as there is no error messages -
you have to rely on checking the output. It is easy to detect if the program always produces wrong output. It is extremely hard to fix if the program produces the correct
result most of the times, but incorrect result sometimes. For example,
// Can compile and run, but give wrong result – sometimes!
if (mark > 50) {
System.out.println("PASS");
} else {

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 71/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
System.out.println("FAIL");
}
This kind of errors is very serious if it is not caught before production. Writing good programs helps in minimizing and detecting these errors. A good testing strategy is
needed to ascertain the correctness of the program. Software testing is an advanced topics which is beyond our current scope.

Debugging Programs
Here are the common debugging techniques:
1. Stare at the screen! Unfortunately, nothing will pop-up even if you stare at it extremely hard.
2. Study the error messages! Do not close the console when error occurs and pretending that everything is fine. This helps most of the times.
3. Insert print statements at appropriate locations to display the intermediate results. It works for simple toy program, but it is neither effective nor efficient for complex
program.
4. Use a graphic debugger. This is the most effective means. Trace program execution step-by-step and watch the value of variables and outputs.
5. Advanced tools such as profiler (needed for checking memory leak and method usage).
6. Perform program testing to wipe out the logical errors. "Write test first, before writing program".

Exercises on Decision/Loop with Input


LINK

Testing Your Program for Correctness


How to ensure that your program always produces correct result, 100% of the times? It is impossible to try out all the possible outcomes, even for a simple program for
adding two integers (because there are too many combinations of two integers). Program testing usually involves a set of representative test cases, which are designed to
catch all classes of errors. Program testing is beyond the scope of this writing.

More on Loops - Nested-Loops, break & continue

Nested Loops
Nested loops are needed to process 2-dimensional (or N-dimensional) data, such as printing 2D patterns. A nested-for-loop takes the following form:

for (...; ...; ...) { // outer loop


// Before running the inner loop
......
for (...; ...; ...) { // inner loop
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 72/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
......
}
// After running the inner loop
......
}

Code Examples: Print Square Pattern


The following program prompt user for the size of the pattern, and print a square pattern using nested-loops. For example,

Enter the size: 5


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

import java.util.Scanner;
/**
* Prompt user for the size; and print Square pattern
*/
public class PrintSquarePattern {
public static void main (String[] args) {
// Declare variables

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 73/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
final int SIZE; // size of the pattern to be input

// Prompt user for the size and read input as "int"


Scanner in = new Scanner(System.in);
System.out.print("Enter the size: ");
SIZE = in.nextInt();
in.close();

// Use nested-loop to print a 2D pattern


// Outer loop to print ALL the rows
for (int row = 1; row <= SIZE; row++) {
// Inner loop to print ALL the columns of EACH row
for (int col = 1; col <= SIZE; col++) {
System.out.print("* ");
}
// Print a newline after all the columns
System.out.println();
}
}
}

This program contains two nested for-loops. The inner loop is used to print a row of "* ", which is followed by printing a newline. The outer loop repeats the inner loop to
print all the rows.

Coding Pattern: Print 2D Patterns


The coding pattern for printing 2D patterns is as follows. I recommend using row and col as the loop variables which is self-explanatory, instead of i and j, x and y.

for (int row = 1; row <= ROW_SIZE; row++) { // outer loop for rows
...... // before each row
for (int col = 1; col <= COL_SIZE; col++) { // inner loop for columns
if (......) {
System.out.print(......); // without newline
} else {
System.out.print(......);
}
}
...... // after each row
System.out.println(); // Print a newline after all the columns
}

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 74/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial

Code Examples: Print Checker Board Pattern


Suppose that you want to print this pattern instead (in program called PrintCheckerPattern):

Enter the size: 6


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

You need to print an additional space for even-number rows. You could do so by adding the following statement before the inner loop.

if ((row % 2) == 0) { // print a leading space for even-numbered rows


System.out.print(" ");
}

Code Example: Print Multiplication Table


The following program prompts user for the size, and print the multiplication table as follows:

Enter the size: 10


* | 1 2 3 4 5 6 7 8 9 10
--------------------------------------------
1 | 1 2 3 4 5 6 7 8 9 10
2 | 2 4 6 8 10 12 14 16 18 20
3 | 3 6 9 12 15 18 21 24 27 30
4 | 4 8 12 16 20 24 28 32 36 40
5 | 5 10 15 20 25 30 35 40 45 50
6 | 6 12 18 24 30 36 42 48 54 60
7 | 7 14 21 28 35 42 49 56 63 70
8 | 8 16 24 32 40 48 56 64 72 80
9 | 9 18 27 36 45 54 63 72 81 90
10 | 10 20 30 40 50 60 70 80 90 100

import java.util.Scanner;
/**
* Prompt user for the size and print the multiplication table.
*/
public class PrintTimeTable {
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 75/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
public static void main(String[] args) {
// Declare variables
final int SIZE; // size of table to be input

// Prompt for size and read input as "int"


Scanner in = new Scanner(System.in);
System.out.print("Enter the size: ");
SIZE = in.nextInt();
in.close();

// Print header row


System.out.print(" * |");
for (int col = 1; col <= SIZE; ++col) {
System.out.printf("%4d", col);
}
System.out.println(); // End row with newline
// Print separator row
System.out.print("----");
for (int col = 1; col <= SIZE; ++col) {
System.out.printf("%4s", "----");
}
System.out.println(); // End row with newline

// Print body using nested-loops


for (int row = 1; row <= SIZE; ++row) { // outer loop
System.out.printf("%2d |", row); // print row header first
for (int col = 1; col <= SIZE; ++col) { // inner loop
System.out.printf("%4d", row*col);
}
System.out.println(); // print newline after all columns
}
}
}

TRY:
1. Write programs called PrintPattern1x, which prompts user for the size and prints each these patterns.

# * # * # * # * # # # # # # # # # # # # # # # # 1 1
# * # * # * # * # # # # # # # # # # # # # # 2 1 1 2
# * # * # * # * # # # # # # # # # # # # 3 2 1 1 2 3
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 76/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
# * # * # * # * # # # # # # # # # # 4 3 2 1 1 2 3 4
# * # * # * # * # # # # # # # # 5 4 3 2 1 1 2 3 4 5
# * # * # * # * # # # # # # 6 5 4 3 2 1 1 2 3 4 5 6
# * # * # * # * # # # # 7 6 5 4 3 2 1 1 2 3 4 5 6 7
# * # * # * # * # # 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8
(a) (b) (c) (d) (e)
Hints:
The equations for major and opposite diagonals are row = col and row + col = size + 1. Decide on what to print above and below the diagonal.
2. Write programs called PrintPattern2x, which prompts user for the size and prints each of these patterns.

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
(a) (b) (c) (d) (e)

Exercises on Nested Loops with Input


LINK

break and continue - Interrupting Loop Flow


The break statement breaks out and exits the current (innermost) loop.

The continue statement aborts the current iteration and continue to the next iteration of the current (innermost) loop.

break and continue are poor structures as they are hard to read and hard to follow. Use them only if absolutely necessary.

Endless loop
for ( ; ; ) { body } is known as an empty for-loop, with empty statement for initialization, test and post-processing. The body of the empty for-loop will execute
continuously (infinite loop). You need to use a break statement to break out the loop.

Similar, while (true) { body } and do { body } while (true) are endless loops.

for (;;) {
...... // Need break inside the loop body
}

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 77/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial

while (true) {
...... // Need break inside the loop body
}

do {
...... // Need break inside the loop body
} while (true);

Endless loop is typically a mistake especially for new programmers. You need to break out the loop via a break statement inside the loop body..

Example (break): The following program lists the non-prime numbers between 2 and an upperbound.
/**
* List all non-prime numbers between 2 and an upperbound
*/
public class NonPrimeList {
public static void main(String[] args) {
final int UPPERBOUND = 100;
for (int number = 2; number <= UPPERBOUND; ++number) {
// Not a prime, if there is a factor between 2 and sqrt(number)
int maxFactor = (int)Math.sqrt(number);
for (int factor = 2; factor <= maxFactor; ++factor) {
if (number % factor == 0) { // Factor?
System.out.println(number + " is NOT a prime");
break; // A factor found, no need to search for more factors
}
}
}
}
}

Let's rewrite the above program to list all the primes instead. A boolean flag called isPrime is used to indicate whether the current number is a prime. It is then used to
control the printing.

/**
* List all prime numbers between 2 and an upperbound
*/
public class PrimeListWithBreak {
public static void main(String[] args) {
final int UPPERBOUND = 100;

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 78/130

You might also like