Last modification: 20/09/2016
Standard input and output are handled using the java.lang.System
class:
System.out
.System.in
.System.err
.Write a ’’Hello World!`` program.
Create a modified version of the program that kindly greets a person, whose name is taken from the standard input. For instance:
$ java GreetingsA
Hi! What's your name?
~> Smith
Welcome Smith, how do you do?
Here ‘’~>
’’ denotes the input to the program.
Create an other version of the program that takes the person’s name from the argument list. For instance:
$ java GreetingsB Jeremy
Welcome Jeremy, how do you do?
Text is represented with the java.lang.String
class. Here is how to convert numbers to and from text.
Convert numbers to texts: String s = "" + 2
, String s = String.valueOf(2)
, String trees = 2 + " trees"
Convert texts to numbers: int n = Integer.parseInt("5")
, double d = Double.parseDouble("3.14")
etc.
Write a program that takes two integers from the standard input and produces the following output:
$ java IntOpts
Please type two integers!
~> 17
~> 3
17 * 3 = 51
17 / 3 = 5
17 % 3 = 2
17 = 3 * 5 + 2
If the second integer equals zero then only the product should be written.
Create a program that takes \(a\) and \(b\) integers as arguments and computes \(a^b\). Use iteration in your program.
Assume that \(b\) is not negative.
\(b\) can be negative as well.
For instance:
$ java Power 2 4
16
$ java Power 2 -3
0.125
Extra exercise. Create a program that produces the powers of two to a given exhibitor, which is taken as argument. At the beginning check that the exhibiror is provided. Use loops, not the Math.pow()
method.
$ java Powers2 4
1
2
4
8
16
Intermediate level. Create a program that computes the solutions of a quadratic equation, assuming that both solution is real. For instance the solutions to the equation \(x^2 + 3 \cdot x + 2 = 0\) are computed as follows.
$ java Quadratic 1.0 3.0 2.0
x1 = -2
x2 = -1
Hint:
use the methods of the java.lang.Math
class.
The solutions to an arbitrary quadratic equation are: \(x_1 = \frac{-b + \sqrt{b^2 - 4 \cdot a \cdot c}}{2 \cdot a}\), \(x_2 = \frac{-b - \sqrt{b^2 - 4 \cdot a \cdot c}}{2 \cdot a}\)
Intermediate level. Create a program that decides whether or not a given year is leap year. The year is taken as argument.
Leap years are divisible by 4 except those that are divisible by 100 but those that are divisible by 400 are still leap years. For instance 2004 and 2008 are leap years because both is divisible by 4 but not by 100. 1600 is also a leap year, because it is divisible by 400.