Object-Oriented Programming with Java, part II – Exercise 1

Write a program that reads strings from the user until the user inputs the string “end”. As long as the input is not “end” the program should handle the input as an integer and print the cube of the integer (meaning number * number * number).

My Code

Main

import java.util.Scanner;

public class Cubes {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        String userInput = scanner.nextLine();
        while (!userInput.contentEquals("end")) {
            int x = Integer.parseInt(userInput);
            System.out.println("" + x * x * x + "");
            userInput = scanner.nextLine();
        }
    }
}

Model Code

Main

import java.util.Scanner;

 

public class Cubes {

 

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

 

        while (true) {

            String input = scanner.nextLine();

            if (input.equals("end")) {

                break;

            }

 

            int number = Integer.valueOf(input);

            System.out.println(number * number * number);

        }

    }

}

Comments

I kind of like the use of the if statement which prevents the repeated code userInput = scanner.nextLine(); in mine but otherwise they are essentially the same. It does through an exception if you put in a string that is not end or an integer though.

Leave a comment