Exercise 2 Predefined Class
Question 1:
public class PredefinedClass {
public static void main(String[] args) {
String a = "Number", b = "Square", c = "Cube";
System.out.printf("%s%8s%7s", a,b,c);
int n = 0;
do{
double sq = Math.pow(n,2);
double cb = Math.pow(n,3);
System.out.printf("%n%d%10.0f%9.0f",n,sq,cb);
n++;
}while(n<=10);
System.out.println("");
}
}
Question
2:
import java.util.Scanner;
public class CountA {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.print("Input a word: ");
String x = sc.nextLine();
countA(x);
}
public static void countA(String x){
char someChar = 'A';
int count = 1;
for(int i=0; i<x.length();i++){
if(x.charAt(i)==someChar){
count++;
}
}
System.out.println("Total 'A' letters: " + count);
}
}
Question 3:
import java.util.Scanner;
public class PrintReverse {
public static void main(String args[]){
Scanner sc = new Scanner (System.in);
System.out.print("Input a word: ");
String x = sc.nextLine();
printReverse(x);
}
public static void printReverse(String x){
for(int i = x.length()-1; i>=0; i--){
System.out.print(x.charAt(i));
}
System.out.println("");
}
}
Question 4:
import java.util.Scanner;
public class RandomInRange {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.print("Input 1st integer: ");
int y = sc.nextInt();
System.out.print("Input 2nd integer: ");
int z = sc.nextInt();
randomInRange(y,z);
}
public static void randomInRange(int y, int z){
int min, max, ans;
min = y;
max = z;
ans = (int)Math.random()*(max-min+1)+min;
if (y > z){
System.out.println("0");
}
else
System.out.println("The random integer from " + y + " and " + z + " is: "
+ ans);
}
}




Comments