String to Char || Char to String - java

Let suppose I have a button
case R.id.button:
which will do the following functionality:
int position;
String keyInStringForm = et2.getText().toString();
int keyInIntegerForm = Integer.parseInt(keyInStringForm);
String text = et1.getText().toString();
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == 'a' || text.charAt(i) == 'A') {
position = 0;
break;
} else if (text.charAt(i) == 'b' || text.charAt(i) == 'B') {
position = 1;
break;
} else if (text.charAt(i) == 'c' || text.charAt(i) == 'C') {
position = 2;
break;
} else if (text.charAt(i) == 'd' || text.charAt(i) == 'D') {
position = 3;
break;
} else if (text.charAt(i) == 'e' || text.charAt(i) == 'E') {
position = 4;
break;
} else if (text.charAt(i) == 'f' || text.charAt(i) == 'F') {
position = 5;
break;
} else if (text.charAt(i) == 'g' || text.charAt(i) == 'G') {
position = 6;
break;
} else if (text.charAt(i) == 'h' || text.charAt(i) == 'H') {
position = 7;
break;
} else if (text.charAt(i) == 'i' || text.charAt(i) == 'I') {
position = 8;
break;
} else if (text.charAt(i) == 'j' || text.charAt(i) == 'J') {
position = 9;
break;
} else if (text.charAt(i) == 'k' || text.charAt(i) == 'K') {
position = 10;
break;
} else if (text.charAt(i) == 'l' || text.charAt(i) == 'L') {
position = 11;
break;
} else if (text.charAt(i) == 'm' || text.charAt(i) == 'M') {
position = 12;
break;
} else if (text.charAt(i) == 'n' || text.charAt(i) == 'N') {
position = 13;
break;
} else if (text.charAt(i) == 'o' || text.charAt(i) == 'O') {
position = 14;
break;
} else if (text.charAt(i) == 'p' || text.charAt(i) == 'P') {
position = 15;
break;
} else if (text.charAt(i) == 'q' || text.charAt(i) == 'Q') {
position = 16;
break;
} else if (text.charAt(i) == 'r' || text.charAt(i) == 'R') {
position = 17;
break;
} else if (text.charAt(i) == 's' || text.charAt(i) == 'S') {
position = 18;
break;
} else if (text.charAt(i) == 't' || text.charAt(i) == 'T') {
position = 19;
break;
} else if (text.charAt(i) == 'u' || text.charAt(i) == 'U') {
position = 20;
break;
} else if (text.charAt(i) == 'v' || text.charAt(i) == 'V') {
position = 21;
break;
} else if (text.charAt(i) == 'w' || text.charAt(i) == 'W') {
position = 22;
break;
} else if (text.charAt(i) == 'x' || text.charAt(i) == 'X') {
position = 23;
break;
} else if (text.charAt(i) == 'y' || text.charAt(i) == 'Y') {
position = 24;
break;
} else if (text.charAt(i) == 'z' || text.charAt(i) == 'Z') {
position = 25;
break;
} else if (text.charAt(i) == ' ') {
position = 26;
break;
}
int initialResult = position + keyInIntegerForm;
int finalResult = initialResult % 26;
char resultantChar = alphabets[finalResult];
where as "alphabets" is a char array for a-z characters.
} // for
Now there will be more that one "resultantChar", I want those "resultantChar" to be combined together to form a string so I can set it onto a textview.
How do I do that

If I understood you correctly, try do something like this:
StringBuffer result = new StringBuffer();
for (int i = 0; i < text.length(); i++) {
...
char resultantChar = alphabets[finalResult];
result.append(resultantChar);
}
System.out.println(result);

Please, simplify your code using that!
char ch = 'Z';
ch = Character.toLowerCase(ch);
int position = Character.getNumericValue(ch) - Character.getNumericValue('a');
Or, for your case:
char ch = Character.toLowerCase(text.charAt(i));
if (ch >= 'a' && ch <= 'z') {
position = Character.getNumericValue(ch) - Character.getNumericValue('a');
} else if (ch == ' ') {
position = 26;
}

