Variables, Conditionals and Exercises

Java 101 - Class 1

What we want to achieve

  • Exercises

  • Debugging

  • תנאי מקוצר - ternary conditional operator

  • MyConsole and Scanner

  • compilation and runtime errors

  • compiling and running via cmd/terminal

  • טבלת מעקב (מצגות)

What we learnt in class

  • חשבון ומודלו

  • if and if-else

  • printing to screen System.out.println

  • while

  • Interger.MAX_VALUE

  • המרת מספרים מממשי לבינראי ולהיפך

Exercises

I0 - קלט ופלט

פלט נעשה ע"י הפקודה

System.out.println("hello 👋")

ברוב הide נוכל לכתוב syso או sout כדי שהide ישלים אותנו אוטומטית

בקלט יש לנו 2 דרכים

  • Scanner

  • MyConsole (מה שלמדים בהתחלה בשיעור)

MyConsole

public class Main {
    public static void main(String[] args) {
        int myInt = MyConsole.readInt("enter int: ");
        double myDouble = MyConsole.readDouble("enter double: ");
        String myString = MyConsole.readString("enter word: ");

        System.out.println("\nint is: " + myInt);
        System.out.println("double is: " + myDouble);
    }
}
enter int:  4.5
Not an integer. Please try again!
enter int:  7
enter double:  10.51

int is: 7
double is: 10.51
string is: hello

Scanner

Scanner scanner = new Scanner(System.in);
String myString = scanner.next();
int myInt = scanner.nextInt();
scanner.close();

System.out.println("myString is: " + myString);
System.out.println("myInt is: " + myInt);

input:

Hi 5

output:

myString is: Hi
myInt is: 5

Variables

משתנים פרימיטיבים

Image Source

public class Main {
    public static void main(String[] args) {
        byte tinyNum  =  100;
        short smallNum = 20_000;
        int num = 1<<20;
        long largeNum = (long) 1<<50;
        float decimal = 10.5050f;
        double largeDecimal = 3.141592653589;
        boolean trueOrFalse = true;

        System.out.println(num);
        System.out.println(largeNum);
        System.out.println(decimal);

        if (trueOrFalse)
            System.out.println("true");
        else
            System.out.println("false");
    }
}
1048576
1125899906842624
10.505
true

if and if else

Wikipedia if-else flow chart

תרגיל: תנאים

Given an integer n , perform the following conditional actions:

  • If n is odd, print Strange

  • If n is even and in the inclusive range of 2 to 5 , print Not Strange

  • If n is even and in the inclusive range of 6 to 20, print Strange

  • If n is even and greater than 20, print Not Strange

Solution

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        System.out.print("Enter an integer: ");
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();

        if (n%2==1)
            System.out.println("Strange");
        else if (n%2==0 && n>=2 && n<=5)
            System.out.println("Not Strange");
        else if (n%2==0 && n>=6 && n<=20)
            System.out.println("Strange");
        else if (n%2==0 && n>20)
            System.out.println("Not Strange");
    }
}
Enter an integer: 20
Strange

תרגיל: האם זה שנה מעוברת

כתבו תוכנית המחזיר האם השנה הוא שנה מעוברת או לא

To determine whether a year is a leap year, follow these steps:

  1. If the year is evenly divisible by 4, go to step 2. Otherwise, go to step 5.

  2. If the year is evenly divisible by 100, go to step 3. Otherwise, go to step 4.

  3. If the year is evenly divisible by 400, go to step 4. Otherwise, go to step 5.

  4. The year is a leap year (it has 366 days).

  5. The year is not a leap year (it has 365 days).

examples:

  • 1600 ✔️ leap year

  • 1700 ❌ not leap year

  • 1800 ❌ not leap year

  • 1900 ❌ not leap year

  • 2000 ✔️ leap year

  • 2001 ❌ not leap year

  • 2004 ✔️ leap year

package com.company;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("enter year: ");
        int year = sc.nextInt();

        boolean four = ((year % 4) == 0);
        boolean hundred = ((year % 100) == 0);
        boolean fourhundred = ((year % 400) == 0);
        boolean isleapyear = fourhundred || (four && !hundred);
        System.out.println(year + " is a leap year? " + isleapyear);
        sc.close();
    }
}
enter year: 2021
2021 is a leap year? false

בא עכשיו לגרום לתוכנית לא להפסק

package com.company;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int year=-1;
        while (year!=0) {
            System.out.print("enter year: ");
            year = sc.nextInt();
            boolean four = ((year % 4) == 0);
            boolean hundred = ((year % 100) == 0);
            boolean fourhundred = ((year % 400) == 0);
            boolean isleapyear = fourhundred || (four && !hundred);
            System.out.println(year + " is a leap year? " + isleapyear);
        }
        sc.close();
    }
}
enter year: 2020
2020 is a leap year? true
enter year: 2021
2021 is a leap year? false
enter year: 0
0 is a leap year? true

