Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Introduction to Programming Session 2 Point Park University CMPS 322 Summer 2008 Q1 Summer 2008 Q1 Version 1.2 1 Questions Questions and issues for last week's topics. Any issues with Netbeans? Summer 2008 Q1 Version 1.2 2 Java Data Types Text reference begins at Page 34. Java variables fall into two categories: – Intrinsic data types. byte, short, int, long char double, float boolean – Intrinsic types are declared in this manner: int myvar1; double total = 0.0; Summer 2008 Q1 Version 1.2 3 Java Data Types The second category of Java variables are known as reference variables. The data types of reference variables a Java classes. Variables to store string data are reference variables. When we declare them, they actually aren’t ready to use yet. We must initialize them by tying them to an instance of the class. String myname; // This is an unintialized variable. myname = new String(“Fred Flintstone”); String yourname = new String(); Summer 2008 Q1 Version 1.2 // An empty string. 4 Declaring Variables Your programs will need to be able to store data in them for computation and processing. This will necessitate that you declare variables. Variables are storage locations in memory that you can refer to by a name that has meaning to you for the context of the application. Variables are declared by selecting data type and variable name: int myintvalue, j, k3; double salary = 10000.0; Note initialization syntax. Summer 2008 Q1 Version 1.2 5 Declaring Variables Variables are not initialized automatically. Use of a variable before initialization is illegal in Java. May be initialized at time of declaration, or via assignment statement. double salary = 10000.0; salary = 22000.0; Summer 2008 Q1 Version 1.2 6 Java Variable Names Variable names or identifiers: – Can contain letters, digits, underscores and dollar signs. – Must start with letter, underscore or dollar sign. (Not a digit.) – Cannot be a reserved word. See Appendix A of text for list of reserved words. – Cannot be true, false or null. – Have no limit to length. int myvar1; double total = 0.0; String _StudentNameValue; int ___placemarker; Summer 2008 Q1 Version 1.2 7 Arithmetic Expressions Most programs will need to support numeric calculations. This is accomplished via statements that combine variables with the arithmetic operators. – +, -, *, /, %. These operators are the binary operators. – They require left and right operands. There are also a number of unary operators, notably: – ++, --, +=, -=, *=, /=. The complete set of Java operators, and their precedence, is shown on Page 86. Summer 2008 Q1 Version 1.2 8 Type Casting Type casting involves stating what your target data type is. Syntax is to place target data type within parentheses, in front of data to be converted. int j; j = (int) 3.24; Summer 2008 Q1 Version 1.2 9 Formatting Numbers Unless you request it, numeric output is raw and often ugly. Formatting numbers in Java is not hard, but it is not intuitive. Must make use of the NumberFormat object. We create a variable that acts as the formatting tool. When we want to display the number formatted, as ask the tool to do its job. NumberFormat numberformat = NumberFormat.getInstance(Locale.US); System.out.print(numberformat.format(dblFarenheit)); Summer 2008 Q1 Version 1.2 10 Formatting Numbers Must import the java.util.NumberFormat package, or java.util.*. There are different types of formatting instances available to you. – Each customized to different types of numbers. form form form form = = = = NumberFormat.getInstance(); NumberFormat.getIntegerInstance(); NumberFormat.getCurrencyInstance(); NumberFormat.getPercentInstance(); NumberFormat also supports several methods to control such things as number of decimal places. form.setMaximumFractionDigits(2); form.setMinimumFractionDigits(2); See the Java Online documentation for full information. See the solutions to last weeks in-class work on Blackboard. Summer 2008 Q1 Version 1.2 11 Getting User Input Unfortunately, not as easy as it should be in Java. Two choices: – Use a Scanner object (newer technique). – Use an InputStream object (older technique). Scanner somewhat easier, but can be cranky. InputStream bulletproof, but harder to use. I have provided two examples of code using each technique. Summer 2008 Q1 Version 1.2 12 Input Via Scanner Must import the java.util.Scanner package, or java.util.*. See Section 2.13 of text for discussion on use. To actually get input, must use of the “next” methods. – Text does not list nextLine(), but it is another string input method. Scanner scanner = new Scanner(System.in); System.out.print("Enter an integer value: "); int intval = scanner.nextInt(); Summer 2008 Q1 Version 1.2 13 Scanner Secret! next() method only gets first chunk of a string if it has spaces. – Must use nextLine() if you want a whole line of input that includes spaces. – But nextLine() will be fooled by any previous input of numeric values. This is because nextInt(), nextDouble() leave the enter key character(s) in the keyboard buffer. – To successfully use the Scanner to get strings from the keyboard, clear it before asking for input. But only if you have previous input. Scanner scanner = new Scanner(System.in); scanner.nextLine(); // This clears things out first. System.out.print("Enter your full name: "); String fullname = scanner.nextLine(); Summer 2008 Q1 Version 1.2 14 The Input Stream Approach This is the original way that Java console input was conducted. Requires several things to be done with your code to get it set up properly. Step 1: Indicate that your main() method throws and IOException. public static void main(String args[]) throws IOException Summer 2008 Q1 Version 1.2 15 The Input Stream Approach Step 2: Create a BufferedReader object. // Set up input channel. BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); Summer 2008 Q1 Version 1.2 16 The Input Stream Approach Step 3: Read in a line of input. – Note: All input that comes in is a character string. String input; System.out.print("Enter adjusted gross income: "); input = in.readLine(); Summer 2008 Q1 Version 1.2 17 The Input Stream Approach Step 4: Converting to your target data type. – Note: All intrinsic data types have a partner reference type (class) that supports parsing of values from a string. – This is very similar to what you did in HTML class with JavaScript. income = Double.parseDouble(input); Summer 2008 Q1 Version 1.2 18 The Input Stream Approach Putting it all together (complete code on Blackboard). public static void main(String args[]) throws IOException { // Set up input channel. BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // Declare support variables. double income,taxdue; String input; System.out.print("Enter adjusted gross income: "); input = in.readLine(); income = Double.parseDouble(input); Summer 2008 Q1 Version 1.2 19 If Statements First, let’s look at the available relational operators: – – – – – – == != < > <= >= Equal to Not equal to Less than Greater than Less than or equal Greater than or equal These are complemented by the compound operators: – && – || And Or Defined on Page 68. Summer 2008 Q1 Version 1.2 20 If Statements Refer to Chapter 3 in text. Used to code decision making statements in programs. Result of an if test is true or false. Syntax requires use of parentheses. if (g > 2) g = 14; Summer 2008 Q1 Version 1.2 21 If Statements General syntax: if () { } else if() { } else { } Summer 2008 Q1 Version 1.2 22 If Blocks When more than one statement is to be executed (if the logical test is true), braces are used to form a block: if (a >= b) { a = 3*b; i = i + 1; } Summer 2008 Q1 Version 1.2 23 The Else Clause Many times it is necessary to take actions both when a condition is true or if it is false. The else clause allows expansion of the if to accommodate this situation. Summer 2008 Q1 Version 1.2 24 Else Clause When more than one statement is to be executed (if the logical test is true), braces are used to form a block: if (a < b + 10) { System.out.println(“Curing too rapidly.”); } else { iter = iter + 1; } Summer 2008 Q1 Version 1.2 25 The Else If Extension Multiple tests can be constructed through use of else if. if (g + 1 != a*b) g = g + 1; else if (a < 10) g = 2*g; else if (a*b > 350) g = g*g; else g = 0; Summer 2008 Q1 Version 1.2 26 Nested If Statements If statements can be placed within other if statements. if (g + 1 != a*b) { g = g + 1; if (a < 10) g = 2*g; else if (a*b > 350) g = g*g; else g = 0; } Summer 2008 Q1 Version 1.2 27 Nested If Statements Be wary of how you structure nested ifs. An else always belongs to the nearest preceding if that’s not already associated with another else. What does following code do? int g = 3; int a = 0; if (g != 3) if (a < 10) System.out.println(“a < 10”); else System.out.println(“a not < 10”); Summer 2008 Q1 Version 1.2 28 Compound IF Statements Simple relational expressions can be joined into more complex expressions via the compound operators. && Logical AND || Logical OR These operators have a precedence. And before or. if (a < 10 && b == 3) System.out.printf(“%d %d\n”,a,b); Summer 2008 Q1 Version 1.2 29 Switch Statements Switch statements are like if statements in many ways. – They clean up the syntax a little bit. Similar to case statements of other languages. Means to compare an integer value against a list of cases. Refer to Page 81 of text. The break statement needed to prevent fall through execution. Summer 2008 Q1 Version 1.2 30 Switch Statements General syntax: switch (expression) { case constant1: statement sequence case constant2: statement sequence . . default: statement sequence } Summer 2008 Q1 Version 1.2 31 Switch Statements Specific example: switch (a) { case 1 : System.out.println(“a = 1”); break; case 2 : System.out.println(“a = 2”); break; default : System.out.println(“a is not 1 or 2”); } Summer 2008 Q1 Version 1.2 32 Formatting Output This is alternative to using NumberFormat object. The printf statement together with formatting codes can achieve a limited degree of output formatting. See Tables 3.8 and 3.9 for available codes. System.out.printf(“The value is %d dollars”,dblDollar); System.out.printf(“The value is %10.2f dollars”, dblDollar); System.out.printf(“%25s\n”,”Bob”); Summer 2008 Q1 Version 1.2 33 Coding Sessions Group work #1: – Write a program that reads a grade of A, B, C, D or F and then prints “excellent”, “good”, “fair”, “poor” or “failure”. – Use the if – else structure. Group work #2: – Revise the above program to use a switch structure. Summer 2008 Q1 Version 1.2 34 Coding Sessions Practice work: – Write a program that reads a user’s age and then prints: “You are a child” if the age is less than 18. “You are an adult” if the age is greater than or equal to 18 and less than 65. “You are a senior citizen” if the age is greater than or equal to 65. Summer 2008 Q1 Version 1.2 35 Assignments Reading: Chapters 3 and 4 from text. Assignment 2. – Due next week. Assignment 1 due today. Participate in discussion forums. Summer 2008 Q1 Version 1.2 36