USDY COMP9103 (Software Development in Java) Ed Challenges

Practice

Hello from Java

Description
Write a program that outputs the line "Hello from Java!" to standard output.

Example:

Hello from Java!

Hint: Make sure that the name of your class corresponds exactly to the name of the file, for example: Cat when the file is Cat.java

Solution

class Hello {
    public static void main(String[] args) {
        System.out.print("Hello from Java!");
    }
}

Greetings

Description
Write a program that asks a user for their name from standard input, and then outputs "Hello, <name>!"

Example:

Enter your name: Ed
Hello, Ed!

Hint: You can use the nextLine() method to get everything that was inputted in the line.

Solution

public class Greet {
    public static void main(String[] args) {
        java.util.Scanner input = new java.util.Scanner(System.in);
        System.out.print("Enter your name: ");
        String name = input.nextLine();
        System.out.println("Hello, " + name + "!");
    }
}

Talking with Clarence

Description
You are to write a program that takes a name from the command line arguments and has a chat with Clarence

To refer to the first argument from the command line you can use:

args[0]

You can also assign args[0] to a string

String name = args[0];

Example output

David: "Hi, where are you?"
Clarence: "Currently at the Cafe!"
David: "Okay! See you there!"

Solution

public class TalkingWithClarence {

    public static void main(String[] args) {
        
        if (args.length < 1) {
            return;
        }
        
        String name = args[0];
        System.out.println(name + ": \"Hi, where are you?\"");
        System.out.println("Clarence: \"Currently at the Cafe!\"");
        System.out.println(name + ": \"Okay! See you there!\"");
    }
}

Sum of Two

Description
Write a program that reads in two integers from standard input and then outputs their sum.

Example 1

Input

1 2

Output

3

Example 2

Input

24 -2

Output

22

Hint: For this challenge you don't need to output any prompts for input, simply read two numbers from standard input.

Solution

import java.util.*;

public class Sum {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int first = input.nextInt();
        int second = input.nextInt();
        System.out.println(first + second);
    }
}

Week 2

Length of String

Description
In this challenge question are asking you to get the length of a string given via command line arguments. You can get the length of a String by using the .length() method associated with it.

Example Output of

java StringLength Test
Test is 4 characters long

Solution

public class StringLength {

    public static void main(String[] args) {
        if(args.length < 1) {
            return;
        }
        String str = args[0];
        int length = str.length();
        System.out.println(str + " is " + length + " characters long");
    }

}

Dot Product

Description
Using the arguments provided in the function, print out the vectors and, compute and print out the dot product

Vector 1 is denoted by v and Vector 2 is denoted by u

To calculate dot product of 3 dimensions:

V = [1, 5, 6]

U = [7, 2, 4]

V . U = (17) + (52) + (6*4)

Example Output:

V = { 1, 2, 3 }
U = { 3, 2, 1 }
V . U = 10

Solution

public class DotProduct {

    public static void main(String[] args) {
        
        if (args.length < 6) {
            return;
        }
        
        int v1 = Integer.parseInt(args[0]);
        int v2 = Integer.parseInt(args[1]);
        int v3 = Integer.parseInt(args[2]);
        int u1 = Integer.parseInt(args[3]);
        int u2 = Integer.parseInt(args[4]);
        int u3 = Integer.parseInt(args[5]);
        
        // TODO
        System.out.printf("V = { %d, %d, %d }%n", v1, v2, v3);
        System.out.printf("U = { %d, %d, %d }%n", u1, u2, u3);
        System.out.println("V . U = " + (v1 * u1 + v2 * u2 + v3 * u3));
    }
}

Simple Calc

Description
We currently have a broken calculator and we need to get basic functions working. When we enter in two numbers they should be added, subtracted, multiplied and divided. This calculator only works with integers as well.

The program runs using the arguments 9 and 8

Sample Output with 1 and 2:

ADD: 3
SUBTRACT: -1
MULTIPLY: 2
DIVIDE: 0

Solution

public class SimpleCalc {

    public static void main(String[] args) {

        if (args.length < 2) {
            return;
        }
        
        int n1 = Integer.parseInt(args[0]);
        int n2 = Integer.parseInt(args[1]);
        
        // TODO
        System.out.println("ADD: " + (n1 + n2));
        System.out.println("SUBTRACT: " + (n1 - n2));
        System.out.println("MULTIPLY: " + (n1 * n2));
        if (n2 == 0) {
            System.out.println("DIVIDE: 0");
        } else {
            System.out.println("DIVIDE: " + (n1 / n2));
        }
    }
}

