Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Java Basics.

Similar presentations


Presentation on theme: "Java Java Basics."— Presentation transcript:

1 Java Java Basics

2 A Simple Java Program Modifier Keyword Identifier for Class name // this program prints “Hello World” to screen public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } Comment Main method declaration Statement Calling the method for printing to screen package cs243; HelloWorld.java

3 Variables variable: A piece of the computer's memory that is given a name and type, and can store a value. Like preset stations on a car stereo, or cell phone speed dial: Steps for using a variable: Declare it - state its name and type Initialize it - store a value into it Use it - print it or use it as part of an expression 3

4 Variables A variable store information such as letters, numbers, words, sentences A variable has three properties: A memory location to store the value, The type of data stored in the memory location, and The name (identifier) used to refer to the memory location. Sample variable declarations: int x; int v, w, y;

5 Variable declaration and initialization
int x; int x,y; Variable initialization x=5; Variable declaration and initialization int x=5;

6 Compiler errors A variable can't be used until it is assigned a value.
int x; System.out.println(x); // ERROR: x has no value You may not declare the same variable twice. int x; int x; // ERROR: x already exists int x = 3; int x = 5; // ERROR: x already exists How can this code be fixed?

7 The 8 Java Primitive data types
Numeric data types example Number of bytes Data type byte x=5; 1 Byte short y=12 2 Short int x=10; 4 Integer long s=12l; 8 Long float r=1.2f; Float double t=4.7; Double Boolean data type Both primitive values and object references can be converted and cast, so you must consider four general cases: Conversion of primitives Casting of primitives Conversion of object references Casting of object references boolean x=true; boolean y=false; 1 Boolean Character data type char x=‘a’; 2 Character

8 Character Data Type Four hexadecimal digits. char letter = 'A'; (ASCII) char numChar = '4'; (ASCII) char letter = '\u0041'; (Unicode) char numChar = '\u0034'; (Unicode) You can use ASCII characters or Unicode characters in your Java Programs NOTE: The increment and decrement operators can also be used on char variables to get the next or preceding Unicode character. For example, the following statements display character b. char ch = 'a'; System.out.println(++ch);

9 Unicode Format Java characters use Unicode, 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. Unicode takes two bytes, preceded by \u, expressed in four hexadecimal numbers that run from '\u0000' to '\uFFFF'. So, Unicode can represent characters. Unicode \u03b1 \u03b2 \u03b3 for three Greek letters

10 Numeric Operators

11 Integer Division +, -, *, /, and % 5 / 2 yields an integer 2.
5.0 / 2 yields a double value 2.5 5 % 2 yields 1 (the remainder of the division)

12 Integer division with /
When we divide integers, the quotient is also an integer. 14 / 4 is 3, not 3.5 4 ) ) ) 1425 54 21 More examples: 32 / 5 is 6 84 / 10 is 8 156 / 100 is 1 Dividing by 0 causes an error when your program runs.

13 Integer remainder with %
The % operator computes the remainder from integer division. 14 % 4 is 2 218 % 5 is ) ) Applications of % operator: Obtain last digit of a number: % 10 is 7 Obtain last 4 digits: % is 6489 See whether a number is odd: 7 % 2 is 1, 42 % 2 is 0 What is the result? 45 % 6 2 % 2 8 % 20 11 % 0 What is 8 % 20? It's 8, but students often say 0. 13

14 Expressions expression: A value or operation that computes a value.
Examples: * 5 (7 + 2) * 6 / 3 42 The simplest expression is a literal value. A complex expression can use operators and parentheses.

15 System.out.print Prints without moving to a new line
allows you to print partial messages on the same line int highestTemp = 5; for (int i = -3; i <= highestTemp / 2; i++) { System.out.print((i * ) + " "); } Output:

16 Printing a variable's value
Use + to print a string and a variable's value on one line. double grade = ( ) / 3.0; System.out.println("Your grade was " + grade); int students = ; System.out.println("There are " + students + " students in the course."); Output: Your grade was 83.2 There are 65 students in the course.

