Free Trainings @ Software University Software University Foundation – softuni.org Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software University @ Facebook facebook.com/SoftwareUniversity Software University @ YouTube youtube.com/SoftwareUniversity Software University Forums – forum.softuni.bg
The classical for -loop syntax is: Consists of Initialization statement Boolean test expression Update statement Loop body block For Loops for (initialization; test; update ) { statements; } 62
Type Conversions Live Demo
Methods Defining and Invoking Methods
Console Input and Output Scanner and Formatted Printing
39 The java.util.Scanner class reads strings and numbers The numbers can be separated by any sequence of whitespace characters (e.g. spaces, tabs, new lines, …) Exception is thrown when non-number characters are entered Reading from the Console import java.util.Scanner; … Scanner input = new Scanner(System.in); int firstNum = input.nextInt(); int secondNum = input.nextInt(); 3 -5 Sample Inputs 3 -5
Loops Live Demo
40 A more complex example: Read two words from the first line Integer and two doubles from the second line A string from the third line Reading from the Console (2) Scanner input = new Scanner(System.in); String firstWord = input.next("\\w+"); String secondWord = input.next("\\w+"); int numInt = input.nextInt(); double numDouble1 = input.nextDouble(); double numDouble2 = input.nextDouble(); input.nextLine(); // Skip to the line end String str = input.nextLine();
Reading from the Console Live Demo
68 Loops can be nested (one inside another) Example: print all combinations from TOTO 6/49 lottery Nested Loops for (int i1 = 1; i1 <= 44; i1++) for (int i2 = i1 + 1; i2 <= 45; i2++) for (int i3 = i2 + 1; i3 <= 46; i3++) for (int i4 = i3 + 1; i4 <= 47; i4++) for (int i5 = i4 + 1; i5 <= 48; i5++) for (int i6 = i5 + 1; i6 <= 49; i6++) System.out.printf("% d %d %d % d % d % d\n", i1, i2, i3, i4, i5, i6 );
Example of for-each loop: The loop iterates over the array of day names The variable day takes all its values Applicable for all collections: arrays, lists, strings, etc. For-Each Loop – Example String[] days = { "Monday", "Tuesday", "Wednesday ", " Thursday ", " Friday", "Saturday", "Sunday" }; for (String day : days) { System.out.println(day ); } 67
36 Type conversion and typecasting change one type to another: Type Conversion long lng = 5; int intVal = (int) lng; // Explicit type conversion float heightInMeters = 1.74f; // Explicit conversion double maxHeight = heightInMeters; // Implicit double minHeight = (double) heightInMeters; // Explicit float actualHeight = (float)
Учебни материали
Споделени от колеги - с преглед преди изтегляне.
Програмиране и програмни езици
Програмиране
JavaSyntax
Преглед на началото - целият файл след изтегляне
0 коментара
За да коментирате, трябва да сте влезли в профила си.
Влезте