JAVA: Easy Java Programming for Beginners, Your Step-By-Step Guide to Learning Java Programming (2015)
Practice Exercises
Exercise #1:
Write a program that will display every command-line argument and the total number of arguments.
CLUE: Use an array variable named length to determine the length of the array.
Exercise #2:
Write a program that will round off a series of ten random numbers from 0 to 100. Round each one of them, then display the result to the screen. Take note of the following:
· Create a class and a main() method for the calculation.
· Use the for loop statement.
· Use the Math.random() to generate the ten random numbers. To get a number between 0 to 100, simply multiply the random number by 100.
· Round the number using the Math.round() method. Rounding off is necessary because the random() method always returns a value less than 1.0.
· Display the rounded number to the screen.
Exercise #3:
Write a program that will create a new Parent class under a main Family class. The objective is also to display the line of text “What a wonderful day!” on the screen.
Practice Exercises Answers
Answer for Exercise #1:
public class MainPractice {
public static void main (String [] args) {
for (int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
System.out.print("Total Words: " + args.length);
}
}
Answer for Exercise #2:
public class MathRandomRound {
public static void main (String [] argh) {
for (int i = 0; i < 10; i++) {
double num = Math.random() * 100;
System.out.print("The number " + num);
System.out.println(" rounds to " + Math.round(num));
}
}
}
Answer for Exercise #3:
class Parent {
}
public class Family {
public static void main(String[] args) {
System.out.println("What a wonderful day!");
Parent parent = new Parent();
}
}