Use http://developer.android.com/reference/java/lang/StringBuilder.html stringbuilder you can append char with stringbuilder

Related

Simplify a given algebraic string. Output the simplified string without parentheses

The examples look like this, Input : "a-(b+c)" output "a-b-c", Input : "a-(a+b)" output "b"
I came up with this method, but the result for input: "a-(a+b)" is "a-a-b", which the correct one should be "b", how to improve that?
public String simplify(String str)
{
int len = str.length();
char res[] = new char[len];
int index = 0, i = 0;
Stack<Integer> s = new Stack<Integer> ();
s.push(0);
while (i < len) {
if (str.charAt(i) == '+') {
if (s.peek() == 1)
res[index++] = '-';
// If top is 0, append the same operator
if (s.peek() == 0)
res[index++] = '+';
} else if (str.charAt(i) == '-') {
if (s.peek() == 1)
res[index++] = '+';
else if (s.peek() == 0)
res[index++] = '-';
} else if (str.charAt(i) == '(' && i > 0) {
if (str.charAt(i - 1) == '-') {
// x is opposite to the top of stack
int x = (s.peek() == 1) ? 0 : 1;
s.push(x);
}
else if (str.charAt(i - 1) == '+')
s.push(s.peek());
}
else if (str.charAt(i) == ')')
s.pop();
else
res[index++] = str.charAt(i);
i++;
}
return new String(res);
}

Word game importing TXT file

