I have this homework assignment for this class I'm retaking, the problem I'm running into is that I'm over-thinking the solution. I have to create a program that converts a four digit number to words.
(Example: 1134 becomes "One One Three Four")
I have a basic code, but it's bulky and ugly. I'm also only allowed to use basic if and switch statements, we have to use a switch statement as well.
Am I over thinking this? I can't figure out how to make this code shorter and I only want to use one switch statement without a while loop. Is it even possible or is this as short as it gets.
Here's my code.
import java.util.Scanner;
public class NumberToWords {
public static void main(String[] args) {
//Set up scanner.
Scanner kb = new Scanner(System.in);
//Ask for a 4 digit integer.
System.out.println("Enter a 4 digit number.");
//Store 4 digit number into a variable
int number = kb.nextInt();
//Seperate number into digits.
int digit4 = number%10;
number = number/10;
int digit3 = number%10;
number = number/10;
int digit2 = number%10;
number = number/10;
int digit1 = number%10;
number = number/10;
//Set up a switch statement to read through the number.
switch (digit1)
{
case 1: System.out.print("One ");break;
case 2: System.out.print("Two "); break;
case 3: System.out.print("Three "); break;
case 4: System.out.print("Four "); break;
case 5: System.out.print("Five "); break;
case 6: System.out.print("Six "); break;
case 7: System.out.print("Seven "); break;
case 8: System.out.print("Eight "); break;
case 9: System.out.print("Nine "); break;
case 0: System.out.print("Zero "); break;
default: System.out.print(""); break;
}
switch (digit2)
{
case 1: System.out.print("One ");break;
case 2: System.out.print("Two "); break;
case 3: System.out.print("Three "); break;
case 4: System.out.print("Four "); break;
case 5: System.out.print("Five "); break;
case 6: System.out.print("Six "); break;
case 7: System.out.print("Seven "); break;
case 8: System.out.print("Eight "); break;
case 9: System.out.print("Nine "); break;
case 0: System.out.print("Zero "); break;
default: System.out.print(""); break;
}
switch (digit3)
{
case 1: System.out.print("One ");break;
case 2: System.out.print("Two "); break;
case 3: System.out.print("Three "); break;
case 4: System.out.print("Four "); break;
case 5: System.out.print("Five "); break;
case 6: System.out.print("Six "); break;
case 7: System.out.print("Seven "); break;
case 8: System.out.print("Eight "); break;
case 9: System.out.print("Nine "); break;
case 0: System.out.print("Zero "); break;
default: System.out.print(""); break;
}
switch (digit4)
{
case 1: System.out.print("One ");break;
case 2: System.out.print("Two "); break;
case 3: System.out.print("Three "); break;
case 4: System.out.print("Four "); break;
case 5: System.out.print("Five "); break;
case 6: System.out.print("Six "); break;
case 7: System.out.print("Seven "); break;
case 8: System.out.print("Eight "); break;
case 9: System.out.print("Nine "); break;
case 0: System.out.print("Zero "); break;
default: System.out.print(""); break;
}
}
}
First, write a method to convert a single digit to a word. Something like,
private static String digitToWord(char ch) {
switch(ch) {
case '0': return "Zero";
case '1': return "One";
case '2': return "Two";
case '3': return "Three";
case '4': return "Four";
case '5': return "Five";
case '6': return "Six";
case '7': return "Seven";
case '8': return "Eight";
case '9': return "Nine";
}
return "Unknown (" + ch + ")";
}
Then you can get the String value of your int. And get the four characters from that String. Something like,
int number = kb.nextInt();
String str = String.format("%04d", number);
StringBuilder sb = new StringBuilder();
sb.append(digitToWord(str.charAt(0)).append(' ');
sb.append(digitToWord(str.charAt(1)).append(' ');
sb.append(digitToWord(str.charAt(2)).append(' ');
sb.append(digitToWord(str.charAt(3));
System.out.println(sb.toString());
Or,
String str = String.format("%04d", kb.nextInt());
System.out.printf("%s %s %s %s%n", digitToWord(str.charAt(0)),
digitToWord(str.charAt(1)), digitToWord(str.charAt(2)),
digitToWord(str.charAt(3)));
this might help
public class NumbersInWords {
public static void main(String[] args) {
String number = "153";
int numLength = number.length();
System.out.println(numLength);
String numberToWord = "";
for (int j = 0; j < numLength; j++) {
switch (number.charAt(j)) {
case '1': {
numberToWord = numberToWord + "one";
break;
}
case '2': {
numberToWord = numberToWord + "two";
break;
}
case '3': {
numberToWord = numberToWord + "three";
break;
}
case '4': {
numberToWord = numberToWord + "four";
break;
}
case '5': {
numberToWord = numberToWord + "five";
break;
}
case '6': {
numberToWord = numberToWord + "six";
break;
}
case '7': {
numberToWord = numberToWord + "seven";
break;
}
case '8': {
numberToWord = numberToWord + "eight";
break;
}
case '9': {
numberToWord = numberToWord + "nine";
break;
}
default: {
numberToWord = numberToWord + "zero";
}
}
}
System.out.println(numberToWord);
}
}
Yeah, you can simply do that operation in a for loop, executed 4 times. The division and mod is consistent at 10. Something like
For i = 0; i < 4; i++
Number/10%10
Condition to check number
Save number in array or print
Copy pasting code and names with numbers should be a red flag to use a loop (or something more is worng).
private static final String[] DIGIT_NAMES = new String[] {"Zero ", "One ", "Two ",
"Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine "};
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number = 0;
do {
// ask for a 4 digit integer
System.out.println("Enter a 4 digit number: ");
try {
number = input.nextInt();
} catch (InputMismatchException ignore) {
System.out.println("Recieved non integer input");
input.next(); // clear bad input
}
} while (number < 1000 || number > 9999);
String result = "";
while (number != 0) {
result = DIGIT_NAMES[number % 10] + result;
number = number / 10;
}
System.out.println(result);
input.close();
}
Related
In my approach below I have a text file of hex values that are passed into a string arraylist, I have a working method that converts a character array into binary titled 'hexToBin'.
I am currently stuck and my question is how would I pass each hex value in the arraylist as a character string so I can use my conversion method to convert hexadecimal values into binary.
I am not allowed to use java's automatic conversion methods or parse commands
hexadecimal text file ~
33CDAEFFAD
032DAE01AD
196CDAEFC0
21A00D0000
100CDAEFFA
F3ABCDEFAB
29A0EDF301
3ABCDEFABC
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Main
{
static void hexToBin(char hexdec[])
{
int i = 0;
while (hexdec[i] != '\u0000')
{
switch (hexdec[i])
{
case '0':
System.out.print("0000");
break;
case '1':
System.out.print("0001");
break;
case '2':
System.out.print("0010");
break;
case '3':
System.out.print("0011");
break;
case '4':
System.out.print("0100");
break;
case '5':
System.out.print("0101");
break;
case '6':
System.out.print("0110");
break;
case '7':
System.out.print("0111");
break;
case '8':
System.out.print("1000");
break;
case '9':
System.out.print("1001");
break;
case 'A':
System.out.print("1010");
break;
case 'B':
System.out.print("1011");
break;
case 'C':
System.out.print("1100");
break;
case 'D':
System.out.print("1101");
break;
case 'E':
System.out.print("1110");
break;
case 'F':
System.out.print("1111");
break;
default:
System.out.print("\nInvalid hexadecimal digit " + hexdec[i]);
}
i++;
}
}
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(new File("RAMerrors8x4c"));
ArrayList<String> values = new ArrayList<String>();
while(sc.hasNext())
{
values.add(sc.nextLine());
}
for(int i = 0; i < values.size(); i++)
{
try {
hexToBin(values.get(i).toCharArray());
}
catch (ArrayIndexOutOfBoundsException e){
System.out.print("");
}
}
}
}
Im trying to replace each letter with a digit using the international standard letter/number mapping. I got my output to run correctly however, how do get the dashes in the phone number to appear automatically in the output? For example, if I enter 1800Flowers it prints out as 18003569377. How do I get it to print out as 1-800-3569377 without using regular expressions?
import java.util.Scanner;
public class PhoneKeypad {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//while loop keeps the program running until the user enters quit
while (true) {
System.out.println("\nEnter a phone number or quit to exit:");
String phoneNumber = input.next();
if (phoneNumber.equalsIgnoreCase("quit")) {
System.out.print("\nProgrammed by me");
return;
}
//checks if the phone number entered is at least 8 digits
if (phoneNumber.length() < 8) {
System.out.println("Invalid Phone Number");
} else {
System.out.println(getNumber(phoneNumber));
}
}
}
//method converts all letters in the phone number to digits
public static String getNumber(String phoneNumber) {
int keypadNum = 0;
for (int i = 0; i < phoneNumber.length(); i++) {
char letter = phoneNumber.charAt(i);
if (Character.isAlphabetic(letter)) {
letter = Character.toUpperCase(letter);
switch (letter) {
case 'A':
case 'B':
case 'C':
keypadNum = 2;
break;
case 'D':
case 'E':
case 'F':
keypadNum = 3;
break;
case 'G':
case 'H':
case 'I':
keypadNum = 4;
break;
case 'J':
case 'K':
case 'L':
keypadNum = 5;
break;
case 'M':
case 'N':
case 'O':
keypadNum = 6;
break;
case 'P':
case 'Q':
case 'R':
case 'S':
keypadNum = 7;
break;
case 'T':
case 'U':
case 'V':
keypadNum = 8;
break;
case 'W':
case 'X':
case 'Y':
case 'Z':
keypadNum = 9;
break;
default:
System.out.println("Invalid phone number");
}
phoneNumber = phoneNumber.substring(0, i) + keypadNum + phoneNumber.substring(i + 1);
}
}
return phoneNumber;
}
}
Expected Output:
You could use a regular expression with String.replaceAll. Remove the leading one, group the first three digits, the second three digits and the final group of digits. Something like
public static String formatNumber(String phoneNumber) {
if (phoneNumber.startsWith("1")) {
phoneNumber = phoneNumber.substring(1);
}
return phoneNumber.replaceAll("(\\d{3})(\\d{3})(\\d+)", "1-$1-$2-$3");
}
or
public static String formatNumber(String phoneNumber) {
return phoneNumber.replaceAll("1(\\d{3})(\\d{3})(\\d+)", "1-$1-$2-$3");
}
And then call it like
System.out.println(formatNumber(getNumber(phoneNumber)));
I ran it with 1800flowers and got (as expected)
1-800-356-9377
or without regular expressions like
public static String formatNumber(String phoneNumber) {
if (phoneNumber.startsWith("1")) {
phoneNumber = phoneNumber.substring(1);
}
return "1-".concat(phoneNumber.substring(0, 3)) //
.concat("-").concat(phoneNumber.substring(3, 6)) //
.concat("-").concat(phoneNumber.substring(6));
}
Before calling formatNumber, you can remove the dashes to normalize it with something like
public static String removeDashes(String phoneNumber) {
StringBuilder sb = new StringBuilder();
for (char ch : phoneNumber.toCharArray()) {
if (ch != '-') {
sb.append(ch);
}
}
return sb.toString();
}
Then
System.out.println(formatNumber(removeDashes(getNumber(phoneNumber))));
I have this program which can make some singular nouns plural (I know I'm missing a lot, but that's aside the point). When I enter in a word such as "man-of-war" it returns as "mans-of-war" instead of "men-of-war". How do I fix this? My code can already make man to men, just not in the case I mentioned. Also for this program every compound word will have the dash, it is simply for practice.
public class LanguageUtils {
static boolean checkException(String noun){
String[] exceptions = {"fish", "fox", "deer", "moose", "sheep", "cattle","pants","scissors"};
for(int i=0;i<exceptions.length;i++) {
if(exceptions[i].equals(noun))
return true;
}
return false;
}
static boolean EnglishConsonant(char ch) {
switch (Character.toLowerCase(ch)) {
case 'a': case 'e': case 'i': case 'o': case 'u':
return false;
default:
return true;
}
}
static String makePlural (String noun){
String pluralWord = "";
int length = noun.length();
String strippedWord = noun.substring(0, noun.length()-1);
char lastLetter = noun.charAt(noun.length()-1);
if(noun.contains("-")){
String nounsaver = noun.substring(noun.indexOf('-'), noun.length());
pluralWord = noun.substring(0,noun.indexOf('-')) + "s" + nounsaver;
}
else{
switch (lastLetter){
case 's':
case 'x':
case 'z':
if(noun.equals("ox")){
pluralWord = noun + "en";
break;
}
else{
pluralWord = noun + "es";
break;
}
case 'o':
if(EnglishConsonant(noun.charAt(noun.length()-2))){
pluralWord = strippedWord + "oes";
break;
}
case 'e':
char f = noun.charAt(noun.length()-2);
String prec = noun.substring(0, noun.length()-2);
if(f == 'f'){
pluralWord = prec + "ves";
break;
}
if(noun.equals("goose")){
pluralWord = "geese";
break;
}
else{
pluralWord = noun + "s";
break;
}
case 'h':
if ((noun.charAt(noun.length()-2)== 'c') || (noun.charAt(noun.length()-2)== 's')) {
pluralWord = noun + "es";
break;
}
case 'f':
if (EnglishConsonant(noun.charAt(noun.length()-2))) {
pluralWord = strippedWord + "ves";
break;
}
case 'y':
if (EnglishConsonant(noun.charAt(noun.length()-2))) {
pluralWord = strippedWord + "ies";
break;
}
default:
if(noun.equals("foot")){
pluralWord = "feet";
break;
}
if(noun.endsWith("man")){
pluralWord = noun.substring(0, noun.length()-3)+"men";
break;
}
else{
pluralWord = noun + "s";
break;
}
}
}
if (length == 1){
pluralWord = noun + "'s";
}
if(checkException(noun)){
pluralWord = noun;
}
return pluralWord;
}
}
When dealing with a compound word, if you need to pluralize a part, call a function designed to do just that: makePlural.
If you have - then break the words and call the makePlural for those words again.
You can use String#replace:
if (noun.contains("man")) {
pluralWord = noun.replace("man", "men");
break;
}
My instructor requires us to take the package from our code and make it a default package. The only problem is he taught us how to do that through Windows and I have a MacBook so his way isn't working. I can't figure out how to do it. I've attached the code to the bottom in case that will help.
package romannumeralcalculator;
import java.util.*;
public class RomanNumeralCalculator
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int integer;
do {
System.out.print("Please enter an interger from 1 to 5999. Enter a negative number to exit. \n ->");
integer = input.nextInt();
} while (integer >= 6000);
while (integer == 0) {
System.out.println("");
break;
}
String results = "";
int ones = integer % 10;
int tens = (integer / 10) % 10;
int hundreds = (integer / 100) % 10;
int thousands = (integer / 1000) % 1000;
switch (thousands) {
case 1:
results += "M";
break;
case 2:
results += "MM";
break;
case 3:
results += "MMM";
break;
case 4:
results += "MMMM";
break;
case 5:
results += "MMMMM";
break;
default:
System.out.println("");
}
switch (hundreds) {
case 1:
results += "C";
break;
case 2:
results += "CC";
break;
case 3:
results += "CCC";
break;
case 4:
results += "CD";
break;
case 5:
results += "D";
break;
case 6:
results += "DC";
break;
case 7:
results += "DCC";
break;
case 8:
results += "DCCC";
break;
case 9:
results += "CM";
break;
default:
System.out.println("");
}
switch (tens) {
case 1:
results += "X";
break;
case 2:
results += "XX";
break;
case 3:
results += "XXX";
break;
case 4:
results += "XL";
break;
case 5:
results += "L";
break;
case 6:
results += "LX";
break;
case 7:
results += "LXX";
break;
case 8:
results += "LXXX";
break;
case 9:
results += "XC";
break;
default:
System.out.println("");
}
switch (ones) {
case 1:
results += "I";
break;
case 2:
results += "II";
break;
case 3:
results += "III";
break;
case 4:
results += "IV";
break;
case 5:
results += "V";
break;
case 6:
results += "VI";
break;
case 7:
results += "VII";
break;
case 8:
results += "VIII";
break;
case 9:
results += "IX";
break;
default:
System.out.println("");
}
System.out.println(results);
}
}
In the projects tab of Netbeans in the top-left:
Expand the tree for your Project.
Expand the Source Packages folder.
Expand the package with your java file.
Drag the java file from under the package to the Source Packages folder.
A dialog box will pop up with the title Move Class. On that dialog click the Refactor button.
This should be the same procedure in Windows. I am not sure why your professor told you something different.
I am trying to change this from an input box into a Scanner class, but i am having trouble doing so.
Its a program that takes words and makes them into a phone number here is the code that does so. Any help would be greatly appreciated and if there is something that i can do in return i would gladly do so.
// declare imports
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.util.*;
public class Telephone {
public static void main(String[] args) {
// ask for the phone number (in letters)
char letter;
String inputMessage = "Please enter the number in Letters " + "or enter '#' to stop the program ";
String inputString = JOptionPane.showInputDialog(inputMessage);
String outputString = "";
String outputMessage = "";
int digit = 0;
int x = 0;
for (int i = 0; i < inputString.length(); i++)
System.out.print(inputString.charAt(x)); {
while (inputString.charAt(x) != '#') {
letter = Character.toUpperCase(inputString.charAt(x));
x++;
// make sure its not a number
if (letter >= 'a' && letter <= 'z') if (letter >= 'A' && letter <= 'Z') {
digit++;
switch (letter) {
case 'A':
case 'B':
case 'C':
outputString += "2";
break;
case 'D':
case 'E':
case 'F':
outputString += "3";
break;
case 'G':
case 'H':
case 'I':
outputString += "4";
break;
case 'J':
case 'K':
case 'L':
outputString += "5";
break;
case 'M':
case 'N':
case 'O':
outputString += "6";
break;
case 'P':
case 'Q':
case 'R':
case 'S':
outputString += "7";
break;
case 'T':
case 'U':
case 'V':
outputString += "8";
break;
case 'W':
case 'X':
case 'Y':
case 'Z':
outputString += "9";
}
if (digit == 7) {
break;
}
if (digit == 3) {
outputString += "-";
}
}
inputMessage = "Enter another set of telephone letters";
}
JOptionPane.showMessageDialog(null, outputString, "Telephone Program", JOptionPane.PLAIN_MESSAGE);
}
Modify the line where you show the JOptionPane as follows,
//String inputString = JOptionPane.showInputDialog(inputMessage);
System.out.println(inputMessage);
Scanner sc = new Scanner(System.in);
String inputString = sc.nextLine();
so you could do the following,
package test;
import java.util.Scanner;
public class Telephone {
public static void main(String[] args) {
// ask for the phone number (in letters)
char letter;
String inputMessage = "Please enter the number in Letters " + "or enter '#' to stop the program ";
// String inputString = JOptionPane.showInputDialog(inputMessage);
System.out.println(inputMessage);
Scanner sc = new Scanner(System.in);
String inputString = sc.nextLine();
String outputString = "";
String outputMessage = "";
int digit = 0;
int x = 0;
for (int i = 0; i < inputString.length(); i++) {
System.out.print(inputString.charAt(x));
}
while (inputString != null && inputString.trim().length() > 0 && inputString.charAt(x) != '#') {
letter = Character.toUpperCase(inputString.charAt(x));
x++;
// make sure its not a number
// if (letter >= 'a' && letter <= 'z') {
if (x >= inputString.length()) {
x = 0;
System.out.println("\n" + outputString);
// JOptionPane.showMessageDialog(null, outputString, "Telephone Program", JOptionPane.PLAIN_MESSAGE);
// inputString = JOptionPane.showInputDialog(inputMessage);
System.out.println(inputMessage);
inputString = sc.nextLine();
} else if (letter >= 'A' && letter <= 'Z') {
digit++;
switch (letter) {
case 'A':
case 'B':
case 'C':
outputString += "2";
break;
case 'D':
case 'E':
case 'F':
outputString += "3";
break;
case 'G':
case 'H':
case 'I':
outputString += "4";
break;
case 'J':
case 'K':
case 'L':
outputString += "5";
break;
case 'M':
case 'N':
case 'O':
outputString += "6";
break;
case 'P':
case 'Q':
case 'R':
case 'S':
outputString += "7";
break;
case 'T':
case 'U':
case 'V':
outputString += "8";
break;
case 'W':
case 'X':
case 'Y':
case 'Z':
outputString += "9";
}
if (digit == 7) {
break;
}
if (digit == 3) {
outputString += "-";
}
}
// }
inputMessage = "Enter another set of telephone letters";
}
System.out.println("\n" + outputString);
// JOptionPane.showMessageDialog(null, outputString, "Telephone Program", JOptionPane.PLAIN_MESSAGE);
}
}