Java Basics-Páginas-3
Java Basics-Páginas-3
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.
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
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,
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,
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
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:
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);
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
// 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())
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).
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
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,
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
// Compute sum
sum = number1 + number2;
// Display result
System.out.println("The sum is: " + sum); // Print with newline
}
}
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.
// Declare variables
int taxableIncome;
double taxPayable;
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
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.)
// Declare variables
int taxableIncome;
double taxPayable;
Notes:
1. The coding pattern for handling input with sentinel (terminating) value is as follows:
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
}
......
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);
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
}
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
}
}
}
/**
* 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
/**
* 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);
}
}
To use the new Console class, you first use System.console() to retrieve the Console object corresponding to the current 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.
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,
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);
}
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;
}
}
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!!!
// 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
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".
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:
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
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.
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
You need to print an additional space for even-number rows. You could do so by adding the following statement before the inner loop.
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
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)
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