Using the provided recording and your knowledge from programming 1. Create a program in java that takes in an input from the user and checks whether it’s a number or a word. In case a number is entered the program should print the number to the power 3 and if a word is entered your program should split that word into 2.
Sample Run 1
Enter a number or word: 7
Output 1:
7 to the power 3= 343
Sample Run 2
Enter a number or word: NAMIBIA
Output 2:
The word split in half is : NAMI and BIA
import java.util.*;
class App {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a number or word: ");
String input = keyboard.next();
try {
Integer inputInt = Integer.valueOf(input);
System.out.println(inputInt + " to the power 3 = " + (inputInt * 3));
} catch (NumberFormatException e) {
int middle = input.length() / 2;
if (input.length() % 2 != 0) {
middle = (input.length() + 1) / 2;
}
String firstPart = input.substring(0, middle);
String secondPart = input.substring(middle);
System.out.println("The word split in half is: " + firstPart + " and " + secondPart);
}
keyboard.close();
}
}
Comments
Leave a comment