How would I go about setting up a point scoring Scrabble type game that only scans words in a word document. So, in the following code I would have a text file with 30 different words and then I wouldn't need a println of all the lines in the file with the points per work i.e racecar is 11 points
import java.util.HashMap;
import java.util.Map;
class Scrabble {
private String word;
Scrabble(String word) {
this.word = word;
}
int getScore() {
Map<Character, Integer> lettersMap = new HashMap<>();
String lettersCap = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int i = 0; i < lettersCap.length(); i++) {
if (lettersCap.charAt(i) == 'A' || lettersCap.charAt(i) == 'E' ||
lettersCap.charAt(i) == 'I' || lettersCap.charAt(i) == 'O' ||
lettersCap.charAt(i) == 'U' || lettersCap.charAt(i) == 'L' ||
lettersCap.charAt(i) == 'N' || lettersCap.charAt(i) == 'R' ||
lettersCap.charAt(i) == 'S' || lettersCap.charAt(i) == 'T') {
lettersMap.put(lettersCap.charAt(i), 1);
lettersMap.put(lettersCap.toLowerCase().charAt(i), 1);
}
if (lettersCap.charAt(i) == 'D' || lettersCap.charAt(i) == 'G') {
lettersMap.put(lettersCap.charAt(i), 2);
lettersMap.put(lettersCap.toLowerCase().charAt(i), 2);
}
if (lettersCap.charAt(i) == 'B' || lettersCap.charAt(i) == 'C' ||
lettersCap.charAt(i) == 'M' || lettersCap.charAt(i) == 'P') {
lettersMap.put(lettersCap.charAt(i), 3);
lettersMap.put(lettersCap.toLowerCase().charAt(i), 3);
}
if (lettersCap.charAt(i) == 'F' || lettersCap.charAt(i) == 'H' ||
lettersCap.charAt(i) == 'V' || lettersCap.charAt(i) == 'W' ||
lettersCap.charAt(i) == 'Y') {
lettersMap.put(lettersCap.charAt(i), 4);
lettersMap.put(lettersCap.toLowerCase().charAt(i), 4);
}
if (lettersCap.charAt(i) == 'K') {
lettersMap.put(lettersCap.charAt(i), 5);
lettersMap.put(lettersCap.toLowerCase().charAt(i), 5);
}
if (lettersCap.charAt(i) == 'J' || lettersCap.charAt(i) == 'X') {
lettersMap.put(lettersCap.charAt(i), 8);
lettersMap.put(lettersCap.toLowerCase().charAt(i), 8);
}
if (lettersCap.charAt(i) == 'Q' || lettersCap.charAt(i) == 'Z') {
lettersMap.put(lettersCap.charAt(i), 10);
lettersMap.put(lettersCap.toLowerCase().charAt(i), 10);
}
}
int totalValue = 0;
for (int j = 0; j < word.length(); j++) {
totalValue += lettersMap.get(word.charAt(j));
}
return totalValue;
}
}
Fill the Map once and use read from the file, I guess every line has only one word.
You can read the file from Files#lines and loop over every line and count the score of every word
public class Scrabble {
private static Map<Character, Integer> lettersMap = new HashMap<>();
static {
fillMap();
}
private static void fillMap() {
String lettersCap = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int i = 0; i < lettersCap.length(); i++) {
if (lettersCap.charAt(i) == 'A' || lettersCap.charAt(i) == 'E' || lettersCap.charAt(i) == 'I'
|| lettersCap.charAt(i) == 'O' || lettersCap.charAt(i) == 'O' || lettersCap.charAt(i) == 'U'
|| lettersCap.charAt(i) == 'L' || lettersCap.charAt(i) == 'N' || lettersCap.charAt(i) == 'R'
|| lettersCap.charAt(i) == 'S' || lettersCap.charAt(i) == 'T') {
lettersMap.put(lettersCap.charAt(i), 1);
lettersMap.put(lettersCap.toLowerCase().charAt(i), 1);
} else if (lettersCap.charAt(i) == 'D' || lettersCap.charAt(i) == 'G') {
lettersMap.put(lettersCap.charAt(i), 2);
lettersMap.put(lettersCap.toLowerCase().charAt(i), 2);
} else if (lettersCap.charAt(i) == 'B' || lettersCap.charAt(i) == 'C' || lettersCap.charAt(i) == 'M'
|| lettersCap.charAt(i) == 'P') {
lettersMap.put(lettersCap.charAt(i), 3);
lettersMap.put(lettersCap.toLowerCase().charAt(i), 3);
} else if (lettersCap.charAt(i) == 'F' || lettersCap.charAt(i) == 'H' || lettersCap.charAt(i) == 'V'
|| lettersCap.charAt(i) == 'W' || lettersCap.charAt(i) == 'Y') {
lettersMap.put(lettersCap.charAt(i), 4);
lettersMap.put(lettersCap.toLowerCase().charAt(i), 4);
} else if (lettersCap.charAt(i) == 'K') {
lettersMap.put(lettersCap.charAt(i), 5);
lettersMap.put(lettersCap.toLowerCase().charAt(i), 5);
} else if (lettersCap.charAt(i) == 'J' || lettersCap.charAt(i) == 'X') {
lettersMap.put(lettersCap.charAt(i), 8);
lettersMap.put(lettersCap.toLowerCase().charAt(i), 8);
} else if (lettersCap.charAt(i) == 'Q' || lettersCap.charAt(i) == 'Z') {
lettersMap.put(lettersCap.charAt(i), 10);
lettersMap.put(lettersCap.toLowerCase().charAt(i), 10);
}
}
}
public static int readFileAndGetScore(String fileName) {
int result = 0;
Files.lines(new File(fileName).toPath()).forEach(wordInLine -> {
result += getScore(wordInLine);
});
return result;
}
private static int getScore(String word) {
int totalValue = 0;
for (int j = 0; j < word.length(); j++) {
totalValue += lettersMap.get(word.charAt(j));
}
return totalValue;
}
}
main function
public static void main(String[] args) {
String fileName = "data.txt";
int totalScore = Scrabble.readFileAndGetScore(fileName);
System.out.println(totalScore);
}
The readability of your code is not really good and has a lot of more or less code duplicates.
Since you were asking about a good way to set up the scoring system of your class, I'd suggest that you initialize it only once and not each time your scoring-method is called. That means you should create a static Map and use a static initializer.
class Scrabble {
private static final Map<Character, Integer> POINTS_FOR_LETTER = new HashMap<>();
static {
addLettersWithPoints("AEIOULNRST", 1);
addLettersWithPoints("DG", 2);
addLettersWithPoints("BCMP", 3);
addLettersWithPoints("FHVWY", 4);
addLettersWithPoints("K", 5);
addLettersWithPoints("JX", 8);
addLettersWithPoints("QZ", 10);
}
private static void addLettersWithPoints(String chars, Integer points) {
for (char nextLetter : chars.toCharArray()) {
POINTS_FOR_LETTER.put(nextLetter, points);
POINTS_FOR_LETTER.put(Character.toLowerCase(nextLetter), points);
}
}
private static int getScore(String word) {
int score = 0;
for (char nextLetter : word.toCharArray()) {
score += POINTS_FOR_LETTER.get(nextLetter);
}
return score;
}
public static void main(String[] args) {
for (String word : Arrays.asList("Test", "Racecar", "PhysicsquestionWithXAndY")) {
System.out.println(word + " -> " + getScore(word));
}
}
}
Now you can get the score for a word by calling the getScore()-method as shown in the main-method.