Volume of Cylinder

V = π ⋅ r2 ⋅ h
You are tasked with writing a program to calculate the area of the base of the cylinder and the volume of the cylinder using the radius and height specified in the command line by the user.

Your program should take two command line arguments. The first argument is the radius of the base of the cylinder. The second one is the height of the cylinder.

Since command line arguments are stored as Strings, you will need to use Double.parseDouble() method to convert it to a double value.

If the number of command line arguments is smaller than two, your program should output:

Not enough arguments.

If the number of command line arguments is greater than two, your program should output:

Too many arguments.

If the radius is negative, your program should output (without checking the value of the height):

Radius cannot be negative.

If the radius is non-negative but the height is negative, your program should output:

Height cannot be negative.

For all situations listed above, the program should terminate immediately after the message has been printed.

The value for PI will should be set as a constant with the value 3.141592. (You should declare a variable with final keyword)

You can assume that the values for radius and height will always be decimal numbers.

The volume of the cylinder can be calculated using the formula:

V=π ⋅ r2 ⋅ h

Your program should display the volume up to 2 decimal places. (use System.out.printf() method)

Solution

public class VolumeOfCylinder {
    public static final double PI = 3.141592;
    public static void main(String[] args) {
        if (args.length < 2) {
            System.out.println("Not enough arguments.");
            return;
        }
        
        if (args.length > 2) {
            System.out.println("Too many arguments.");
            return;
        }
        
        double radius = Double.parseDouble(args[0]);
        
        double height = Double.parseDouble(args[1]);
        
        if (radius < 0) {
            System.out.println("Radius cannot be negative.");
            return;
        }
        
        if (height < 0) {
            System.out.println("Height cannot be negative.");
            return;
        }
        
        System.out.printf("The volume of the cylinder is %.2f.%n", PI * radius * radius * height);
    }
}

Golden Ratio *

Description
Golden ratio is possibly the best known irrational number and is found everywhere from architectural works and paintings to many patterns in nature, such as the spiral arrangement of the leaves and the connection being drawn between the golden ratio and human genome DNA. The popularity of this ratio is explained by the fact it is supposed to be aesthetically pleasing.

Write a program that reads two numbers from the standard input and finds whether they are in the golden ratio. The numbers can be provided in any order, i.e. a followed by b or b followed by a. If any of the inputs provided are not numeric, your program should print an errror message as shown in Example 4 and terminate.

Two quantities a and b constitute the golden ratio if the following expression is true:

Interestingly, this ratio always equals to the following irrational number:

Example 1

Enter two numbers: 61.8 38.2

Golden ratio!

Example 2

Enter two numbers: 38.2 61.8

Golden ratio!

Example 3

Enter two numbers: 1.2 2.4

Maybe next time.

Example 4

Enter two numbers: a b

Invalid input.

Note that you only need to compare the ratios with up to 3 decimal points precision. For example, 1.6181 should be considered equal to 1.6178 since they both can be rounded to 1.618.

This challenge requires the use of an if statement

Solution

public class GoldenRatio {

    public static void main(String[] args) {
    
        System.out.print("Enter two numbers: ");
        
        java.util.Scanner input = new java.util.Scanner(System.in);
        
        if (!input.hasNextDouble()) {
            System.out.println("\nInvalid input.");
            return;
        }
        
        Double a = input.nextDouble();
        
        if(!input.hasNextDouble()) {
            System.out.println("\nInvalid input.");
            return;
        }
        
        Double b = input.nextDouble();
        
        if (b > a) {
            Double c = a;
            a = b;
            b = c;
        }
        
        Double left = (a + b) / a;
        
        Double right = a / b;
        
        // 只需要比较小数点后面三位数字,四舍五入法
        System.out.println(Math.abs(left - right) <= 0.0095 ? "\nGolden ratio!" : "\nMaybe next time.");
    }
}

Week 3

Compare Two Numbers

Description
You are tasked with writing a program that will take two numbers from standard input and evaluate if the first number is greater than the second

Example 1 output (args[0] = 7, args[1] = 8):

Is 7 > 8? false

Example 2 output (args[0] = 9, args[1] = 4):

Is 9 > 4? true

Solution

public class IsFirstGreater {
    