17 Precedence precedence: Order in which operators are evaluated.
Generally operators evaluate left-to-right is (1 - 2) - 3 which is -4 But */% have a higher level of precedence than * 4 is 13 6 + 8 / 2 * 3 * 3 is 18 Parentheses can force a certain order of evaluation: (1 + 3) * 4 is 16 Spacing does not affect order of evaluation 1+3 * 4-2 is 11

18 Precedence examples 1 * 2 + 3 * 5 % 4 \_/ | 2 + 3 * 5 % 4
\_/ | * 5 % 4 \_/ | % 4 \___/ | \________/ | 1 + 8 % 3 * 2 - 9 \_/ | * 2 - 9 \___/ | \______/ | \_________/ | Ask the students what 15 / 4 and 2 / 3 are, since the answers are non-obvious.

19 Precedence questions What values result from the following expressions? 9 / 5 695 % 20 7 + 6 * 5 7 * 6 + 5 248 % 100 / 5 6 * / 4 (5 - 7) * 4 6 + (18 % ( )) Answers: 1 15 37 47 9 16 -8 19

20 Real number example 2.0 * 2.4 + 2.25 * 4.0 / 2.0
\___/ | * 4.0 / 2.0 \___/ | / 2.0 \_____/ | \____________/ |

21 Example

22 Declaring constants Java does not directly support constants. However, a final variable is effectively a constant. The final modifier causes the variable to be unchangeable Java constants are normally declared in ALL CAPS class Math { public final double PI=3.14; }

