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 in Java Practical session #3 Language Basics This session ● ● ● Control Flow Statements ○ Decision making (continue if-then-else) ■ switch ○ Looping statements ■ for ■ while ■ do-while ○ Branching statements ■ break ■ continue Text Comparison program Eclipse - output to file The switch Statement ● ● ● ● ● ● ● ● ● can have a number of possible execution paths works with the ○ byte, short, char, and int primitive data types ○ enumerated types (maybe letter in the course) ○ String class (from Java 7) a switch block - body of a switch statement can be labeled with one or more case or default labels evaluates its expression, then executes all statements that follow the matching case label tests expressions based only on a single integer, enumerated value, or String object each break statement terminates the enclosing switch statement control flow continues with the first statement following the switch block The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered The switch Statement ● ● ● Technically, the final break is not required because flow falls out of the switch statement. Using a break is recommended so that modifying the code is easier and less error prone. The default section handles all values that are not explicitly handled by one of the case sections. The switch Statement The following code example, SwitchDemo2, shows how a statement can have multiple case labels. The code example calculates the number of days in a particular month: The switch Statement class SwitchDemo2 { public static void main(String[] args) { case 2: if (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0)) numDays = 29; else numDays = 28; break; default: System.out.println("Invalid month."); break; int month = 2; int year = 2000; int numDays = 0; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: numDays = 31; break; case 4: case 6: case 9: case 11: numDays = 30; break; This is the output from the code: Number of Days = 29 } System.out.println("Number of Days = " + numDays); } } The while and do-while Statements The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as: while (expression) { statement(s) } The while and do-while Statements Using the while statement to print the values from 1 through 10 can be accomplished as in the following WhileDemo program: class WhileDemo { public static void main(String[] args){ int count = 1; while (count < 11) { System.out.println("Count is: " + count); count++; } } } The while and do-while Statements ● You can implement an infinite loop using the while statement as follows: while (true){ // your code goes here } The while and do-while Statements ● The Java programming language also provides a do-while statement, which can be expressed as follows: do { statement(s) } while (expression); The while and do-while Statements ● ● The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once, as shown in the following DoWhileDemo program: class DoWhileDemo { public static void main(String[] args){ int count = 1; do { System.out.println("Count is: " + count); count++; } while (count < 11); } } The for Statement ● ● a compact way to iterate over a range of values the general form of the for statement can be expressed as follows: for (initialization; termination; increment) { statement(s) } The for Statement When using this version of the for statement, keep in mind that: ● The initialization expression initializes the loop; it's executed once, as the loop begins. ● When the termination expression evaluates to false, the loop terminates. ● The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value. The for Statement The following program, ForDemo, uses the general form of the for statement to print the numbers 1 through 10 to standard output: class ForDemo { public static void main(String[] args){ for(int i=1; i<11; i++){ System.out.println("Count is: " + i); } } } The output of this program is: Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5 Count is: 6 Count is: 7 Count is: 8 Count is: 9 Count is: 10 The for Statement ● ● ● The scope of the declared variable extends from its declaration to the end of the block governed by the for statement. If the variable that controls a for statement is not needed outside of the loop, it's best to declare the variable in the initialization expression. The names i, j, and k are often used to control for loops ○ declaring them within the initialization expression limits their life span and reduces errors. The for Statement The three expressions of the for loop are optional; an infinite loop can be created as follows: // infinite loop for ( ; ; ) { // your code goes here } Loops exercises #1 - same logic, different loops Write a program that get two positive integers, x and y, from user and calculate the xy. Example: x=2 y=3 xy = 8 Write two versions of the program: one with for and one with while. Loops exercises #1 - same logic, different loops Scanner sc = new Scanner(System.in); System.out.print("Enter the first number:"); int x = sc.nextInt(); System.out.print("Enter the second number:"); int y = sc.nextInt(); int result = 1; for (int i = 0; i < y; i++) result *= x; System.out.println(x + "^" + y + " is: " + result); Scanner sc = new Scanner(System.in); System.out.print("Enter the first number:"); int x = sc.nextInt(); System.out.print("Enter the second number:"); int y = sc.nextInt(); int result = 1, i = 0; while (i < y){ result *= x; i++; } System.out.println(x + "^" + y + " is: " + result); Loops exercises #2 - control flow following Follow the program control flow and try to understand what this program done: public static void main(String[] args) { int x, y, something = 0; Scanner sc = new Scanner(System.in); System.out.println("Enter two numbers: "); x = sc.nextInt(); y = sc.nextInt(); while (x-- > 0) something++; for (; y > 0; y--, something--); System.out.println(something); } Loops exercises #2 - control flow following Follow the program control flow and try to understand what this program done: public static void main(String[] args) { int x, y, something = 0; Scanner sc = new Scanner(System.in); System.out.println("Enter two numbers: "); x = sc.nextInt(); y = sc.nextInt(); while (x-- > 0) something++; for (; y > 0; y--, something--); System.out.println(something); } Yep, the code do (x - y). Loops exercises #3 - double loop Write a program that get positive integer from user as input and prints n*n square of asterisks. Loops exercises #3 - double loop Write a program that get positive integer from user as input and prints n*n square of asterisks. public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Please enter dimension"); int n = sc.nextInt(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) System.out.print('*'); System.out.println(); } } Loops exercises #4 - reverse number Write a program that get integer number as input from the user, reverse it and prints as output. Loops exercises #4 - reverse number Write a program that get integer number as input from the user, reverse it and prints as output. public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter number: "); int reversed_num = 0, sign = 1, num = sc.nextInt(); // Treat negative number as positive and remember sign if (num < 0){ sign = -1; num = -num; { // Reverse the number while (num > 0){ reversed_num = reversed_num * 10 + num%10; num /= 10; } reversed_num *= sign; System.out.println("Reversed = " + reversed_num); } The continue Statement ● The continue statement skips the current iteration of a for, while , or dowhile loop. ● The following program, ContinueDemo , steps through a String, counting the occurrences of the letter "p". If the current character is not a p, the continue statement skips the rest of the loop and proceeds to the next character. If it is a "p", the program increments the letter count. The continue Statement class ContinueDemo { public static void main(String[] args) { String searchMe = "peter piper picked a " + "peck of pickled peppers"; int max = searchMe.length(); // length of string searchMe int numPs = 0; for (int i = 0; i < max; i++) { // interested only in p's if (searchMe.charAt(i) != 'p') // char at index i in string searchMe continue; // process p's numPs++; } System.out.println("Found " + numPs + " p's in the string."); } } The continue Statement ● ● The output of this program: Found 9 p's in the string. To see this effect more clearly, try removing the continue statement and recompiling. When you run the program again, the count will be wrong, saying that it found 35 p's instead of 9. Text Comparison ● ● ● ● ● Your homeworks will be programs How we going to check your homework? ○ We will take particular inputs for your homework program and run on: ■ our implementation of the assignment with this input and will output it to file - name it classOutput.txt ■ your implementation of the assignment with this input and will output it to file - name it homeOutput.txt ○ The two output files will be compared for difference ○ In case the outputs EXACTLY the same - you get 100 points for the task, any difference - you will get 0 for the task. You will be provided with some example input and outputs, so it is possible to compare your output at home with our output. For that reason we will se how to compare two text files. Eclipse IDE have its own text comparison feature - so we will use Eclipse. Text Comparison Comparison example - how-to: ● Open Eclipse ● Create new Java project (of course you can use your existing project) ● Create new text file and name it classOutput.txt ● Create second text file and name it homeOutput.txt Text Comparison ● ● ● Enter some text in the classOutput.txt file, for example (that way, four lines of text): "Luck is what happens when preparation meets opportunity." - Seneca Now, copy the text to the second file and change it a little bit. Save both files. Text Comparison ● ● ● ● In the package explorer window of the IDE select one of the files with the pointer; Press shift button on the keyboard; Without release the control (or command on Mac) button click on the second file; Now you have two selected files, the classOutput.txt and the homeOutput. txt Text Comparison ● ● Right click (control click on Mac) your mouse/trackpad when the pointer on one of the two files and both still selected to bring the context menu up; Choice the Compare With context menu item, and the Each Other sub-item. Text Comparison ● ● As you can see in the following snapshot, you can see all the differences between those two files. The buttons in the right upper corner of the window can help you to navigate between the differences. Eclipse - multi-input by one step ● ● In your homework you'll be asked to work with some massive input To not enter every execution of your code many inputs manually you can do the following: ○ For example, we have a program that sum two integers, so the user input will be: [first integer] [enter] [second integer] [enter] ○ Instead of entering manually each one of the numbers prepare text file with user input beforehand ○ Run your program ○ Copy/Paste the whole user input from the prepared file to the console ○ For example, your input to your program that sums up to integers is 5 & 7, so you need to enter the digit 5, the "enter" keyboard button, the digit 7 and again "enter" keyboard button. So prepare input file like that: ■ 5 ■ 7 ■ ○ Pay attention, the file have three line, because each "enter" button press creates new line. Eclipse - output to file ● ● Another thing you will need for you homework is to redirect/add your output to file instead of console window. Lets see how to redirect/add the standard output (snapshot on the next slide) ○ Before execution of your project go to menu bar and choose Run | Run Configurations... (same for debug) ○ In the opened configuration window choose your project from the left sided list ○ In the right side choice the Common tab ○ In the opened tab seek for Standard Input and Output region ○ In the region mark the File: option with V and use the File System button to choose where and what the name of your output file will be ○ Press Apply button in the low left part of the window ○ Press Run to execute your project Eclipse - output to file Next Lecture ● ● ● Arrays Submission System Homework overview