How to fix a program that incorrectly calculates the percentages of numbers in Java?

I am trying to find the frequency of each letter in a document, so this program counts up the number of occurrences of each letter, and then finds the total number of letters. Then it's supposed to find the frequency, the problem is it counts the letters correctly and the total, but the percentages incorrectly. How do I calculate the percentage?
//find number of occurrences for each letter
String[] letter = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
int[] count = new int[26];
int totalCount = 0;
for(int i = 0; i < subset.length(); i++)
{
char letters = subset.charAt(i);
if(letters == 'a')
count[0]++;
else if(letters == 'b')
count[1]++;
else if(letters == 'c')
count[2]++;
else if(letters == 'd')
count[3]++;
else if(letters == 'e')
count[4]++;
else if(letters == 'f')
count[5]++;
else if(letters == 'g')
count[6]++;
else if(letters == 'h')
count[7]++;
else if(letters == 'i')
count[8]++;
else if(letters == 'j')
count[9]++;
else if(letters == 'k')
count[10]++;
else if(letters == 'l')
count[11]++;
else if(letters == 'm')
count[12]++;
else if(letters == 'n')
count[13]++;
else if(letters == 'o')
count[14]++;
else if(letters == 'p')
count[15]++;
else if(letters == 'q')
count[16]++;
else if(letters == 'r')
count[17]++;
else if(letters == 's')
count[18]++;
else if(letters == 't')
count[19]++;
else if(letters == 'u')
count[20]++;
else if(letters == 'v')
count[21]++;
else if(letters == 'w')
count[22]++;
else if(letters == 'x')
count[23]++;
else if(letters == 'y')
count[24]++;
else if(letters == 'z')
count[25]++;
}
//find total characters in document
double[] frequency = new double[26];
for(int i = 0; i < 26; i++)
{
totalCount += count[i];
frequency[i] = ((double)count[i] / (totalCount + 1)) * 100; //the problem
}
System.out.println(totalCount);
//for(int i = 0; i < 26; i++)
//{
// frequency[i] = (double)(count[i] / totalCount * 100);
//}
//print
System.out.println(" Letter Occurrences Frequency");
System.out.println("--------------------------------");
for(int i = 0; i < 26; i++)
{
System.out.println(" " + letter[i] + "\t " + count[i] + "\t " + df.format(frequency[i]));
}
The frequency needs to be calculated after you have the totalCount:
for(int i = 0; i < 26; i++) {
totalCount += count[i];
}
System.out.println(totalCount);
System.out.println(" Letter Occurrences Frequency");
System.out.println("--------------------------------");
for(int i = 0; i < 26; i++) {
frequency[i] = ((double)count[i] / (totalCount + 1)) * 100;
System.out.println(" " + letter[i] + "\t " + count[i] + "\t " + df.format(frequency[i]));
}
Side note
You don't need a for loop for totalCount since it's just the length of the string (i.e. totalCount = subset.length())
you wouldn't need 25 if else statements to find letter counts... Just do:
count[subset.charAt(i) - 61]++;
61 is the ASCII value for letter 'a'