    public static int parseInt(String arg) {
        int x = -1;
        try {
            x = Integer.parseInt(arg);
        } catch (NumberFormatException e) {
            //ignore!
            x = -1;
        }
        return x;
    }
    
    public static void main(String[] args) {
        if(args.length < 2) {
            return;
        }
        int n1 = parseInt(args[0]);
        int n2 = parseInt(args[1]);
        //Your code goes here
        System.out.printf("Is %d > %d? %s%n", n1, n2, n1 > n2);
    }
    
}

Fizz Buzz

Description
Write a program that outputs the numbers from 1 to 100, unless:

The number is a multiple of 3, then output Fizz

The number is a multiple of 5, then output Buzz

The number is a multiple of both 3 and 5, then output FizzBuzz

Example

No input will be given

The output will be as follows

1
2
Fizz
4
Buzz
...

Hint: In this challenge, you want to use a loop that iterates from 1 to 100, along with if statements inside the body of the loop.

Solution

// your code here
class FizzBuzz {
    public static void main(String[] args) {
        for (int i = 1; i <= 100; i++) {            
            String result = "";
            if (i % 3 == 0) {
                result += "Fizz";
            }
            if (i % 5 == 0) {
                result += "Buzz";
            }
            if (result.isEmpty()) {
                result += i;
            }
            System.out.println(result);
        }
    }
}

Apollo 11

Description
Apollo 11 was the first space flight that landed humans on the Moon. The spacecraft was launched by a Saturn V rocket from the John F Kennedy Space Centre on July 16 of 1969.

Write a program that simulates the launch countdown of Apollo 11 as shown below. Make sure to follow the output shown exactly.

Hint: You should use loops to complete this challenge.

Guidance is internal.
12...
11...
10...
9...
8...
7...
Ignition sequence start.
6...
5...
4...
3...
2...
1...
All engine running.
Lift off on Apollo 11!

Solution

// your code here
class Apollo {
    public static void main(String[] args) {
        String[] stages = new String[]{
            "Guidance is internal.",
            "12...",
            "11...",
            "10...",
            "9...",
            "8...",
            "7...",
            "Ignition sequence start.",
            "6...",
            "5...",
            "4...",
            "3...",
            "2...",
            "1...",
            "All engine running.",
            "Lift off on Apollo 11!"
        };
        
        for (String stage: stages) {
            System.out.println(stage);
        }
    }
}

Command Line Calculator

Description
Your are tasked to complete a program that takes in 3 command line arguments in the form number character number. The second argument relates to the type of operation that will be applied to the first and third argument.

You do need to handle the case where someone could divide by zero and output

Attempted Divide By Zero

Example 1:

java CommandCalculator 5 + 10

Output

15

Example 2:

java CommandCalculator 1 / 1

Output

1

Solution

public class CommandCalculator {
    
    public static void main(String[] args) {
        if(args.length < 3) {
            return;
        }
        
        int num1 = Integer.parseInt(args[0]);
        String operation = args[1];
        int num2 = Integer.parseInt(args[2]);
        
        switch(operation) {
            case "+":
                System.out.println(num1 + num2);
                break;
            case "-":
                System.out.println(num1 - num2);
                break;
            case "*":
                System.out.println(num1 * num2);
                break;
            case "/":
                if (num2 == 0) {
                    System.out.println("Attempted Divide By Zero");
                    break;
                }
                System.out.println(num1 / num2);
                break;
        }
    }
}

Box

Description
Write a program that displays a filled in box of a specified area.

Use the asterisk * character when outputting the box with given dimensions.

Width and height of the box will be passed to the program as command line arguments.

If any arguments are invalid, missing or extra then output the corresponding message in the examples below and quit.

Your program will be run with the following arguments:

$ java Box <width> <height>

Tips

  • When running your code, you can specify the command line arguments in the command text box under the console.

  • No need to use the Scanner for this challenge, instead you should get the width and height from the command line arguments.

  • Remember to check check whether any arguments are invalid, missing or extra then then output the corresponding message in the examples below and quit. You can assume the arguments provided will always be integers.

Example 1

$ java Box
No arguments

Example 2

$ java Box 4
Too few arguments

Example 3

$ java Box 4 5 6
Too many arguments

Example 4

$ java -2 4
Negative width

Example 5

$ java Box 4 -2
Negative height

Example 6

$ java -2 -4
Negative dimensions

Example 7

$ java Box 4 4
****
****
****
****

Example 8

$ java Box 6 4
******
******
******
******