כמו שניתן לשים לב, עטפנו את התוכנית שלנו עם while

while (year!=0) {
    ...
}

שים לב שמנו את Scanner בחוץ ככה לא נצטרך פעם לייצר משתנה חדש כל פעם. בנוסף גם הסגירה שלו בחוץ

תרגילים: המרות

מה יהיה הפלט?

public class Main {
    public static void main(String[] args) {
        int x = 8, y = 13;
        double d = y/x;
        System.out.println("y/x = "+d);
        d = (double)y/x;
        System.out.println("y/x = "+d);
        double a = 5, b = 18;
        int c = (int)(a/b);
        System.out.println("a/b = "+c);
    }
}
y/x = 1.0
y/x = 1.625
a/b = 0

שאלו את עצמכם למה ההדפסה הראשונה יוצא 1.0 🤔

מה יהיה הפלט?

public class Main {
    public static void main(String[] args) {
        double num = 123.45687;
        System.out.println((int)(num * 100) / 100.0);
    }
}
123.45

מה יהיה הפלט?

public class Main {
    public static void main(String[] args) {
        float x = (float)1.0, y = 3.0f, z=99;
        System.out.println(x/y);
        System.out.println(z);
    }
}
0.33333334
99.0

כאן הכזרנו על 3 משתני float

לולי היינו עושים ככה הקוד לא מתקפל

float x = (float)1.0, y = 3.0, z=99;

לא היה מתקפל כי ה y היה double. לזה קוראים compilation error

Runtime Error

public class Main {
    public static void main(String[] args) {
        System.out.println("Integer.MAX_VALUE = "+Integer.MAX_VALUE);
        System.out.println("Integer.MIN_VALUE = "+Integer.MIN_VALUE);
        System.out.println("Integer.SIZE = "+Integer.SIZE);
        int x = Integer.MAX_VALUE + 1;
        System.out.println("Integer.MAX_VALUE + 1 = "+x);
        int a = 0, b=10, z;
        z = b/a;
        System.out.println("b/a = "+z);
    }
}
Integer.MAX_VALUE = 2147483647
Integer.MIN_VALUE = -2147483648
Integer.SIZE = 32
Integer.MAX_VALUE + 1 = -2147483648
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at com.company.Main.main(Main.java:11)

מאוחר יותר נלמד על try וcatch שיעזרו לנו להתמודד עם שגיאות

תרגיל

כתבו אם מספר הוא int, short or long

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        System.out.print("Enter an integer: ");
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();

        if (Short.MAX_VALUE>=n && Short.MIN_VALUE<=n)
            System.out.println("n is a: short");
        else if (Integer.MAX_VALUE>=n && Integer.MIN_VALUE<=n)
            System.out.println("n is an: int");
        else if (Long.MAX_VALUE>=n && Long.MIN_VALUE<=n)
            System.out.println("n is a: long");
    }
}
Enter an integer: 100000
n is an: int

מספר שלם עובד לנו, אבל מה קורה במספר ממשי

Enter an integer: 10.5
Exception in thread "main" java.util.InputMismatchException
    at java.base/java.util.Scanner.throwFor(Scanner.java:939)
    at java.base/java.util.Scanner.next(Scanner.java:1594)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
    at com.company.Main.main(Main.java:8)

קיבלנו Runtime error

על הדרך בא נוסיף גם while ככה שכל עוד הקלט אינו 0 הוא ימשיך לבקש

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        System.out.print("Enter a number: ");
        Scanner scanner = new Scanner(System.in);
        double n = scanner.nextDouble();

        while (n!=0.) {
            if (Short.MAX_VALUE >= n && Short.MIN_VALUE <= n && n % 1 == 0.) {
                System.out.println(n + " can fit in a: ");
                System.out.println("* short\n* int\n* long\n");
            } else if (Integer.MAX_VALUE >= n && Integer.MIN_VALUE <= n && n % 1 == 0.) {
                System.out.println(n + " can fit in a: ");
                System.out.println("* int\n* long\n");
            } else if (Long.MAX_VALUE >= n && Long.MIN_VALUE <= n && n % 1 == 0.)
                System.out.println(n + " can fit in a: \n* long\n");
            else if ((Float.MAX_VALUE >= n && Float.MIN_VALUE <= n) || (Double.MAX_VALUE >= n && Double.MIN_VALUE <= n))
                System.out.println("n is either a: float, double\n");

            //receive next input
            System.out.print("Enter a number: ");
            n = scanner.nextDouble();
        }

        scanner.close();
    }
}
Enter a number: 10.5
n is either a: float, double

Enter a number: 1000000
1000000.0 can fit in a: 
* int
* long

Enter a number: 0

גם היינו יכול לעשות && ((short) n) == n ו ((int) n) == n בתנאי

יש לזה ביצועים יותר גבוההים

Last updated