How to make multiplication and division counted first in my calculator?

Hello guys im trying to make a calculator that is based on user scanner input, The calculator works fine for calculating from left to right but im having difficulties putting priorities in *,/ and ()
for example 3+(5*2)+1 should be 14 instead mine is 17, and then when i tried
5+((2+1)*3)-1 it gives me weird error..
Can anyone help please? and how can i make my code appear more efficient and simpler thank you in advance.
So here is my code :
System.out.print("Input Equation : ");
n = s.next() + s.nextLine();
n = n.replaceAll("\\s+", "");
char[] nans = n.toCharArray();
c = 0;
for (int i = 0; i < n.length(); i++)
if (nans[i] == '+' || nans[i] == '-' || nans[i] == '/' || nans[i] == '*')
c++;
char[] op = new char[c];
int[] num = new int[c + 1];
c = 0;
for (int i = 0; i < n.length(); i++) {
if (nans[i] == '+' || nans[i] == '-' || nans[i] == '/' || nans[i] == '*') {
op[c] = nans[i];
c++;
}
}
c = 0;
for (int i = 0; i < n.length(); i++) {
if (nans[i] == '1' || nans[i] == '2' || nans[i] == '3' || nans[i] == '4' || nans[i] == '5'
|| nans[i] == '6' || nans[i] == '7' || nans[i] == '8' || nans[i] == '9' || nans[i] == '0')
nus = nus + nans[i];
else if (nans[i] == '+' || nans[i] == '-' || nans[i] == '/' || nans[i] == '*') {
num[c] = Integer.parseInt(nus);
nus = "";
c++;
}
if (i == n.length() - 1){
num[c] = Integer.parseInt(nus);
}
}
for (int i = 0; i < c; i++) {
if (op[i] == '+') {
result = result + num[i] + num[i + 1];
num[i + 1] = 0;
}
else if (op[i] == '-') {
result = result + num[i] - num[i + 1];
num[i + 1] = 0;
}
else if (op[i] == '/') {
result = (result + num[i]) / num[i + 1];
num[i + 1] = 0;
}
else if (op[i] == '*') {
result = (result + num[i]) * num[i + 1];
num[i + 1] = 0;
}
}
System.out.print(" = "+ result);
When you read a token (that is an argument for operator or simply a number), make sure that the next operator is not multiplication or division, otherwise, you want to calculate that one. You can achieve this by means of recursion easily.

JAVA - String index out of range, I can't figure out why