Example 9

$ java Box 8 4
********
********
********
********

Example 10

$ java Box 1 1
*

Example 11

$ java Box 1 0
No output

Example 12

$ java Box 0 0
No output

Solution

public class Box {

    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("No arguments");
            return;
        } else if (args.length < 2) {
            System.out.println("Too few arguments");
            return;
        } else if (args.length > 2) {
            System.out.println("Too many arguments");
            return;
        }
        
        int width = Integer.parseInt(args[0]);
        int height = Integer.parseInt(args[1]);
        
        if (width < 0 && height < 0) {
            System.out.println("Negative dimensions");
            return;
        }
        
        if (width < 0) {
            System.out.println("Negative width");
            return;
        }
        
        if (height < 0) {
            System.out.println("Negative height");
            return;
        }
        
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
    
}

Odd or Even

Description
Write a program that asks the user for a number from standard input and then displays whether the number is odd or even.

Example 1

Enter a number: 1
The number 1 is odd.

Example 2

Enter a number: 2
The number 2 is even.

Hint: You can use the modulus operator % to return the remainder of division of two numbers, for example 5 % 3 is 2.

Solution

class OddEven {
    public static void main(String[] args) {
        System.out.print("Enter a number: ");
        java.util.Scanner input = new java.util.Scanner(System.in);
        int num = input.nextInt();
        System.out.printf("The number %d is %s.%n", num, num % 2 == 0 ? "even" : "odd");
    }
}

Roman Numerals *

Description
When someone mentions numbers or numerals, they most likely mean the Hindu-Arabic numerical system, which represents each number using the following digits: 1, 2, 3, 4, 5, 6, 7, 8, 9 and 0. However, it was not until the Middle Ages that people in Europe started using Arabic numerals. Before that, people who could write and count used Roman numerals.

Write a program that takes an Arabic number and converts it to a Roman numeral. If the provided input is not a number, your program should indicate that as shown in the examples below. You can assume that numbers will be 1≤n≤4999.

Roman numerals use letters of the Latin alphabet to represent numbers. Every number can be expressed using the following seven digits:

I = 1

V = 5

X = 10

L = 50

C = 100

D = 500

M = 1000

These digits are then combined to represent specific numbers, for example, 350 can be represented as CCCL. In order to prevent long sequences of repeated numbers, such as IIII, Roman numeric system uses subtractive notation:

IV = 4

IX = 9

XL = 40

XC = 90

CD = 400

CM = 900

For your reference, numbers from 1 to 10 are represented as follows:

I II III IV V VI VII VIII IX X

Example 1

Enter a number: 2016

Roman equivalent is MMXVI

Example 2

Enter a number: 1999

Roman equivalent is MCMXCIX

Example 3

Enter a number: abc

Not a number.

Solution

public class RomanNumerals {
    public static void main(String[] args) {
        Integer[] rabicNums = new Integer[]{
            1,
            2,
            3,
            4,
            5,
            6,
            7,
            8,
            9,
            10,
            40,
            50,
            90,
            100,
            400,
            500,
            900,
            1000
        };

        String[] romanNums = new String[]{
            "I",
            "II",
            "III",
            "IV",
            "V",
            "VI",
            "VII",
            "VIII",
            "IX",
            "X",
            "XL",
            "L",
            "XC",
            "C",
            "CD",
            "D",
            "CM",
            "M"
        };

        System.out.print("Enter a number: ");

        java.util.Scanner input = new java.util.Scanner(System.in);

        if (!input.hasNextInt()) {
            System.out.println("\nNot a number.");
            return;
        }

        int num = input.nextInt();

        String result = "";

        int res = num;

        solve:
        while (res > 0) {
            for (int i = 0; i < rabicNums.length; i++) {
                if (rabicNums[i] == res) {
                    result += romanNums[i];
                    break solve;
                }
            }

            int j = 9;
            for (; j < rabicNums.length; j++) {
                if (rabicNums[j] > res) {
                    break;
                }
            }
            result += romanNums[j - 1];
            res -= rabicNums[j - 1];
        }

        System.out.println("\nRoman equivalent is " + result);
    }
}

注:持续更新中。。。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,236评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,867评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,715评论 0 340
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,899评论 1 278
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,895评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,733评论 1 283
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,085评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,722评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,025评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,696评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,816评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,447评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,057评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,009评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,254评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,204评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,561评论 2 343

推荐阅读更多精彩内容