Filling in array from end - java

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':
}
}

Related

Converting Integers to Roman Numerals in Java

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;
}

Calculate Points from Letters in a Switch Case

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." );
}

the output should display a hyphen (-) after the first 3 digits and subsequently a hyphen after every 4 digits

I have an assignment but i couldn't complete this question.
Previously I add inserted else if (counter == 7) { break; } after the counter==3 but I had removed since the question said to process as many digits as the user wants.
I do not know how to add to count every 4 digit for dash after the first 3 digits dash.
the code below is what I have.
please help and explain to me if possible. thanks :)
import java.util.Scanner;
public class question1 {
public static void main (String [] args)
{
boolean notletter = false;
Scanner console = new Scanner(System.in);
String phoneletter = "";
int counter = 0;
System.out.print("Enter a phone number in letters only: ");
String phoneNumber = console.nextLine();
String phnum2 = phoneNumber.replaceAll(" ", "");
for (int i = 0; i <= phnum2.length() - 1; i++) {
if (!(Character.isLetter(phnum2.charAt(i)))) {
notletter = true;
break;
}
{
switch (Character.toUpperCase(phnum2.charAt(i))) {
case 'A':
case 'B':
case 'C':
phoneletter = phoneletter + "2";
break;
case 'D':
case 'E':
case 'F':
phoneletter = phoneletter + "3";
break;
case 'G':
case 'H':
case 'I':
phoneletter = phoneletter + "4";
break;
case 'J':
case 'K':
case 'L':
phoneletter = phoneletter + "5";
break;
case 'M':
case 'N':
case 'O':
phoneletter = phoneletter + "6";
break;
case 'P':
case 'Q':
case 'R':
case 'S':
phoneletter = phoneletter + "7";
break;
case 'T':
case 'U':
case 'V':
phoneletter = phoneletter + "8";
break;
case 'W':
case 'X':
case 'Y':
case 'Z':
phoneletter = phoneletter + "9";
break;
}
counter++;
if (counter ==3) {
phoneletter = phoneletter + "-";
}
}
}
if (notletter == true) {
System.out.println("Please indicate only alphabets");
} else {
System.out.println(phoneletter);
}
}
}
This can be done by editing the if-statement at the end of your code:
if (counter ==3) {
phoneletter = phoneletter + "-";
}
Here you already checked if the counter is three. If it is, add a hyphen. The next thing to do is to check the case of "a hyphen after every 4 digits". To do this, we can check if counter - 3 is a multiple of 4:
(counter - 3) % 4 == 0
However, this would make it insert an extra - at the end of the output if (input length - 1) is a multiple of 4. So we shouldn't add a hyphen if we reached the end of the string. This can be done by checking whether i is phnom.length() - 1:
i != phnom.length() - 1
If we combine all these conditions together, we get
if (counter == 3 || ((counter - 3) % 4 == 0 && i != phnom.length() - 1)) {
Note: This can actually be done using a regular expression, but since this is homework, I doubt this approach will be accepted. Here is how you do this with regex:
// phoneLetter is a string of digits without any hyphens
String result = phoneLetter.replaceAll("^\\d{3}|\\d{4}(?!$)", "$0-");

Convertion of numeros

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)) {
...
}
}

Objects - What am I doing wrong?

I am attempting to create an array of objects, Trees (like a forest) 12x12. They are all trees at first. The user inputs the number of fires to start and the probability of the fires spreading to one of the surrounding objects. I have it working when I use an array[][] but when trying to make it work with objects I cannot get the objects to check their surrounding objects then decide to catch fire or not. I am new to the site so I am unsure exactly what you need to see.
public static void fireCheck(Tree[][] trees1){
int i = 0;
int c = 0;
for(i = 0; i <= 11; i ++) {
for(c = 0; c <= 11; c ++) {
switch(trees1[i][c].getStatus()){
case '^': break;
case '.': break;
case '*': trees1[i][c].burned(); break;
default: break;
}
if(trees1[i][c].getStatus() == '^'){
if(i <= 10){
switch(trees1[i + 1][c].getStatus()){
case '^': break;
case '.': break;
case '*': trees1[i+1][c].probability(); break;
default: break;
}
if(c <= 10){
switch(trees1[i][c + 1].getStatus()){
case '^': break;
case '.': break;
case '*': trees1[i][c+1].probability(); break;
default: break;
}
switch(trees1[i + 1][c + 1].getStatus()){
case '^': break;
case '.': break;
case '*': trees1[i+1][c+1].probability(); break;
default: break;
}
}
}
if(i >= 1){
switch(trees1[i - 1][c].getStatus()){
case '^': break;
case '.': break;
case '*': trees1[i-1][c].probability(); break;
default: break;
}
if(c >= 1){
switch(trees1[i][c - 1].getStatus()){
case '^': break;
case '.': break;
case '*': trees1[i][c-1].probability(); break;
default: break;
}
switch(trees1[i - 1][c - 1].getStatus()){
case '^': break;
case '.': break;
case '*': trees1[i-1][c-1].probability(); break;
default: break;
}
}
}
if(i <= 10){
if(c >= 1){
switch(trees1[i+1][c-1].getStatus()){
case '^': break;
case '.': break;
case '*': trees1[i+1][c-1].probability(); break;
default: break;
}
}
}
}
}
}
}
I suppose you want to make this program more object oriented.
Create a class Tree, which has some position and a way of identifying if another tree is neighbor.
interface OurTree{
public int getPosition();
public boolean isNeighbour(OurTree tree);
public boolean isBurning();
}
Implementing above interface will help you.
Create a set of objects of the above implemented interface (assume this as forest). Loop through the set, and identify if any tree is on fire. if yes, burn its neighbours.
Alternatively you can define a method to return neighbours of given tree, and burn them all at once.

Categories

Resources