So I'm making a program that decodes a coded message, it compiles but when I run it I get a java.lang.StringIndexOutOfBoundsException: String index out of range: 1 error and I can't figure out where this is coming from.
Here's the code:
import java.util.Scanner;
public class ReverseCodeProgram {
public static int i;
public static String decodeLetter(String s){
String a = "";
if ((s.charAt(0) == '.'))
a = "E";
if ((s.charAt(0) == '-'))
a = "T";
if ((s.charAt(0) == '-') && (s.charAt(1) == '-'))
a = "M";
if ((s.charAt(0) == '-') && (s.charAt(1) == '.'))
a = "N";
if ((s.charAt(0) == '.') && (s.charAt(1) == '.'))
a = "I";
if ((s.charAt(0) == '.') && (s.charAt(1) == '-'))
a = "A";
if ((s.charAt(0) == ' ') && (s.charAt(1) == ' '))
a = " ";
if ((s.charAt(0) == '.') && (s.charAt(1) == '-') && (s.charAt(2) == '.'))
a = "R";
if ((s.charAt(0) == '.') && (s.charAt(1) == '.') && (s.charAt(2) == '.'))
a = "S";
if ((s.charAt(0) == '.') && (s.charAt(1) == '.') && (s.charAt(2) == '-'))
a = "U";
if ((s.charAt(0) == '-') && (s.charAt(1) == '.') && (s.charAt(2) == '.'))
a = "D";
if ((s.charAt(0) == '-') && (s.charAt(1) == '-') && (s.charAt(2) == '.'))
a = "G";
if ((s.charAt(0) == '-') && (s.charAt(1) == '.') && (s.charAt(2) == '-'))
a = "K";
if ((s.charAt(0) == '-') && (s.charAt(1) == '.') && (s.charAt(2) == '-'))
a = "O";
if ((s.charAt(0) == '.') && (s.charAt(1) == '-') && (s.charAt(2) == '-'))
a = "W";
if ((s.charAt(0) == '-') && (s.charAt(1) == '.') && (s.charAt(2) == '.') && (s.charAt(3) == '.'))
a = "B";
if ((s.charAt(0) == '-') && (s.charAt(1) == '.') && (s.charAt(2) == '-') && (s.charAt(3) == '.'))
a = "C";
if ((s.charAt(0) == '.') && (s.charAt(1) == '.') && (s.charAt(2) == '-') && (s.charAt(3) == '.'))
a = "F";
if ((s.charAt(0) == '.') && (s.charAt(1) == '.') && (s.charAt(2) == '.') && (s.charAt(3) == '.'))
a = "H";
if ((s.charAt(0) == '.') && (s.charAt(1) == '-') && (s.charAt(2) == '-') && (s.charAt(3) == '-'))
a = "J";
if ((s.charAt(0) == '.') && (s.charAt(1) == '-') && (s.charAt(2) == '.') && (s.charAt(3) == '.'))
a = "L";
if ((s.charAt(0) == '.') && (s.charAt(1) == '-') && (s.charAt(2) == '-') && (s.charAt(3) == '.'))
a = "P";
if ((s.charAt(0) == '-') && (s.charAt(1) == '-') && (s.charAt(2) == '.') && (s.charAt(3) == '-'))
a = "Q";
if ((s.charAt(0) == '.') && (s.charAt(1) == '.') && (s.charAt(2) == '.') && (s.charAt(3) == '-'))
a = "V";
if ((s.charAt(0) == '-') && (s.charAt(1) == '.') && (s.charAt(2) == '.') && (s.charAt(3) == '-'))
a = "X";
if ((s.charAt(0) == '-') && (s.charAt(1) == '.') && (s.charAt(2) == '-') && (s.charAt(3) == '-'))
a = "Y";
if ((s.charAt(0) == '-') && (s.charAt(1) == '-') && (s.charAt(2) == '.') && (s.charAt(3) == '.'))
a = "Z";
s = a;
return s;
}
public static void main(String[] args) {
System.out.println("Please enter the sentence in Morse code");
String code = new Scanner(System.in).nextLine();
String decodedCharacter = "", character = "", decodedCode = "";
for (i = 0; i < code.length(); i++){
if (code.charAt(i) == ' '){
for (int j = i - 4; j < i; j++){
character += code.charAt(j);
decodedCharacter = "" + decodeLetter(character);
}
decodedCode += decodedCharacter;
}
}
System.out.println(decodedCode);
}
}
For your input, the exception happens at if ((s.charAt(0) == '.') && (s.charAt(1) == '.')) where s is just . and you are trying to access second character of it.
You should have a change in your loop to read the characters:
for (i = 0; i < code.length(); i++) {
if (code.charAt(i) == ' ') {
character = ""; //Clear the value before read
for (int j = i - 4; j < i; j++) {
character += code.charAt(j);
}
decodedCharacter = decodeLetter(character); //This should be outside the for(int j = 1-4 loop for you to read the 4 chars and then pass to decode.
decodedCode += decodedCharacter;
}
}
for (int j = i - 4; j < i; j++)
The above line is causing your error. It's because i is less than 4 when it reaches that line. Try the following instead:
public static void main(String[] args) {
System.out.println("Please enter the sentence in Morse code");
String code[] = new Scanner(System.in).nextLine().split(" ");
String decodedCode = "";
for(String character : code){
decodedCode += decodeLetter(character);
}
System.out.println(decodedCode);
}
It splits the input into a string array by "character" and then iterates over it.

Categories