I am currently working on a two way morse code translator program. I am not quite finished but when doing a test of the program I received multiple compilation errors. I have no idea what is wrong but am sure it is something simple. Any help would be appreciated.
Here is my code so far:
public class MorseCodeProject
{
public static void main(String[] args)
{
System.out.println("Please enter the conversion to be preformed.");
System.out.println("Type 1 to convert English to Morse code.");
System.out.println("Type 2 to convert Morse code to English.");
int type = Input.getInt();
System.out.println("Please enter the message to be converted.");
String message = Input.getString();
if(type == 1)
EtoM(message);
else
MtoE(message);
}
public static void EtoM(String message)
{
String translation[] = new String[message.length()];
String y;
for(int x = 0; x < message.length(); x++)
{
y = message.substring(x, x + 1);
switch(y)
{
case "a":
translation[x] = ".-";
break;
case "b":
translation[x] = "-...";
break;
case "c":
translation[x] = "-.-.";
break;
case "d":
translation[x] = "-..";
break;
case "e":
translation[x] = ".";
break;
case "f":
translation[x] = "..-.";
break;
case "g":
translation[x] = "--.";
break;
case "h":
translation[x] = "....";
break;
case "i":
translation[x] = "..";
break;
case "j":
translation[x] = ".---";
break;
case "k":
translation[x] = "-.-";
break;
case "l":
translation[x] = ".-..";
break;
case "m":
translation[x] = "--";
break;
case "n":
translation[x] = "-.";
break;
case "o":
translation[x] = "---";
break;
case "p":
translation[x] = ".--.";
break;
case "q":
translation[x] = "--.-";
break;
case "r":
translation[x] = ".-.";
break;
case "s":
translation[x] = "...";
break;
case "t":
translation[x] = "-";
break;
case "u":
translation[x] = "..-";
break;
case "v":
translation[x] = "...-";
break;
case "w":
translation[x] = ".--";
break;
case "x":
translation[x] = "-..-";
break;
case "y":
translation[x] = "-.--";
break;
case "z":
translation[x] = "--..";
break;
case "1":
translation[x] = ".----";
break;
case "2":
translation[x] = "..---";
break;
case "3":
translation[x] = "...--";
break;
case "4":
translation[x] = "....-";
break;
case "5":
translation[x] = ".....";
break;
case "6":
translation[x] = "-....";
break;
case "7":
translation[x] = "--...";
break;
case "8":
translation[x] = "---..";
break;
case "9":
translation[x] = "----.";
break;
case "0":
translation[x] = "-----";
break;
case " ":
translation[x] = "|";
default:
break;
}
for(int z = 0; z < message.length(); z++)
{
System.out.println(translation[z]);
}
}
}
public static void MtoE(String message)
{
int segments = 1;
char segment1;
int x = 0;
for(x = 0; x < message.length(); x++);
{
if(message.charAt(x) = "|")
{
segments += 1;
}
}
String segmentedMessage[] = new String[segments];
int j = 0;
int k;
for(int y = 0; y < segments; y++)
{
for(k = j; k < message.length(); k++)
{
if(message.charAt(k) == "|")
{
segementedMessage[y] = message.substirng(j, k);
j = k;
}
}
}
String segment;
String translation[] = new String[segments]
for(int c = 0; c < segments; c++)
{
segment = segmentedMessage[c];
switch(segment)
{
case ".-":
translation[c] = "a";
break;
case "-...":
translation[c] = "b";
break;
case "-.-.":
translation[c] = "c";
break;
case "-..":
translation[c] = "d";
break;
case ".":
translation[c] = "e";
break;
case "..-.":
translation[c] = "f";
break;
case "--.":
translation[c] = "g";
break;
case "....":
translation[c] = "h";
break;
case "..":
translation[c] = "i";
break;
case ".---":
translation[c] = "j";
break;
case "-.-":
translation[c] = "k";
break;
case ".-..":
translation[c] = "l";
break;
case "--":
translation[c] = "m";
break;
case "-.":
translation[c] = "n";
break;
case "---":
translation[c] = "o";
break;
case ".--.":
translation[c] = "p";
break;
case "--.-":
translation[c] = "q";
break;
case ".-.":
translation[c] = "r";
break;
case "...":
translation[c] = "s";
break;
case "-":
translation[c] = "t";
break;
case "..-":
translation[c] = "u";
break;
case "...-":
translation[c] = "v";
break;
case ".--":
translation[c] = "w";
break;
case "-..-":
translation[c] = "x";
break;
case "y-.--:
translation[c] = "y";
break;
case "--..":
translation[c] = "z";
break;
case ".----":
translation[c] = ".----";
break;
case "..--":
translation[c] = "..---";
break;
case "...--":
translation[c] = "...--";
break;
case "....-":
translation[c] = "....-";
break;
case ".....":
translation[c] = ".....";
break;
case "-....":
translation[c] = "-....";
break;
case "--...":
translation[c] = "--...";
break;
case "---..":
translation[c] = "---..";
break;
case "----.":
translation[c] = "----.";
break;
case "-----":
translation[c] = "-----";
break;
case "|":
translation[c] = " ";
default:
break;
}
}
}
}
Here are the problems I found:
1.
if(message.charAt(x) = "|")
should likely be
if(message.charAt(x) == '|')
The same goes for if(message.charAt(k) = "|"). Recall that = is assignment whereas == is comparison, and that charAt() returns a char as opposed to a String, so we compare with '|' and not "|" (you should use .equals() for strings anyway).
2.
segementedMessage[y] = message.substirng(j, k);
substring is mispselled here, and so is segmentedMessage (which you declare with the correct spelling earlier).
3.
String translation[] = new String[segments]
You're missing a ; at the end of this line.
4.
case "y-.--:
You're missing a closing " at the end of that string (should be case "y-.--":).
Related
The homework for my Java class instructs us to take an integer input from the user (up to 3999) and convert it into a Roman Numeral. The trouble I am having with the code is that when I input the integer while testing, it sets the integer to 0 and the Roman Numeral prints out as null. This could be a result of declaring the variables inside an object but im unsure at this point.
public class RomanNumerals
{
// instance variables
int input;
String romanNum;
/**
* Object that records the input from a user.
*/
public RomanNumerals()
{
int input=0;
String romanNum="";
//System.out.println("Input a number to get a Roman Numeral");
//int input = integer.nextInt();
}
public int Scanner()
{
Scanner integer = new Scanner(System.in);
System.out.println("Input a number to get a Roman Numeral: ");
int input = integer.nextInt();
return input;
}
/**
* Object that takes the input from the user and determines what roman numerals are appropriate.
*/
public String Int2Roman()
{
if (input < 1 || input > 3999)
{
System.out.println("Please input a number between 1 and 3999.");
}
while (input >= 1000)
{
romanNum = romanNum + "M";
input = input - 1000;
}
while (input >= 900)
{
romanNum = romanNum + "CM";
input = input - 900;
}
while (input >= 500)
{
romanNum = romanNum + "S";
input = input - 500;
}
while (input >= 400)
{
romanNum = romanNum + "CS";
input = input - 1000;
}
while (input >= 100)
{
romanNum = romanNum + "C";
input = input - 100;
}
while (input >= 90)
{
romanNum = romanNum + "XC";
input = input - 1000;
}
while (input >= 50)
{
romanNum = romanNum + "L";
input = input - 1000;
}
while (input >= 40)
{
romanNum = romanNum + "XL";
input = input - 40;
}
while (input >= 10)
{
romanNum = romanNum + "X";
input = input - 10;
}
while (input >= 9)
{
romanNum = romanNum + "IX";
input = input - 9;
}
while (input >= 5)
{
romanNum = romanNum + "V";
input = input - 5;
}
while (input >= 4)
{
romanNum = romanNum + "IV";
input = input - 4;
}
while (input >= 1)
{
romanNum = romanNum + "I";
input = input - 5;
}
System.out.println("The Roman Numeral of " + input + " is " + romanNum);
return romanNum;
}
public static void main(String[] args)
{
RomanNumerals a = new RomanNumerals();
a.Scanner();
a.Int2Roman();
}
}
Your Scanner method does not store the keyboard input in the field (instance variable) input but in a local variable input.
Replace
int input = integer.nextInt(); //this declares a new local variable
with
input = integer.nextInt(); //uses the existing field
try this to see if works , works for me, simple , basic , pretty straight forward
public static void main(String[] args) {
//INPUNT INTEGER VALUE
// OUTPUT STRING VALUE (SYSTEM CONSOLE OUTPUT
//**********************************************************************************//
int _inValue = 117; //int parameter value
//**********************************************************************************//
//check if the number is between 1 and 3999
if (_inValue < 1){
System.out.println("integer can't be less than 1");
return;
}
if (_inValue > 3999){
System.out.println("integer can't be more than 3999");
return;
}
//convert the value in array to work by separate numbers
char[] arg = String.valueOf(_inValue).toCharArray();
//count the number of characters to use a case condition or length of the integer in value
int _count = Integer.toString(_inValue).length();
// output variable
String _output = "";
//case condition base in the length of the integer value
switch (_count){
case 1: // case base in one figure (1)
switch (_inValue){
case 1:
_output = "I";
break;
case 2:
_output = "II";
break;
case 3:
_output = "III";
break;
case 4:
_output = "IV";
break;
case 5:
_output = "V";
break;
case 6:
_output = "VI";
break;
case 7:
_output = "VII";
break;
case 8:
_output = "VIII";
break;
case 9:
_output = "IX";
break;
}
break;
case 2: //case base in two figures (10)
switch (Character.getNumericValue(arg[0])){//base in the first character of the integer value lets use another case condition
case 1:
_output = "X";
break;
case 2:
_output = "XX";
break;
case 3:
_output = "XXX";
break;
case 4:
_output = "XL";
break;
case 5:
_output = "L";
break;
case 6:
_output = "LX";
break;
case 7:
_output = "LXX";
break;
case 8:
_output = "LXXX";
break;
case 9:
_output = "XC";
break;
}
_output += _getValue10(Character.getNumericValue(arg[1])); //lets call this function to get the other two figures or number to complete the integer amount and build the roman value in string
break;
case 3: //case base in three figures (100)
switch (Character.getNumericValue(arg[0])){ //base in the first character of the integer value lets use another case condition
case 1:
_output = "C";
break;
case 2:
_output = "CC";
break;
case 3:
_output = "CCC";
break;
case 4:
_output = "CD";
break;
case 5:
_output = "D";
break;
case 6:
_output = "DC";
break;
case 7:
_output = "DCC";
break;
case 8:
_output = "DCCC";
break;
case 9:
_output = "CM";
break;
}
_output += _getValue100(Character.getNumericValue(arg[1]),Character.getNumericValue(arg[2])); //lets call this function to get the other two figures or number to complete the integer amount and build the roman value in string
break;
case 4: // case base in 4 figures (1000)
if(_inValue != 1000){ // validate the value if its different of a 1000
// use a cycle to concat the string base of the number of the integer in value
for (int i = 0; i < Character.getNumericValue(arg[0]);i++ ){
_output += "M";
}
}else{
// if its a 1000 use this one and that's it
_output += "M";
}
_output += _getValue1000(Character.getNumericValue(arg[1]),Character.getNumericValue(arg[2]),Character.getNumericValue(arg[3])); //lets call this function to get the other three figures or number to complete the integer amount and build the roman value in string
break;
}
System.out.println("the integer number is: " + _inValue);
System.out.println("the roman number is: " + _output);
}
///method who return the other three values
private static String _getValue1000(int valueOne, int valueTwo, int valueThree){
String _output = "";
if(valueOne != 0){
switch (valueOne){
case 1:
_output += "C";
break;
case 2:
_output += "CC";
break;
case 3:
_output += "CCC";
break;
case 4:
_output += "CD";
break;
case 5:
_output += "D";
break;
case 6:
_output += "DC";
break;
case 7:
_output += "DCC";
break;
case 8:
_output += "DCCC";
break;
case 9:
_output += "CM";
break;
}
}
if(valueTwo != 0){
switch (valueTwo){
case 1:
_output += "X";
break;
case 2:
_output += "XX";
break;
case 3:
_output += "XXX";
break;
case 4:
_output += "XL";
break;
case 5:
_output += "L";
break;
case 6:
_output += "LX";
break;
case 7:
_output += "LXX";
break;
case 8:
_output += "LXXX";
break;
case 9:
_output += "XC";
break;
}
}
if(valueThree != 0){
switch (valueThree){
case 1:
_output += "I";
break;
case 2:
_output += "II";
break;
case 3:
_output += "III";
break;
case 4:
_output += "IV";
break;
case 5:
_output += "V";
break;
case 6:
_output += "VI";
break;
case 7:
_output += "VII";
break;
case 8:
_output += "VIII";
break;
case 9:
_output += "IX";
break;
}
}
return _output;
}
/// method who return the other two values
private static String _getValue100(int valueOne, int valueTwo){
String _output = "";
if(valueOne != 0){
switch (valueOne){
case 1:
_output += "X";
break;
case 2:
_output += "XX";
break;
case 3:
_output += "XXX";
break;
case 4:
_output += "XL";
break;
case 5:
_output += "L";
break;
case 6:
_output += "LX";
break;
case 7:
_output += "LXX";
break;
case 8:
_output += "LXXX";
break;
case 9:
_output += "XC";
break;
}
}
if(valueTwo != 0){
switch (valueTwo){
case 1:
_output += "I";
break;
case 2:
_output += "II";
break;
case 3:
_output += "III";
break;
case 4:
_output += "IV";
break;
case 5:
_output += "V";
break;
case 6:
_output += "VI";
break;
case 7:
_output += "VII";
break;
case 8:
_output += "VIII";
break;
case 9:
_output += "IX";
break;
}
}
return _output;
}
/// method who return one other value
private static String _getValue10(int valueOne){
String _output = "";
if(valueOne != 0){
switch (valueOne){
case 1:
_output += "I";
break;
case 2:
_output += "II";
break;
case 3:
_output += "III";
break;
case 4:
_output += "IV";
break;
case 5:
_output += "V";
break;
case 6:
_output += "VI";
break;
case 7:
_output += "VII";
break;
case 8:
_output += "VIII";
break;
case 9:
_output += "IX";
break;
}
}
return _output;
}
I am trying to create a scrabble-like program that calculates the points of letters contained in a word. These word are contained in a .txt file. I can get it to read from the file, but unsure how to get it to calculate the value of each word. I have attached what I have done so far, and am wondering if a switch case is the best way to go, and if so, how do I assign a value to a letter with a switch case. Any help is appreciated.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pointsproblem;
/**
*
*/
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class PointsProblem {
/**
* #param args the command line arguments
* #throws java.io.FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
//create new object//
PointsProblem task1 = new PointsProblem();
File file = new File("dictionary.txt");
// read the file//
Scanner input = new Scanner(file);
//check if file can be found//
if (!file.isFile()) {
System.err.println("Cannot open file: " + input);
System.exit(0);
}
else {
System.out.println("Successfully opened file: " + input + ".");
}
//read all the lines in the file//
{
while (input.hasNext()) {
String word = input.nextLine();
System.out.println(word);
System.out.println("'" + input + "' is worth " + point + " points");
int point = "";
switch(point) {
case 'a': = "1":
case 'e': = "1";
case 'i': = "1";
case 'l': = "1";
case 'n': = "1";
case 'o': = "1";
case 'r': = "1";
case 's': = "1";
case 't': = "1";
case 'u': = "1";
case 'g': = "2";
case 'g': = "2";
case 'b': = "3";
case 'm': = "3";
case 'c': = "3";
case 'p': = "3";
case 'f': = "4";
case 'h': = "4";
case 'v': = "4";
case 'w': = "4";
case 'y': = "4";
case 'k': = "5";
case 'j': = "8";
case 'x': = "8";
case 'q': = "10";
case 'z': = "10";
return score = point + "";
}//end switch
}//end point calculation loop
public int getScore() {
return score;
}
//public boolean containsLetter(Character letter) {
//return points.contains(letter);//
}
I have tried assigning an int of X to the value as well. I would like it to read the word contained in the file and give a total score.
Looks like a Map<Character, Integer> would fit:
public class PointsProblem {
final Map<Character, Integer> pointsMap = Map.of(
'a', 1,
'e', 1,
//.......
'z', 10
);
Then, in your function, simply use the map to find the corresponding point for each character:
int wordPoints = 0;
for(char c : word.toCharArray())
wordPoints += pointsMap.get(c);
Use a map to store the values:
Map<Character, Integer> charValues = new HashMap();
charValues.put('a', 2);
charValues.put('b', 1);
You can use the chars() and collect as sum
int total = word.chars()
.mapToObj(c -> charValues.get((char)c))
.mapToInt(i -> (int)i)
.sum();
But according to your use case you can count the chars first and then multiply
Map<Character, Integer> counter = new HashMap<>();
while (input.hasNext()) {
String word = input.next();
word.chars().forEach(c -> counter.compute(c, (k, v) -> v == null ? 1 : v + 1));
}
counter.entrySet()
.stream()
.mapToInt(e -> charValues.get(e.getKey())*e.getValue())
.sum();
if you are using switch your code will look like:
int total = 0;
switch (c){
case 'a' : total += 1; break;
case 'b' : total += 2; break;
}
I'm not sure that the code you've shown us will compile. There are a few things you need to change;
1) You're setting a String to an int. You'll want to change that to
int point = 0
2) You aren't setting anything in the switch statement
Change case 'a': = "1": to case 'a': point = 1;
3) You will never set a unique value in the switch statement because you aren't using 'break'
Checkout this page for a good tutorial: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Basically without any break statements, your code will go through the of the statements and point will just be assigned to your last case
You want to have something along the lines of
switch(char) {
case 'a': point = 1;
break;
case 'e': point = 1;
break;
// etc.
default: point = 1; // maybe throw an error or add some logging for the default case
break;
}
return point;
I am presuming that you actually have this switch statement in it's own method and not in main as you've shown us above, otherwise the return statement won't help you.
You can also shorten this so that each case simply returns a value (again, if this is in it's own method), i.e.
switch(char) {
case 'a': return 1;
case 'b': return 1;
// etc.
}
edit:
The best way to get the point value of the whole word via a switch statement is:
char[] chars = word.toCharArray();
int point=0;
for (char c: chars) {
switch(c) {
case 'a':
point += 1;
break;
// etc.
}
}
System.out.println("Total point value of word '" + word + "' was " + point);
Instead of assigning individually for each 'case' statement, you can also use the fall through feature of the switch block.
int calcScore(String str)
{
int score = 0;
for(int i=0; i<str.length(); i++)
{
switch(str.charAt(i)) {
case 'a':
case 'e':
case 'i':
case 'l':
case 'n':
case 'o':
case 'r':
case 's':
case 't':
case 'u': score += 1; break;
case 'g': score += 2; break;
case 'b':
case 'm':
case 'c':
case 'p': score += 3; break;
case 'f':
case 'h':
case 'v':
case 'w':
case 'y': score += 4; break;
case 'k': score += 5; break;
case 'j':
case 'x': score += 8; break;
case 'q':
case 'z': score += 10; break;
}
}
return score;
}
This function can be called for each word.
Thanks everyone, I ended up with the following code which gives the output I am after;
System.out.println("Points problem");
File file = new File("dictionary.txt");
// read the file//
Scanner input = new Scanner(file);
//check if file can be found//
if (!file.isFile()) {
System.err.println("Cannot open file: " + file);
System.exit(0);
} else {
System.out.println("Successfully opened file: " + file + ".");
}
//read all the lines in the file//
while (input.hasNext()) {
String word = input.nextLine();
//System.out.println(word);
int l = word.length();
int point = 0;
for (int x = 0; x < l; x++) {
char c = word.charAt(x);
switch (c) {
case 'a':
case 'e':
case 'i':
case 'l':
case 'n':
case 'o':
case 'r':
case 's':
case 't':
case 'u':
point += 1;
break;
case 'd':
case 'g':
point += 2;
break;
case 'b':
case 'c':
case 'm':
case 'p':
point += 3;
break;
case 'f':
case 'h':
case 'v':
case 'w':
case 'y':
point += 4;
break;
case 'k':
point += 5;
break;
case 'j':
case 'x':
point += 8;
break;
case 'q':
case 'z':
point += 10;
break;
}//end switch*/
}//end point calculation loop
System.out.println(word + "is worth " + point + " points." );
}
This code keeps giving me an error in line 7:
error: array required, but String found
switch(str[i]){
It seems to not be treating the array created as an array... any suggestions?
public class Encryption_plus_some{
public String encrypt(String str){
String answer = "";
str.toCharArray();
for(int i = 0; i < str.length(); i++){
switch(str[i]){
case "a": answer += "a";
break;
case "b": answer += "y";
break;
case "c": answer += "x";
break;
case "d": answer += "w";
break;
case "e": answer += "e";
break;
case "f": answer += "u";
break;
case "g": answer += "t";
break;
case "h": answer += "s";
break;
case "i": answer += "i";
break;
case "j": answer += "q";
break;
case "k": answer += "p";
break;
case "l": answer += "o";
break;
case "m": answer += "n";
break;
case "n": answer += "m";
break;
case "o": answer += "o";
break;
case "p": answer += "k";
break;
case "q": answer += "j";
break;
case "r": answer += "i";
break;
case "s": answer += "h";
break;
case "t": answer += "g";
break;
case "u": answer += "u";
break;
case "v": answer += "e";
break;
case "w": answer += "d";
break;
case "x": answer += "c";
break;
case "y": answer += "i";
break;
case "z": answer += "a";
break;
default: answer += " ";
break;
}
}
return answer;
}
public static void main(String[] args) {
System.out.println(encrypt("some words to encrypt"));
}
}
.toCharArray returns a char array (char[]) from the string, it doesn't turn the String value into a charArray. The String str is still a string.
Try:
char[] charArray = str.toCharArray();
functions can't change the type of the variable.
Save your str.toCharArray in a char array
char arr[]=str.toCharArray
I just saw some of my work today, and i want to enter the user how many alphabet they want and continue converting. Can i have help? It would be fantastic. I tried anything. I'm just new in java programming that's why. Thanks :)
This is my whole programming
import java.util.Scanner;
public class Try2 {
public static void main(String[] args) {
int counter = 0;
int it = 0;
Scanner keyboard = new Scanner(System. in );
System.out.println("Enter words to digits: ");
String alpha = keyboard.nextLine();
alpha = alpha.toLowerCase();
String num = (" ");
while (counter < alpha.length()) {
switch (alpha.charAt(it)) {
case 'A':
case 'a':
case 'B':
case 'b':
case 'c':
case 'C':
num += "2";
counter++;
break;
case 'D':
case 'E':
case 'F':
case 'd':
case 'e':
case 'f':
num += "3";
counter++;
break;
case 'G':
case 'H':
case 'I':
case 'g':
case 'h':
case 'i':
num += "4";
counter++;
break;
case 'J':
case 'K':
case 'L':
case 'j':
case 'k':
case 'l':
num += "5";
counter++;
break;
case 'M':
case 'N':
case 'O':
case 'm':
case 'n':
case 'o':
num += "6";
counter++;
break;
case 'P':
case 'R':
case 'S':
case 'p':
case 'r':
case 's':
num += "7";
counter++;
break;
case 'T':
case 'U':
case 'V':
case 't':
case 'u':
case 'v':
num += "8";
counter++;
break;
case 'W':
case 'w':
case 'X':
case 'x':
case 'Y':
case 'y':
case 'Z':
case 'z':
case ' ':
num += "9";
counter++;
break;
}
if ((counter % 4) == 3) {
num += "-";
}
it++;
}
System.out.println(num);
}
}
You can wrap the read line code with another while loop:
Scanner keyboard = new Scanner(System.in);
while(true) {
System.out.println("Enter words to digits: ");
String alpha = keyboard.nextLine();
alpha = alpha.toLowerCase();
String num = " ";
int counter = 0;
int it = 0;
while (counter < alpha.length()) {
...
}
//new line (optional)
num += "\n";
}
You can check if the user entered a flag to end input:
//You can choose any flag you want
if(alpha.equals("finish")) {
break;
}
About your switch:
You can remove all the upper case letters because you wrote: alpha = alpha.toLowerCase();
You forgot 'q'
If alpha don't match: [a-zA-z ] (contains only letters and spaces) an IndexOutOfBoundsException will be thrown from alpha.charAt(it) because you don't increase counter and the loop don't exit in time.
To prevent the last problem you can remove counter and it and change the while loop to for loop:
for (int i = 0; i < alpha.length(); i++) {
if ((i % 4) == 3) {
num += "-";
}
switch (alpha.charAt(i)) {
...
}
}
I have a double split up into an int array, however the problem I am facing, is that I need it to fill in from the back, like this:
int[] arrayA = new int[5];
int[] arrayB = new int[5];
x = 23456.08;
//code here
//what im left with:
arrayA [0,2,3,4,5,6];
arrayB [0,8];
Heres how im cutting up the double:
public static void main(System args[])
{
Scanner input = new Scanner(System.in);
String answer = "";
int count = 0;
int thatone = 0;
int[] splitD = new int[5]; //main num
int[] splitDec = new int[1]; //decimal
//Enter the Number
System.out.print("Enter a number to convert: ");
double num = input.nextDouble();
// convert number to String
String convert = num + "";
// split the number
String[] split = convert.split("\\.");
String firstPart = split[0];
char[] charArray1 = firstPart.toCharArray();
// recreate the array with size equals firstPart length
splitD = new int[charArray1.length];
for (int i = 0; i < charArray1.length; i++)
{
// convert char to int
splitD[i] = Character.getNumericValue(charArray1[i]);
count++;
}
// the decimal part
if (split.length > 1)
{
String secondPart = split[1];
char[] charArray2 = secondPart.toCharArray();
splitDec = new int[charArray2.length];
for (int i = 0; i < charArray2.length; i++)
{
// convert char to int
splitDec[i] = Character.getNumericValue(charArray2[i]);
}
}
for(int i =0; i<count;i++)
{
if(i ==0) // x00000.00 or 000x00.00
{
if(splitD[0] != "0")
{
switch (splitD[i])
{
case 9: answer+="Nine"; break;
case 8: answer+="Eight"; break;
case 7: answer+="Seven"; break;
case 6: answer+="Six"; break;
case 5: answer+="Five"; break;
case 4: answer+="Four"; break;
case 3: answer+="Three"; break;
case 2: answer+="Two"; break;
case 1: answer+="One"; break;
default: answer+=""; break;
}
answer+= " Hundred ";
}
else
{
answer+= "";
}
}
else if(i ==1)//this goes with i =2 //0x0000
{
if(splitD[i] == 1)
{
switch (splitD[i+1])
{
case 9: answer+="Nineteen"; break;
case 8: answer+="Eighteen"; break;
case 7: answer+="Seventeen"; break;
case 6: answer+="Sixteen"; break;
case 5: answer+="Fifteen"; break;
case 4: answer+="Fourteen"; break;
case 3: answer+="Thirteen"; break;
case 2: answer+="Twelve"; break;
case 1: answer+="ten"; break;
default: answer+=""; break;
}
answer+= " Thousand ";
thatone = 1;
}
else
{
switch (splitD[i])
{
case 9: answer+="Ninety"; break;
case 8: answer+="Eighty"; break;
case 7: answer+="Seventy"; break;
case 6: answer+="Sixty"; break;
case 5: answer+="Fifty"; break;
case 4: answer+="Fourty"; break;
case 3: answer+="Thirty"; break;
case 2: answer+="Twenty"; break;
case 1: answer+=""; break;
default: answer+=""; break;
}
}
}
else if(i == 2) //00x000
{
if(thatone ==0)
{
switch (splitD[i])
{
case 9: answer+=" Nine"; break;
case 8: answer+=" Eight"; break;
case 7: answer+=" Seven"; break;
case 6: answer+=" Six"; break;
case 5: answer+=" Five"; break;
case 4: answer+=" Four"; break;
case 3: answer+=" Three"; break;
case 2: answer+=" Two"; break;
case 1: answer+=" One"; break;
default: answer+=""; break;
}
answer+= " Thousand ";
}
else
{
}
}
else if(i ==3)
{
switch (splitD[i])
{
case 9: answer+="Nine"; break;
case 8: answer+="Eight"; break;
case 7: answer+="Seven"; break;
case 6: answer+="Six"; break;
case 5: answer+="Five"; break;
case 4: answer+="Four"; break;
case 3: answer+="Three"; break;
case 2: answer+="Two"; break;
case 1: answer+="One"; break;
default: answer+=""; break;
}
answer+= " Hundred ";
}
else if(i ==4) //0000x0
{
switch (splitD[i])
{
case 9: answer+="Ninety"; break;
case 8: answer+="Eighty"; break;
case 7: answer+="Seventy"; break;
case 6: answer+="Sixty"; break;
case 5: answer+="Fifty"; break;
case 4: answer+="Fourty"; break;
case 3: answer+="Thirdy"; break;
case 2: answer+="Twenty"; break;
case 1: answer+=""; break;
default: answer+=""; break;
}
answer+= " ";
}
else if(i ==5) //00000x
{
switch (splitD[i])
{
case 9: answer+="Nine"; break;
case 8: answer+="Eight"; break;
case 7: answer+="Seven"; break;
case 6: answer+="Six"; break;
case 5: answer+="Five"; break;
case 4: answer+="Four"; break;
case 3: answer+="Three"; break;
case 2: answer+="Two"; break;
case 1: answer+="One"; break;
default: answer+=""; break;
}
}
}
if(splitDec[0] == 0)
{
answer += " and 00/100 Dollars";
}
else if(splitDec[1] == 0)
{
answer += " and " +splitDec[0] + "0/100 Dollars";
}
else
{
answer += " and " +splitDec[0] +splitDec[1] +" /100 Dollars";
}
System.out.println(answer);
}
}
What should I do to make the array add 0 in the appropriate places?
such as if I typed in 54.00 I would get:
int[] SplitD = {0,0,0,0,5,4};
Thanks!
Instead of re-initializing the array:
// recreate the array with size equals firstPart length
splitD = new int[charArray1.length];
for (int i = 0; i < charArray1.length; i++)
{
// convert char to int
splitD[i] = Character.getNumericValue(charArray1[i]);
count++;
}
Use the existing (with length = 5), iterating from the back:
if(charArray1.length > 5) // heavy hard-code, would prefer something better
throw new IllegalArgumentException("Maximum 5 digits, on both decimal sides.");
// watch out of ArrayIndexOutOfBoundsException
for (int i = charArray1.length - 1, j = splitD.length -1 ;
i >=0 && j >=0; i--, j--)
{
// convert char to int
splitD[j] = Character.getNumericValue(charArray1[i]);
count++;
}
Recall, int arrays are filled with zeros, at initialization.
Think creating an array of String, one String for each character (including the decimal point), would be a better approach:
String[] chars = String.valueOf(num).split("(?<=.)");
Job done.
Edit:
To use a switch, don't even split:
for (byte b : String.valueOf(num).getBytes()) {
switch(b) {
case '.':
case '1':
}
}