23 Comments in Java Compiler view class A class A { {
In Java, comments are preceded:- by two slashes (//) in a line, or enclosed between /* and */ in one or multiple lines. When the compiler sees //, it ignores all text after // in the same line. When it sees /*, it scans for the next */ and ignores any text between /* and */ // This application program prints Welcome to Java! /* This application program prints Welcome to Java! */ class A { // Author :Ahmed Aly int x; public static void m() ……….. } class A { int x; public static void m() ……….. } Compiler view

24 Comments example /* Suzy Student, CS 101, Fall 2019
This program prints lyrics about ... something. */ public class BaWitDaBa { public static void main(String[] args) { // first verse System.out.println("Bawitdaba"); System.out.println("da bang a dang diggy diggy"); System.out.println(); // second verse System.out.println("diggy said the boogy"); System.out.println("said up jump the boogy"); }

25 Identifier JAVA use identifiers to name variables, constants, methods, classes, and packages An identifier is a sequence of characters that consists of letters, digits, underscores (_), and dollar signs ($). A n identifier cannot start with a digit. An identifier cannot be a reserved word. An identifier cannot be true, false, or null. An identifier can be of any length. // author: Ahmed Ali package racing; public class Car{ String color; private int speed; private int numOfDoors=4; public void incrementSpeed(int value){ ………………….. } $2 ComputeArea area radius showMessageDialog Since Java is case-sensitive, X and x are different identifiers. 2A A-b d+4 racing, Car, color, speed, numOfDoors, incrementSpeed are all identifiers

26 Reserved Words Modifiers
// author: Ahmed Ali public class Car{ String color; private int speed; private int numOfDoors=4; public void incrementSpeed(int value){ ………………….. } public void decrementSpeed(int value){ speed=speed-value; public int getSpeed(){ public boolean isMoving() { public static void getNumberOfCars() Reserved words or keywords are words that have a specific meaning to the compiler and cannot be used for other purposes in the program. For example: class, public, static, and void. int speed; int class; Modifiers Java uses certain reserved words called modifiers that specify the properties of the data, methods, and classes and how they can be used. For example: public ,private, final private int speed; public static void getNumberOfCars(){ }

27 List of Java Keywords

28 Literal Values for primitives
By default, a numeric literal is either a double or an int, 7 5.6 int double float x=4.7f; float x=4.7; int x=1342; double x=1_767.2; int x=1_342; byte b = 1; short s = 2; Java relaxes its assignment conversion boolean b = true; boolean v = false; boolean b = True; boolean x = False; This relaxation of the rule applies only when the assigned value is an integral literal. int i = 12; byte b = I // compile error char x=‘A’; char x=65;

29 Strings The data type String hold an array of characters
String values are surrounded by double quotation String name1=“Ahmed ”; String name1=new String(“Ahmed ”); String concatenation is applied using the + operator String name1=“Ahmed ”; String name2=“Mohamed”; String name=name1+name2; String x=7+” ”; Combining variables and string int y=10; //prints y=10 String s=“y=“+y;

30 String concatenation string concatenation: Using + between a string and another value to make a longer string. "hello" + 42 is "hello42" 1 + "abc" + 2 is "1abc2" "abc" is "abc12" "abc" is "3abc" "abc" + 9 * 3 is "abc27" "1" + 1 is "11" "abc" is "3abc" Use + to print a string and an expression's value together. System.out.println("Grade: " + ( ) / 2); Output: Grade: 83.5

31 Primitive data type conversion
A primitive data type can be converted to another type, provided the conversion is a widening conversion int i=12; double d=i; 1-Conversion by Assignment All operands are set to the wider type of them The promotion should be to at least int 3-Conversion by Arithmatic Promotion short s1=7; short s2=13; // short s3=s1+s2; compile error as s1,s2 are converted to int int i=s1+s2; 2-Conversion by Method call class test{ void m1(){ int i=9; m2(i); } void m2(double d){ ///

32 Primitive Casting Casting is explicitly telling Java to make a conversion. A casting operation may widen or narrow its argument. To cast, just precede a value with the parenthesized name of the desired type. int i = d; double d = 4.5; int i = (int)d; int i=12; short s=(short)i; short s=i; int i=7; short i=i +3; int i; short s=(short) (i +3); int i=4 +7.0; int i=(int) (4 +7.0);

33 Casting between char and Numeric Types
int i = 'a'; // Same as int i = (int)'a'; The Unicode of character a is assigned to i char c = 97; // Same as char c = (char)97; The lower 16 are used as the unicode

34 Mixing types When int and double are mixed, the result is a double.
The conversion is per-operator, affecting only its operands. 7 / 3 * / 2 \_/ | * / 2 \___/ | / 2 \_/ | \________/ | 3 / 2 is 1 above, not 1.5. / 3 * / 4 \___/ | * / 4 \_____/ | / 4 \_/ | \_________/ | \______________/ |

35 Java Operators Logic Arithmetic Logic Assignment Comparison
+,-,*,/,%,++,-- Logic &,|,~,&&,|| Assignment =, +=, -=, etc.. Comparison <,<=,>,>=,==,!= Work just like in C/C++, Logic &,|,^,~,<<,>>,>>>

36 Increment and decrement
shortcuts to increase or decrease a variable's value by 1 Shorthand Equivalent longer version variable++; variable = variable + 1; variable--; variable = variable - 1; int x = 2; x++; // x = x + 1; // x now stores 3 double gpa = 2.5; gpa--; // gpa = gpa - 1; // gpa now stores 1.5

37 Modify-and-assign operators
shortcuts to modify a variable's value Shorthand Equivalent longer version variable += value; variable = variable + value; variable -= value; variable = variable - value; variable *= value; variable = variable * value; variable /= value; variable = variable / value; variable %= value; variable = variable % value; x += 3; // x = x + 3; gpa -= 0.5; // gpa = gpa - 0.5; number *= 2; // number = number * 2;

38 Java's Math class Method name Description Math.abs(value)
absolute value Math.round(value) nearest whole number Math.ceil(value) rounds up Math.floor(value) rounds down Math.log10(value) logarithm, base 10 Math.max(value1, value2) larger of two values Math.min(value1, value2) smaller of two values Math.pow(base, exp) base to the exp power Math.sqrt(value) square root Math.sin(value) Math.cos(value) Math.tan(value) sine/cosine/tangent of an angle in radians Math.toDegrees(value) Math.toRadians(value) convert degrees to radians and back Math.random() random double between 0 and 1 Constant Description E PI

39 Calling Math methods Examples:
Math.methodName(parameters) Examples: double squareRoot = Math.sqrt(121.0); System.out.println(squareRoot); // 11.0 int absoluteValue = Math.abs(-50); System.out.println(absoluteValue); // 50 System.out.println(Math.min(3, 7) + 2); // 5 The Math methods do not print to the console. Each method produces ("returns") a numeric result. The results are used as expressions (printed, stored, etc.).

40 Return return: To send out a value as the result of a method.
The opposite of a parameter: Parameters send information in from the caller to the method. Return values send information out from a method to its caller. main Math.abs(-42) -42 Math.round(2.71) 2.71 42 3

41 Math questions Evaluate the following expressions: Math.abs(-1.23)
Math.pow(3, 2) Math.pow(10, -2) Math.sqrt(121.0) - Math.sqrt(256.0) Math.round(Math.PI) + Math.round(Math.E) Math.ceil(6.022) + Math.floor( ) Math.abs(Math.min(-3, -5)) Math.max and Math.min can be used to bound numbers. Consider an int variable named age. What statement would replace negative ages with 0? What statement would cap the maximum age to 40?

42 Input and System.in System.out System.in
An object with methods named println and print System.in not intended to be used directly We use a second object, from a class Scanner, to help us. Constructing a Scanner object to read console input: Scanner name = new Scanner(System.in); Example: Scanner console = new Scanner(System.in);

43 Hint: Reading integers from Console
class ScannerDemo { public static void main (String [] arg) java.util.Scanner scan=new java.util.Scanner (System.in); System.out.println("Please Enter first number"); int num1=scan.nextInt(); System.out.println("Please Enter Second number"); int num2=scan.nextInt(); int sum=num1+num2; System.out.println("The sum of " + num1 +" and "+num2+"="+sum); }

44 Java class libraries, import
Java class libraries: Classes included with Java's JDK. organized into groups named packages To use a package, put an import declaration in your program. Syntax: // put this at the very top of your program import packageName.*; Scanner is in a package named java.util import java.util.*; To use Scanner, you must place the above line at the top of your program (before the public class header).

45 Scanner methods System.out.print("How old are you? "); // prompt
Description nextInt() reads a token of user input as an int nextDouble() reads a token of user input as a double next() reads a token of user input as a String nextLine() reads a line of user input as a String Each method waits until the user presses Enter. The value typed is returned. System.out.print("How old are you? "); // prompt int age = console.nextInt(); System.out.println("You'll be 40 in " + (40 - age) + " years."); prompt: A message telling the user what input to type.

46 Example Scanner usage Output (user input underlined):
import java.util.*; // so that I can use Scanner public class ReadSomeInput { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("How old are you? "); int age = console.nextInt(); System.out.println(age + "... That's quite old!"); } Output (user input underlined): How old are you? 14 14... That's quite old! It's also useful to write a program that prompts for multiple values, both on the same line or each on its own line.

47 Another Scanner example
import java.util.*; // so that I can use Scanner public class ScannerSum { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("Please type three numbers: "); int num1 = console.nextInt(); int num2 = console.nextInt(); int num3 = console.nextInt(); int sum = num1 + num2 + num3; System.out.println("The sum is " + sum); } Output (user input underlined): Please type three numbers: The sum is 27 The Scanner can read multiple values from one line. It's also useful to write a program that prompts for multiple values, both on the same line or each on its own line.

48 Control Structures The for loop is similar to C/C++
Java also has support for continue and break keywords Again, work very similar to C/C++ for(int i = 0; i < 10; i++) { a += i; if(a > 100) break; } for(int i = 0; i < 10; i++) { if(i == 5) continue; a += i; }

49 Executes a block of statements only if a test is true
The if statement Executes a block of statements only if a test is true if (test) { statement; ... } Example: double gpa = console.nextDouble(); if (gpa >= 2.0) { System.out.println("Application accepted.");

50 Executes one block if a test is true, another if false
The if/else statement Executes one block if a test is true, another if false if (test) { statement(s); } else { } Example: double gpa = console.nextDouble(); if (gpa >= 2.0) { System.out.println("Welcome to Mars University!"); System.out.println("Application denied.");

51 Nested if/else/if Example:
If it ends with else, one code path must be taken. If it ends with if, the program might not execute any path. if (test) { statement(s); } else if (test) { } Example: if (place == 1) { System.out.println("You win the gold medal!"); } else if (place == 2) { System.out.println("You win a silver medal!"); } else if (place == 3) { System.out.println("You earned a bronze medal.");

52 Factoring if/else code
factoring: extracting common/redundant code Factoring if/else code can reduce the size of if/else statements or eliminate the need for if/else altogether. Example: if (a == 1) { x = 3; } else if (a == 2) { x = 6; y++; } else { // a == 3 x = 9; } x = 3 * a; if (a == 2) { y++; }

53 Code in need of factoring
if (money < 500) { System.out.println("You have, $" + money + " left."); System.out.print("Caution! Bet carefully."); System.out.print("How much do you want to bet? "); bet = console.nextInt(); } else if (money < 1000) { System.out.print("Consider betting moderately."); } else { System.out.print("You may bet liberally."); }

54 if/else question BMI Weight class below 18.5 underweight 18.5 - 24.9
normal overweight 30.0 and up obese A person's body mass index (BMI) is defined to be: Write a program that produces the following output: This program reads data for two people and computes their body mass index (BMI) and weight status. Enter next person's information: height (in inches)? 70.0 weight (in pounds)? height (in inches)? 62.5 weight (in pounds)? 130.5 Person #1 body mass index = 27.87 overweight Person #2 body mass index = 23.49 normal Difference = 4.38

55 if/else, return question
Write a class countFactors that returns the number of factors of an integer. countFactors(24) returns 8 because 1, 2, 3, 4, 6, 8, 12, and 24 are factors of 24. Write a program that prompts the user for a maximum integer and prints all prime numbers up to that max. Maximum number? 52 15 primes (28.84%)

56 Relational expressions
A test in an if is the same as in a for loop. for (int i = 1; i <= 10; i++) { ... if (i <= 10) { ... These are boolean expressions, seen in Ch. 5. Tests use relational operators: Operator Meaning Example Value == equals 1 + 1 == 2 true != does not equal 3.2 != 2.5 < less than 10 < 5 false > greater than 10 > 5 <= less than or equal to 126 <= 100 >= greater than or equal to 5.0 >= 5.0 Note that == tests equality, not = . The = is used for the assignment operator!

57 Logical operators: &&, ||, !
Conditions can be combined using logical operators: "Truth tables" for each, used with logical values p and q: Operator Description Example Result && and (2 == 3) && (-1 < 5) false || or (2 == 3) || (-1 < 5) true ! not !(2 == 3) p q p && q p || q true false p !p true false

58 Evaluating logic expressions
Relational operators have lower precedence than math. 5 * 7 >= * (7 - 1) 5 * 7 >= * 6 35 >= 35 >= 33 true Relational operators cannot be "chained" as in algebra. 2 <= x <= (assume that x is 15) true <= 10 error! Instead, combine multiple tests with && or || 2 <= x && x <= (assume that x is 15) true && false false

59 Logical questions What is the result of each of the following expressions? int x = 42; int y = 17; int z = 25; y < x && y <= z x % 2 == y % 2 || x % 2 == z % 2 x <= y + z && x >= y + z !(x < y && x < z) (x + y) % 2 == 0 || !((z - y) % 2 == 0) Answers: true, false, true, true, false

60 Control Structures if/else, for, while, do/while, switch
Basically work the same as in C/C++ i = 0; while(i < 10) { a += i; i++; } for(i = 0; i < 10; i++) { a += i; } if(a > 3) { a = 3; } else { a = 0; switch(i) { case 1: string = “foo”; case 2: string = “bar”; default: string = “”; } i = 0; do { a += i; i++; } while(i < 10);

61 The while loop while loop: Repeatedly executes its body as long as a logical test is true. while (test) { statement(s); } Example: int num = 1; // initialization while (num <= 200) { // test System.out.print(num + " "); num = num * 2; // update OUTPUT:

62 A deceptive problem... Write a method printNumbers that prints each number from 1 to a given maximum, separated by commas. For example, the call: printNumbers(5) should print: 1, 2, 3, 4, 5

63 for loop syntax for (initialization; test; update) { statement; ... }
body header for (initialization; test; update) { statement; ... } Perform initialization once. Repeat the following: Check if the test is true. If not, stop. Execute the statements. Perform the update.

64 Initialization Tells Java what variable to use in the loop
for (int i = 1; i <= 6; i++) { System.out.println(i + " squared = " + (i * i)); } Tells Java what variable to use in the loop Called a loop counter Can use any variable name, not just i Can start at any value, not just 1

65 Test Tests the loop counter variable against a bound
for (int i = 1; i <= 6; i++) { System.out.println(i + " squared = " + (i * i)); } Tests the loop counter variable against a bound Uses comparison operators: < less than <= less than or equal to > greater than >= greater than or equal to

66 Update Changes loop counter's value after each repetition
for (int i = 1; i <= 6; i++) { System.out.println(i + " squared = " + (i * i)); } Changes loop counter's value after each repetition Without an update, you would have an infinite loop Can be any expression: for (int i = 1; i <= 9; i += 2) { System.out.println(i);

67 Loop walkthrough for (int i = 1; i <= 4; i++) {
2 3 for (int i = 1; i <= 4; i++) { System.out.println(i + " squared = " + (i * i)); } System.out.println("Whoo!"); Output: 1 squared = 1 2 squared = 4 3 squared = 9 4 squared = 16 Whoo! 4 5 1 2 4 3 5

68 Fixed cumulative sum loop
A corrected version of the sum loop code: int sum = 0; for (int i = 1; i <= 1000; i++) { sum = sum + i; } System.out.println("The sum is " + sum); Key idea: Cumulative sum variables must be declared outside the loops that update them, so that they will exist after the loop.

69 Cumulative product This cumulative idea can be used with other operators: int product = 1; for (int i = 1; i <= 20; i++) { product = product * 2; } System.out.println("2 ^ 20 = " + product); How would we make the base and exponent adjustable?

70 Multi-line loop body System.out.println("+----+");
for (int i = 1; i <= 3; i++) { System.out.println("\\ /"); System.out.println("/ \\"); } Output: +----+ \ / / \

71 Loops with if/else if/else statements can be used with loops or methods: int evenSum = 0; int oddSum = 0; for (int i = 1; i <= 10; i++) { if (i % 2 == 0) { evenSum = evenSum + i; } else { oddSum = oddSum + i; } System.out.println("Even sum: " + evenSum); System.out.println("Odd sum: " + oddSum);

72 Expressions for counter
int highTemp = 5; for (int i = -3; i <= highTemp / 2; i++) { System.out.println(i * ); } Output:

73 Counting down The update can use -- to make the loop count down.
The test must say > instead of < System.out.print("T-minus "); for (int i = 10; i >= 1; i--) { System.out.print(i + ", "); } System.out.println("blastoff!"); Output: T-minus 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, blastoff!

74 Loop tables What statement in the body would cause the loop to print:
To see patterns, make a table of count and the numbers. Each time count goes up by 1, the number should go up by 5. But count * 5 is too great by 3, so we subtract 3. count number to print 5 * count 1 2 5 7 10 3 12 15 4 17 20 22 25 5 * count - 3 2 7 12 17 22

75 Loop tables question What statement in the body would cause the loop to print: Let's create the loop table together. Each time count goes up 1, the number printed should ... But this multiple is off by a margin of ... count number to print 1 17 2 13 3 9 4 5 -4 * count -4 -8 -12 -16 -20 -4 * count -4 * count + 21 -4 17 -8 13 -12 9 -16 5 -20 1

76 Redundancy between loops
for (int j = 1; j <= 5; j++) { System.out.print(j + "\t"); } System.out.println(); System.out.print(2 * j + "\t"); System.out.print(3 * j + "\t"); System.out.print(4 * j + "\t"){ Output:

77 Nested loops nested loop: A loop placed inside another loop. Output:
for (int i = 1; i <= 4; i++) { for (int j = 1; j <= 5; j++) { System.out.print((i * j) + "\t"); } System.out.println(); // to end the line Output: Statements in the outer loop's body are executed 4 times. The inner loop prints 5 numbers each time it is run.

78 Nested for loop exercise
What is the output of the following nested for loops? for (int i = 1; i <= 6; i++) { for (int j = 1; j <= 10; j++) { System.out.print("*"); } System.out.println(); Output: **********

79 Complex lines What nested for loops produce the following output?
....1 ...2 ..3 .4 5 We must build multiple complex lines of output using: an outer "vertical" loop for each of the lines inner "horizontal" loop(s) for the patterns within each line outer loop (loops 5 times because there are 5 lines) inner loop (repeated characters on each line)

80 Outer and inner loop First write the outer loop, from 1 to the number of lines. for (int line = 1; line <= 5; line++) { ... } Now look at the line contents. Each line has a pattern: some dots (0 dots on the last line) a number ....1 ...2 ..3 .4 5

81 Nested for loop exercise
What is the output of the following nested for loops? for (int line = 1; line <= 5; line++) { for (int j = 1; j <= (-1 * line + 5); j++) { System.out.print("."); } for (int k = 1; k <= line; k++) { System.out.print(line); System.out.println(); Answer: ....1 ...22 ..333 .4444 55555

82 Drawing complex figures
Use nested for loops to produce the following output. Why draw ASCII art? Real graphics require a lot of finesse ASCII art has complex patterns Can focus on the algorithms #================# | <><> | | <>....<> | | <> <> | |<> <>|

83 3 Type of Errors might be in your program
i-Compile Errors Compile errors occurs on attempting to compile your file Compile errors prevent the creation of the .class file Compile error occurs when a syntax rule is not obeyed ii-Runtime Errors Runtime errors occurs after the program has compiled successfully and is running Runtime error in java are called Exceptions Exceptions can occur for many reasons including a wrong input from user or a certain resource (eg. A file) that was not found. iii-Logic Error The class compiled and run without reporting any errors The task is not executed correctly due to algorithmic error

84 Exercises Using just the ahead and turnRight/turnLeft methods create a robot that travels in a complete square once, beginning from its starting position. Make the robot travel 150 units for each side of the square. Using a for loop create a robot that travels in a complete square 10 times. Adapt the code so that it uses a loop that repeats four times to control the forward movement and turns.

85 The main voltage supplied by a substation is measured at hourly intervals over a 72-hour period, and a report made. Write a program to read in the 72 reading array and determine: the mean voltage measured the hours at which the recorded voltage varies from the mean by more than 10% any adjacent hours when the change from one reading to the next is greater than 15% of the mean value

86 We wish to solve the following problem using Java
We wish to solve the following problem using Java. given an array A, print all permutations of A (print all values of A in every possible order). For example, A contained the strings “apple”, “banana”, and “coconut”, the desired output is: apple banana coconut apple coconut banana banana apple coconut banana coconut apple coconut apple banana coconut banana apple

87 Write a Java application which prints a triangle of x's and y's like the one below. Each new line will have one more x or y than the preceding line. The program should stop after it prints a line with 80 characters in it. You may make use of both the Write() and WriteLine() methods. For example; x yy xxx yyyy xxxxx

88 A year with 366 days is called a leap year
A year with 366 days is called a leap year. A year is a leap year if it is divisible by 4 (for example, 1980). However, since the introduction of the Gregorian calendar on October 15, 1582, a year is not a leap year if it is divisible by 100 (for example, 1900); however, it is a leap year if it is divisible by 400 (for example, 2000). Write program (not a whole class) that accepts an int argument called “year” and returns true if the year is a leap year and false otherwise.

89 A number of students are answering a questionnaire form that has 25 questions. Answer to each question is given as an integer number ranging from 1 to 5. Write a program that first reads the number of students that have left the fulfilled questionnaire. After that the programs reads answers so that first answers of the first student are entered starting from question 1 and ending to question 25. Answers of second student are then read in similar way. When all answers are entered the program finds out what are questions (if any) to which all students have given the same answer. Finally the program displays those questions (the question numbers).

90 Write a console application that inputs the grads of 100 students and counts the number of students with grad ‘A’ or ‘a’ and ‘B’ or ‘b’ and ‘C’ or ‘c’ and ‘D’ or ‘d’ and ‘F’ or ‘f’

91 Using a while loop create a robot that travels in a square forever (or until the round ends anyway).
Alter your robot so that it counts the number of squares it has travelled and writes this to the console.


Download ppt "Java Java Basics."

Similar presentations


Ads by Google