CS2514

Introduction to Java

Dr Derek Bridge

School of Computer Science & Information Technology

University College Cork

Classes

Class definitions

Another example of objects and classes

import statements

Class exercise

In the Japanese dice game of Kitsune Bakuchi, three dice are rolled. If all three show the same value, the player wins four times his/her stake; otherwise he or she loses his/her stake.

Code this game in Java.

But first you need to know how to do if-statements in Java...

Conditional statements

PythonJava
if x < y:
    print('x is smaller than y')
elif x == y:
    print('x is equal to y')
else:
    print('x is larger than y')
 
if (x < y) {
    System.out.println('x is smaller than y');
} else if (x == y) {
    System.out.println('x is equal to y');
} else {
    System.out.println('x is larger than y');
}

In the Java, note:

Boolean expressions

Solution

import java.util.Scanner;
import java.util.Random;

class KitsuneBakuchi {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Random dice = new Random();
        
        System.out.print("How much do you want to wager: ");
        int wager = sc.nextInt();
        
        int roll1 = dice.nextInt(6) + 1;
        int roll2 = dice.nextInt(6) + 1;
        int roll3 = dice.nextInt(6) + 1;
        
        int winnings = 0;
        if (roll1 == roll2 && roll2 == roll3) {
            winnings = 4 * wager;
        }
        
        System.out.println("Your rolled " + roll1 + " " + roll2 + " " + roll3);
        System.out.println("You win " + winnings);
    }

}

Another example of objects and classes

String objects

Quick quiz

Q: What do we learn from the following?

PythonJava
s = "Goodbye"
n = len(s)
String s = "Goodbye";
int n = s.length();

String interface

String methods

The concatenation operator

Concatenation using +

...So what do these produce?

int x = 25;
int y = 14;

System.out.println("My favourite number is " + x + y);

System.out.println(x + y + " is my favourite number");

Strings are immutable

Advanced point