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);
}
}
注:持续更新中。。。