Programming Fundamentals I (COSC- 1336), Lecture 2 (prepared after Chapter 2 of Liang’s 2011 textbook) Stefan Andrei 10/17/20151 COSC-1336, Lecture 2
Overview of the previous lecture To review computer basics, programs, and operating systems (§§ ). To explore the relationship between Java and the World Wide Web (§1.5). To distinguish the terms API, IDE, and JDK (§1.6). To write a simple Java program (§1.7). To display output on the console (§1.7). To explain the basic syntax of a Java program (§1.7). To create, compile, and run Java programs (§1.8). (GUI) To display output using the JOptionPane output dialog boxes (§1.9). 10/17/20152 COSC-1336, Lecture 2
Connection with current lecture In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from this chapter, you will learn how to solve practical problems programmatically. Through these problems, you will learn Java primitive data types and related subjects, such as variables, constants, data types, operators, expressions, and input and output. 10/17/20153 COSC-1336, Lecture 2
Overview of This Lecture To write Java programs to perform simple calculations (§2.2). To obtain input from the console using the Scanner class (§2.3). To use identifiers to name variables, constants, methods, and classes (§2.4). To use variables to store data (§§ ). To program with assignment statements and assignment expressions (§2.6). To use constants to store permanent data (§2.7). To declare Java primitive data types: byte, short, int, long, float, double, and char (§§2.8.1). To use Java operators to write numeric expressions (§§2.8.2–2.8.3). To display current time (§2.9). 10/17/20154 COSC-1336, Lecture 2
Overview of This Lecture (cont) To use short hand operators (§2.10). To cast value of one type to another type (§2.11). To compute loan payment (§2.12). To represent characters using the char type (§2.13). To compute monetary changes (§2.14). To represent a string using the String type (§2.15). To become familiar with Java documentation, programming style, and naming conventions (§2.16). To distinguish syntax errors, runtime errors, and logic errors and debug errors (§2.17). (GUI) To obtain input using the JOptionPane input dialog boxes (§2.18). 10/17/20155 COSC-1336, Lecture 2
Introducing Programming with an Example Listing 2.1. Computing the Area of a Circle This program computes the area of the circle. 10/17/20156 COSC-1336, Lecture 2
Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * ; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } no value radius allocate memory for radius animation 10/17/20157 COSC-1336, Lecture 2
Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * ; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } no value radius memory no value area allocate memory for area animation 10/17/20158 COSC-1336, Lecture 2
Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * ; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } 20 radius no value area assign 20 to radius animation 10/17/20159 COSC-1336, Lecture 2
Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * ; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } 20 radius memory area compute area and assign it to variable area animation 10/17/ COSC-1336, Lecture 2
Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * ; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } 20 radius memory area print a message to the console animation 10/17/ COSC-1336, Lecture 2
Reading Input from the Console 1. Create a Scanner object Scanner input = new Scanner(System.in); 2. Use the methods next(), nextByte(), nextShort(), nextInt(), nextLong(), nextFloat(), nextDouble(), or nextBoolean() to obtain to a string, byte, short, int, long, float, double, or boolean value. For example, System.out.print("Enter a double value: "); Scanner input = new Scanner(System.in); double d = input.nextDouble(); 10/17/ COSC-1336, Lecture 2
ComputeAreaWithConsoleInput.java import java.util.Scanner; // Scanner is in the java.util package public class ComputeAreaWithConsoleInput { public static void main(String[] args) { // Create a Scanner object Scanner input = new Scanner(System.in); // Prompt the user to enter a radius System.out.print("Enter a number for radius:"); double radius = input.nextDouble(); double area = radius * radius * ; System.out.println("Area of circle of radius " + radius + " is " + area); } 10/17/ COSC-1336, Lecture 2
Compiling and running ComputeAreaWithConsoleInput.java 10/17/ COSC-1336, Lecture 2
Identifiers An identifier is a sequence of characters that consist of letters, digits, underscores ( _ ), and dollar signs ( $ ). An identifier must start with a letter, an underscore ( _), or a dollar sign ( $ ). It cannot start with a digit. An identifier cannot be a reserved word. (See Appendix A, “Java Keywords,” for a list of reserved words). An identifier cannot be true, false, or null. An identifier can be of any length. 10/17/ COSC-1336, Lecture 2
Variables // Compute the first area radius = 1.0; area = radius * radius * ; System.out.println("The area is " + area + " for radius "+radius); // Compute the second area radius = 2.0; area = radius * radius * ; System.out.println("The area is " + area + " for radius "+radius); 10/17/ COSC-1336, Lecture 2
Declaring Variables int x; // Declare x to be an // integer variable; double radius; // Declare radius to // be a double variable; char a; // Declare a to be a // character variable; 10/17/ COSC-1336, Lecture 2
Assignment Statements x = 1; // Assign 1 to x; radius = 1.0; // Assign 1.0 to radius; a = 'A'; // Assign 'A' to a; 10/17/ COSC-1336, Lecture 2
Declaring and Initializing in One Step int x = 1; double d = 1.4; 10/17/ COSC-1336, Lecture 2
Constants The general syntax of declaring and defining a constant is: final = ; where final is the modifier, is the data type of the constant, is the name of the constant (it is recommended to be with capital letters), and is its value (which of course, it cannot be modified). Example: final double PI = ; final int SIZE = 3; 10/17/ COSC-1336, Lecture 2
Numerical Data Types 10/17/ COSC-1336, Lecture 2
Binary, Octal, and Hexadecimal Bases Decimal base is the one we used every day: {0, 1, …, 9} Binary base: {0, 1} Examples: 1101 (2) = 1*2 3 +1*2 2 +0*2 1 +1*2 0 =13 (10) Octal base: {0, 1, …, 7} Example: 352 (8) = 3*8 2 +5*8 1 +2*8 0 =234 (10) Hexadecimal base: {0, …, 9, A, B, C, D, E, F} Where A means 10 (10), B means 11 (10), …, F means 15 (10). Example: 4BE (16) = 4* * *16 0 =1214 (10) 10/17/ COSC-1336, Lecture 2
Numeric Operators 10/17/ COSC-1336, Lecture 2
Integer Division +, -, *, /, and % 5 / 2 yields an integer / 2 yields a double value 2.5 5f / 2 yields a double value % 2 yields 1 (the remainder of the division) 10/17/ COSC-1336, Lecture 2
Remainder Operator Remainder is very useful in programming. For example: an even number % 2 is always 0 and an odd number % 2 is always 1. So you can use this property to determine whether a number is even or odd. Exercise: Suppose today is Saturday and you and your friends are going to meet in 10 days. What day is in 10 days? 10/17/ COSC-1336, Lecture 2
Remainder Operator: Solution of the Exercise You can find that day is Tuesday using the following expression: 10/17/ COSC-1336, Lecture 2
Calculating time and display it Write a program that obtains hours and minutes from seconds. 10/17/ COSC-1336, Lecture 2
Calculating hours and minutes import java.util.Scanner; public class DisplayTime { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter an integer for seconds:"); int seconds = input.nextInt(); int minutes = seconds / 60; int remainingSeconds = seconds % 60; System.out.println(seconds + " seconds is " + minutes + " minutes and " + remainingSeconds + " seconds"); } 10/17/ COSC-1336, Lecture 2
Editing, compiling, and running DisplayTime.java 10/17/ COSC-1336, Lecture 2
Problem: Displaying Current Time The currentTimeMillis() method in the System class returns the current time in milliseconds since the midnight, January 1, 1970 GMT. 1970 was the year when the Unix operating system was formally introduced. This method can be similarly used to obtain the current time, and then compute the current second, minute, and hour. 10/17/ COSC-1336, Lecture 2
Note Calculations involving floating-point numbers are approximated because these numbers are not stored with complete accuracy. Example: System.out.println( ); displays , not 0.5, and System.out.println( ); displays , not 0.1. Integers are stored precisely. Therefore, calculations with integers yield a precise integer result. 10/17/ COSC-1336, Lecture 2
Number Literals A literal is a constant value that appears directly in the program. For example, 34, 1,000,000, and 5.0 are literals in the following statements: int i = 34; long x = ; double d = 5.0; 10/17/ COSC-1336, Lecture 2
Integer Literals An integer literal can be assigned to an integer variable as long as it can fit into the variable. A compilation error would occur if the literal were too large for the variable to hold. For example, the statement byte b = 1000; would cause a compilation error, because 1000 cannot be stored in a variable of the byte type. 10/17/ COSC-1336, Lecture 2
Integer Literals (cont) An integer literal is assumed to be of the int type, whose value is between ( ) to 2 31 –1 ( ). To denote an integer literal of the long type, append it with the letter L or l. L is preferred because l (lowercase L ) can easily be confused with 1 (the digit one). 10/17/ COSC-1336, Lecture 2
Floating-Point Literals Floating-point literals are written with a decimal point. By default, a floating-point literal is treated as a double type value. For example, 5.0 is considered a double value, not a float value. You can make a number a float by appending the letter f or F, and make a number a double by appending the letter d or D. For example, you can use 100.2f or 100.2F for a float number, and 100.2d or 100.2D for a double number. 10/17/ COSC-1336, Lecture 2
Scientific Notation Floating-point literals can also be specified in scientific notation. For example, e+2, same as e2, is equivalent to , and e-2 is equivalent to The character E (or e ) means actually 10 and the value after E (or e ) represents an exponent e+2 = * 10 2 = /17/ COSC-1336, Lecture 2
Arithmetic Expressions is translated to (3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y) 10/17/ COSC-1336, Lecture 2
How to Evaluate an Expression? Though Java has its own way to evaluate an expression behind the scene, the result of a Java expression and its corresponding arithmetic expression are the same. Therefore, you can safely apply the arithmetic rule for evaluating a Java expression. 10/17/ COSC-1336, Lecture 2
Problem: Converting Temperatures Fahrenheit is the temperature scale proposed in 1724 by, and named after, the Dutch-German-Polish physicist Daniel Gabriel Fahrenheit (1686–1736). Today, the temperature scale has been replaced by the Celsius scale in most countries, but it remains the official scale of the United States and Belize and is retained as a secondary scale in Canada. The Celsius scale is named after the Swedish astronomer Anders Celsius (1701–1744), who developed a similar temperature scale in Write a program that converts a Fahrenheit degree to Celsius using the formula: 10/17/ COSC-1336, Lecture 2
FahrenheitToCelsius.java import java.util.Scanner; public class FahrenheitToCelsius { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a degree in Fahrenheit:"); double fahrenheit = input.nextDouble(); // Convert Fahrenheit to Celsius double celsius = (5.0 / 9) * (fahrenheit - 32); System.out.println("Fahrenheit " + fahrenheit + " is " + celsius + " in Celsius"); } 10/17/ COSC-1336, Lecture 2
Compiling and running FahrenheitToCelsius.java 10/17/ COSC-1336, Lecture 2
Shortcut Assignment Operators OperatorExampleEquivalent +=i += 8i = i + 8 -=f -= 8.0f = f *=i *= 8i = i * 8 /=i /= 8i = i / 8 %=i %= 8i = i % 8 X op= Y; is equivalent to X = X op (Y); 10/17/ COSC-1336, Lecture 2
Examples Example 1: int y = 5, x = 10; x += y + 1; How much is x ? Example 2: int y = 5, x = 10; x *= y + 1; How much is x ? 10/17/ COSC-1336, Lecture 2
Increment and Decrement Operators OperatorNameDescription ++var preincrementThe expression ( ++var ) increments var by 1 and evaluates to the new value in var after the increment. var++ postincrementThe expression ( var++ ) evaluates to the original value in var and increments var by 1. --var predecrementThe expression ( --var ) decrements var by 1 and evaluates to the new value in var after the decrement. var-- postdecrement The expression ( var-- ) evaluates to the original value in var and decrements var by 1. 10/17/ COSC-1336, Lecture 2
Increment and Decrement Operators (cont.) 10/17/ COSC-1336, Lecture 2
Increment and Decrement Operators (cont.) Using increment and decrement operators makes expressions short, but it also makes them complex and difficult to read. Avoid using these operators in expressions that modify multiple variables, or the same variable for multiple times such as this: int k = ++i + i; 10/17/ COSC-1336, Lecture 2
Increment and Decrement (cont) int count = 2; int x = count++; How much is x and count ? The value of x is 2 and the value of count is 3. int count = 2; int x = ++count ; How much is x and count ? The value of x is 3 and the value of count is 3. int count1 = 2, count2 = 3; int x = count count2; How much is x, count1, and count2 ? The value of x is 6 and the values of count1 and count2 are 3 and 4. int count1 = 2, count2 = 3; int x = count1++ + count2++; How much is x ? The value of x is 5 and the values of count1 and count2 are 3 and 4. 10/17/ COSC-1336, Lecture 2
Numeric Type Conversion Consider the following statements: byte i = 100; long k = i * 3 + 4; double d = i * k / 2; 10/17/ COSC-1336, Lecture 2
Conversion Rules When performing a binary operation involving two operands of different types, Java automatically converts the operand based on the following rules: 1. If one of the operands is double, the other is converted into double. 2. Otherwise, if one of the operands is float, the other is converted into float. 3. Otherwise, if one of the operands is long, the other is converted into long. 4. Otherwise, both operands are converted into int. 10/17/ COSC-1336, Lecture 2
Type Casting Implicit casting: double d = 3; // type widening Explicit casting: int i = (int)3.0; // type narrowing int i = (int)3.9; // Fraction part is // truncated What is wrong? int x = 5 / 2.0; 10/17/ COSC-1336, Lecture 2
Highlighting casting The following Java statements: double x = 3.45; int a = x; will lead to a compile-time error (“ found double, required int ”). However, we can use cast to avoid the error, but: double x = 3.45; int a = (int) x; Precision will be lost ! 10/17/ COSC-1336, Lecture 2
More examples on casting if total and count are doubles, and we want an integer result when dividing them, we can cast to int. The result will be loss of precision. For example: double total = 8.20; double count = 3.20; int result = (int) (total / count); How much is result ? 2 10/17/ COSC-1336, Lecture 2
The Unicode Consortium Java characters use Unicode. Originally, Unicode used a 16-bit encoding scheme established by the Unicode Consortium to support the interchange, processing, and display of written texts in the world’s diverse languages (65,536 characters). Later, the Unicode standard has been extended to 1,112,064 characters – beyond the scope of this course! 10/17/2015 COSC-1336, Lecture 2 53
Unicode Format The standard Unicode takes two bytes, preceded by \u, expressed in four hexadecimal numbers that run from '\u0000' to '\uFFFF'. So, the standard Unicode can represent characters. Unicode \u03b1 \u03b2 \u03b3 for three Greek letters. 10/17/ COSC-1336, Lecture 2
Problem: Displaying Unicodes Write a program that displays two Chinese characters and three Greek letters. 10/17/ COSC-1336, Lecture 2
DisplayUnicode.java import javax.swing.JOptionPane; public class DisplayUnicode { public static void main(String[] args) { JOptionPane.showMessageDialog(null, "\u6B22\u8FCE \u03b1 \u03b2 \u03b3", "\u6B22\u8FCE Welcome", JOptionPane.INFORMATION_MESSAGE); } 10/17/ COSC-1336, Lecture 2
Compiling and running DisplayUnicode.java 10/17/ COSC-1336, Lecture 2
Character Data Type char letter = 'A'; (ASCII) char numChar = '4'; (ASCII) char letter = '\u0041'; (Unicode) char numChar = '\u0034'; (Unicode) Four hexadecimal digits. 10/17/ COSC-1336, Lecture 2
More on ASCII and Unicode The ASCII character set (American Standard Code Information Interchange) is older and smaller than Unicode, but is still quite popular. NOTE: The increment and decrement operators can also be used on char variables to get the next or preceding Unicode character. For example, the below statements display character b. char ch = 'a'; System.out.println(++ch); 10/17/ COSC-1336, Lecture 2
More about numeric operators and char s The other numeric operators cannot be directly used to get a char (like for ++ and -- operators). A char operand is automatically cast to a number if the other operand is a number or a char. Example: the below code will lead to a syntax error as there is no ‘ + ’ operator for char type. char x = '2'; char y = '0'; char z = x + y; 10/17/2015 COSC-1336, Lecture 2 60
More on ‘ + ’ operator for char s To fix the previous error, we can cast the obtained number to a char. char x = '2'; char y = '0'; char z = (char) (x + y); System.out.println(z); will display b Question: What the below code will display? char x = '2'; char y = '0'; char z = (char) x + y; System.out.println(z); 10/17/2015 COSC-1336, Lecture 2 61
More on ‘ + ’ operator for char s (cont.) How about the code? char x = '2'; char y = '0'; char z = (char) x + (char) y; System.out.println(z); How about this? int x = '2'; int y = '0'; int z = x + y; System.out.println((char) z); 10/17/2015 COSC-1336, Lecture 2 62
Casting between char and Numeric Types int i = 'a'; // Same as int i = (int)'a'; char c = 97; // Same as char c = (char)97; 10/17/ COSC-1336, Lecture 2
Escape Sequences for Special Characters Description Escape Sequence Unicode Backspace \b\u0008 Tab \t\u0009 Linefeed \n\u000A Carriage return \r\u000D Backslash \\\u005C Single Quote \ ' \u0027 Double Quote \ " \u /17/ COSC-1336, Lecture 2
Appendix B: ASCII Character Set ASCII Character Set is a subset of the Unicode from \u0000 to \u007f 10/17/ COSC-1336, Lecture 2
ASCII Character Set, cont. The ASCII Character Set is a subset of the Unicode from \u0000 to \u007f 10/17/ COSC-1336, Lecture 2
The String Type The char type only represents one character. To represent a string of characters, use the data type called String. For example, String message = "Welcome to Java"; String is actually a predefined class in the Java library just like the System class and JOptionPane class. The String type is not a primitive type. It is known as a reference type. 10/17/ COSC-1336, Lecture 2
The String Type (cont.) Any Java class can be used as a reference type for a variable. Reference data types will be thoroughly discussed in Chapter 7, “Objects and Classes.” For the time being, you just need to know how to declare a String variable, how to assign a string to the variable, and how to concatenate strings. 10/17/ COSC-1336, Lecture 2
String Concatenation // Three strings are concatenated String message = "Welcome " + "to " + "Java"; // String Chapter is concatenated with number 2 String s = "Chapter" + 2; // s becomes Chapter2 // String Supplement is concatenated with character B String s1 = "Supplement" + 'B'; // s1 becomes SupplementB 10/17/ COSC-1336, Lecture 2
2.1 – String Concatenation The + operator is also used for arithmetic addition. The function that it performs depends on the type of the information on which it operates. If both operands are String s, or if one is a String and one is a number, it performs String concatenation. If both operands are numeric, it adds them. The + operator is evaluated left to right, but parentheses can be used to force the order. 10/17/ COSC-1336, Lecture 2
More on the ‘ + ’ semantics Operand1 + Operand2 + Operand3 = (Operand1 + Operand2) + Operand3 Example: "Maes " = ("Maes " + 107) Since "Maes " is of type String and 107 is of type int, then 107 is converted to a String. Hence ("Maes " + 107) = "Maes 107 " This is equal to "Maes " " Maes" = ( ) + " Maes" Since both 107 and 111 are of type int, there is no need for any conversion, thus the answer is 218. Hence ( ) + " Maes" = "218 Maes" 10/17/ COSC-1336, Lecture 2
Programming Style and Documentation Appropriate Comments Naming Conventions Proper Indentation and Spacing Lines Block Styles 10/17/ COSC-1336, Lecture 2
Appropriate Comments Include a summary at the beginning of the program to explain what the program does, its key features, its supporting data structures, and any unique techniques it uses. Include your name, class section, instructor, date, and a brief description at the beginning of the program. 10/17/ COSC-1336, Lecture 2
Naming Conventions Choose meaningful and descriptive names. Variables and method names: Use lowercase. If the name consists of several words, concatenate all in one, use lowercase for the first word, and capitalize the first letter of each subsequent word in the name. For example, the variables radius and area, and the method computeArea(). 10/17/ COSC-1336, Lecture 2
Naming Conventions (cont.) Class names: Capitalize the first letter of each word in the name. For example, the class name ComputeArea. Constants: Capitalize all letters in constants, and use underscores to connect words. For example, PI and MAX_VALUE are good names for constants. 10/17/ COSC-1336, Lecture 2
Proper Indentation and Spacing Indentation Indent two spaces. Spacing Use blank line to separate segments of the code. 10/17/ COSC-1336, Lecture 2
Block Styles Use end-of-line style for braces. 10/17/ COSC-1336, Lecture 2
Programming Errors Syntax Errors Detected by the compiler Runtime Errors Causes the program to abort Logic Errors Produces incorrect result Question: Which of the errors are considered the most dangerous? 10/17/ COSC-1336, Lecture 2
Syntax Errors – can you find it? public class ShowSyntaxErrors { public static void main(String[] args) { i = 30; System.out.println(i + 4); } 10/17/ COSC-1336, Lecture 2
Runtime Errors – can you find it? import java.util.Scanner; public class ShowRuntimeErrors { public static void main(String[] args) { System.out.print("Enter an integer: "); Scanner input = new Scanner(System.in); int d = input.nextInt(); int i = 1 / d; } 10/17/ COSC-1336, Lecture 2
Logic Errors – can you find it? import javax.swing.JOptionPane; public class ShowLogicErrors { // Determine if a number is between 1 and 100 inclusively public static void main(String[] args) { // Prompt the user to enter a number String input = JOptionPane.showInputDialog(null, "Please enter an integer:", "ShowLogicErrors", JOptionPane.QUESTION_MESSAGE); int number = Integer.parseInt(input); System.out.println("The number is between 1 and 100, " + "inclusively? " + ((1 < number) && (number < 100))); System.exit(0); } 10/17/ COSC-1336, Lecture 2
Debugging Logic errors are called ‘bugs’. The process of finding and correcting errors is called debugging. A common approach to debugging is to use a combination of methods to narrow down to the part of the program where the bug is located. 10/17/ COSC-1336, Lecture 2
Debugging (cont.) You can hand-trace the program in order to show the values of the variables or the execution flow of the program: You can catch errors by reading the program, or You can insert print() statements (spies). This approach might work for a short, simple program. But for a large, complex program, the most effective approach for debugging is to use a debugger utility. 10/17/ COSC-1336, Lecture 2
Debugger A debugger is a program that facilitates debugging. You can use a debugger to: Execute a single statement at a time. Trace into or stepping over a method. Set breakpoints. Display variables. Display call stack. Modify variables. 10/17/ COSC-1336, Lecture 2
The JOptionPane Input This lesson provides two ways of obtaining input: 1. Using the Scanner class (console input) 2. Using JOptionPane input dialogs 10/17/ COSC-1336, Lecture 2
Getting Input from Input Dialog Boxes String input = JOptionPane.showInputDialog( "Enter an input"); 10/17/ COSC-1336, Lecture 2
Getting Input from Input Dialog Boxes String string = JOptionPane.showInputDialog( null, "Enter a year", "Example 2.2 Input", JOptionPane.QUESTION_MESSAGE); 10/17/ COSC-1336, Lecture 2
Two Ways to Invoke the Method There are several ways to use the showInputDialog() method. For the time being, you only need to know two ways to invoke it. One is to use a statement as shown in the example: String string = JOptionPane.showInputDialog(null, x, y, JOptionPane.QUESTION_MESSAGE); where x is a String for the prompting message, and y is a String for the title of the input dialog box. 10/17/ COSC-1336, Lecture 2
The other way to invoke the method The other is to use a statement like this: JOptionPane.showInputDialog(x); where x is a String for the prompting message. 10/17/ COSC-1336, Lecture 2
Converting String s to int s The input returned from the input dialog box is a String. If you enter a numeric value such as 123, it returns "123". To obtain the input as a number, you have to convert a String into a number. To convert a String into an int value, you can use the static parseInt() method in the Integer class as follows: int intValue = Integer.parseInt(intString); where intString is a numeric String such as "123". 10/17/ COSC-1336, Lecture 2
Converting String s to double s To convert a String into a double value, you can use the static parseDouble() method in the Double class as follows: double doubleValue=Double.parseDouble(doubleString); where doubleString is a numeric string such as "23.45". 10/17/ COSC-1336, Lecture 2
Summary To write Java programs to perform simple calculations (§2.2). To obtain input from the console using the Scanner class (§2.3). To use identifiers to name variables, constants, methods, and classes (§2.4). To use variables to store data (§§ ). To program with assignment statements and assignment expressions (§2.6). To use constants to store permanent data (§2.7). To declare Java primitive data types: byte, short, int, long, float, double, and char (§§2.8.1). To use Java operators to write numeric expressions (§§2.8.2–2.8.3). To display current time (§2.9). 10/17/ COSC-1336, Lecture 2
Summary (cont) To use short hand operators (§2.10). To cast value of one type to another type (§2.11). To compute loan payment (§2.12). To represent characters using the char type (§2.13). To compute monetary changes (§2.14). To represent a string using the String type (§2.15). To become familiar with Java documentation, programming style, and naming conventions (§2.16). To distinguish syntax errors, runtime errors, and logic errors and debug errors (§2.17). (GUI) To obtain input using the JOptionPane input dialog boxes (§2.18). 10/17/ COSC-1336, Lecture 2
Reading suggestions From [Liang: Introduction to Java programming: Eight Edition, 2011 Pearson Education, ] Chapter 2 (Elementary Programming) 10/17/ COSC-1336, Lecture 2
Coming up next From [Liang: Introduction to Java programming: Eight Edition, 2011 Pearson Education, ] Chapter 3 (Selections) 10/17/ COSC-1336, Lecture 2
Thank you for your attention! Questions? 10/17/ COSC-1336, Lecture 2