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.
Related
I have made this very obnoxious way of finding the winner in a tic tac toe game and I was just wondering if there is a simpler way of doing this.
This is the method I currently have, and as you can see it is very redundant and repetitive. Any tips to narrow this down would be amazing. I'm thinking maybe a nested for-loop might work but not entirely sure how to set that up within this.
public static boolean isGameOver(char[][] gameBoard) {
//Testing for Horizontal Win
if(gameBoard[0][0] == 'X' && gameBoard[0][2] == 'X' && gameBoard [0][4] == 'X') {
System.out.println("Player Wins!\n");
playerScore++;
return true;
}
if(gameBoard[0][0] == 'O' && gameBoard[0][2] == 'O' && gameBoard [0][4] == 'O') {
System.out.println("CPU Wins!\n");
cpuScore++;
return true;
}
if(gameBoard[2][0] == 'X' && gameBoard[2][2] == 'X' && gameBoard [2][4] == 'X') {
System.out.println("Player Wins!\n");
playerScore++;
return true;
}
if(gameBoard[2][0] == 'O' && gameBoard[2][2] == 'O' && gameBoard [2][4] == 'O') {
System.out.println("CPU Wins!\n");
cpuScore++;
return true;
}
if(gameBoard[4][0] == 'X' && gameBoard[4][2] == 'X' && gameBoard [4][4] == 'X') {
System.out.println("Player Wins!\n");
playerScore++;
return true;
}
if(gameBoard[4][0] == 'O' && gameBoard[4][2] == 'O' && gameBoard [4][4] == 'O') {
System.out.println("CPU Wins!\n");
cpuScore++;
return true;
}
//Testing for Vertical Win
if(gameBoard[0][0] == 'X' && gameBoard[2][0] == 'X' && gameBoard [4][0] == 'X') {
System.out.println("Player Wins!\n");
playerScore++;
return true;
}
if(gameBoard[0][0] == 'O' && gameBoard[2][0] == 'O' && gameBoard [4][0] == 'O') {
System.out.println("CPU Wins!\n");
cpuScore++;
return true;
}
if(gameBoard[0][2] == 'X' && gameBoard[2][2] == 'X' && gameBoard [4][2] == 'X') {
System.out.println("Player Wins!\n");
playerScore++;
return true;
}
if(gameBoard[0][2] == 'O' && gameBoard[2][2] == 'O' && gameBoard [4][2] == 'O') {
System.out.println("CPU Wins!\n");
cpuScore++;
return true;
}
if(gameBoard[0][4] == 'X' && gameBoard[2][4] == 'X' && gameBoard [4][4] == 'X') {
System.out.println("Player Wins!\n");
playerScore++;
return true;
}
if(gameBoard[0][4] == 'O' && gameBoard[2][4] == 'O' && gameBoard [4][4] == 'O') {
System.out.println("CPU Wins!\n");
cpuScore++;
return true;
}
//Testing for Diagonal Win
if(gameBoard[0][0] == 'X' && gameBoard[2][2] == 'X' && gameBoard [4][4] == 'X') {
System.out.println("Player Wins!\n");
playerScore++;
return true;
}
if(gameBoard[0][0] == 'O' && gameBoard[2][2] == 'O' && gameBoard [4][4] == 'O') {
System.out.println("CPU Wins!\n");
cpuScore++;
return true;
}
if(gameBoard[4][0] == 'X' && gameBoard[2][2] == 'X' && gameBoard [0][4] == 'X') {
System.out.println("Player Wins!\n");
playerScore++;
return true;
}
if(gameBoard[4][0] == 'O' && gameBoard[2][2] == 'O' && gameBoard [0][4] == 'O') {
System.out.println("CPU Wins!\n");
cpuScore++;
return true;
}
//Testing for Tie
if(gameBoard[0][0] != ' ' && gameBoard[0][2] != ' ' && gameBoard[0][4] != ' ' &&
gameBoard[2][0] != ' ' && gameBoard[2][2] != ' ' && gameBoard[2][4] != ' ' &&
gameBoard[4][0] != ' ' && gameBoard[4][2] != ' ' && gameBoard[4][4] != ' ') {
System.out.println("It's a tie!!!\n");
numOfTies++;
return true;
}
return false;
}
Ok, I got a little carried away. But perhaps you could use some ideas presented here. My main goal was to make it so the entire board need not be checked after each move. This is the type of issue that is best considered during the design phase of a program.
I created a TriGroup class (which is essentially a mutable string to hold successive moves.
Then a map is used to hold all the groupings which have a common coordinate.
when a move is made, those groupings have the current player appended.
and check is done to see if that player won.
this program will run by itself using random moves resulting in a victory or a tie.
Some border cases may have been overlooked.
public class TicTacToeCheck {
int moveCount = 0;
static int MAX_MOVES = 27;
class TriGroup {
public String group = "";
#Override
public String toString() {
return group;
}
}
TriGroup row1 = new TriGroup();
TriGroup row2 = new TriGroup();
TriGroup row3 = new TriGroup();
TriGroup col1 = new TriGroup();
TriGroup col2 = new TriGroup();
TriGroup col3 = new TriGroup();
TriGroup diag1 = new TriGroup();
TriGroup diag2 = new TriGroup();
Map<String, List<TriGroup>> commonGroupings = new HashMap<>();
{
commonGroupings.put("00", List.of(row1, col1, diag1));
commonGroupings.put("02", List.of(row1, col2));
commonGroupings.put("04", List.of(row1, col3));
commonGroupings.put("20", List.of(row2, col1));
commonGroupings.put("22", List.of(row2, col2, diag1, diag2));
commonGroupings.put("24", List.of(row2, col3));
commonGroupings.put("40", List.of(row3, col1, diag1));
commonGroupings.put("42", List.of(row3, col2));
commonGroupings.put("44", List.of(row3, col3));
}
public static void main(String[] args) {
new TicTacToeCheck().start();
}
public void start() {
char player = 'X';
Random r = new Random();
outer: while (moveCount < MAX_MOVES) {
commonGroupings.entrySet().forEach(System.out::println);
System.out.println();
int row = r.nextInt(3) * 2;
int col = r.nextInt(3) * 2;
System.out.println("Move: " + row + ", " + col);
player = player == 'X' ? 'O' : 'X';
char val;
switch (val = recordMove(row, col, player)) {
case 'X' -> {
System.out.println("X wins!");
break outer;
}
case 'O' -> {
System.out.println("O wins!");
break outer;
}
case 0 -> {
System.out.println("Tie!");
break outer;
}
default -> {
}
}
}
commonGroupings.entrySet().forEach(System.out::println);
}
public char recordMove(int row, int col, char c) {
moveCount++;
for (TriGroup tri : commonGroupings.get(row + "" + col)) {
if (tri.group.length() > 2) {
// just ignore the row/col and try the next
continue;
}
// update group
tri.group += c;
if (tri.group.equals(c + "" + c + "" + c)) {
return c;
}
}
if (moveCount == MAX_MOVES) {
return 0;
}
return '#';
}
}
This version uses 2 auxiliary, private methods to make the code less repetitive, without changing the behavior of calling isGameOver. The main observation is that there is very little difference between checking for a win by O or checking for one by X - only a single character. So that becomes checkWins. The next observation is that there is a lot of repetition involved in checking 3 positions of the board that are next to each other. If you give me the char to expect, where to start, and where to look next (dcol and drow), that becomes allEqual.
Your code skips over uneven positions of the board; my code does not. I feel that it is an error to mix presentation ("how you show things to users") with model ("how you represent things internally"); so my code is not currently a drop-in replacement for yours, but can quickly be fixed to be such a replacement by tweaking values in checkWins (diagonal down would be 0, 0, 2, 2, and so on).
Note that, efficiency-wise, your code is probably faster. But I find this version to be much shorter, more readable, and therefore easier to debug & maintain.
private static boolean allEqual(char expected, char[][] b,
int row, int col, int drow, int dcol) {
for (int i=0; i<b[0].length; i++) {
if (b[row][col] != expected) return false;
row += drow;
col += dcol;
}
return true;
}
private static boolean checkWins(char playerChar, char[][]b) {
boolean win = allEqual(playerChar, b, 0, 0, 0, 1) // 1st row
|| allEqual(playerChar, b, 1, 0, 0, 1)
|| allEqual(playerChar, b, 2, 0, 0, 1) // 3rd row
|| allEqual(playerChar, b, 0, 0, 1, 0) // 1st col
|| allEqual(playerChar, b, 0, 1, 1, 0)
|| allEqual(playerChar, b, 0, 2, 1, 0) // 3rd col
|| allEqual(playerChar, b, 0, 0, 1, 1) // diagonal down
|| allEqual(playerChar, b, 2, 0, 1,-1); // diagonal up
return win;
}
public static boolean isGameOver(char[][] gameBoard) {
if (checkWins('X', gameBoard)) {
System.out.println("Player Wins!\n");
playerScore ++;
return true;
} else if (checkWins('O', gameBoard)) {
System.out.println("CPU Wins!\n");
cpuScore ++;
return true;
} else {
return false;
}
}
Take a look at this:
https://www.geeksforgeeks.org/tic-tac-toe-game-in-java/
Add the strings of gameBoard[x][y] and check them in a switch statement.
If the compound strings are equals to XXX or OOO, you can return the winner.
For your code something like this:
for (int a = 0; a < 8; a++) {
String line = null;
switch (a) {
case 0:
line = gameBoard[0][0] + gameBoard[0][1] + gameBoard[0][2];
break;
case 1:
line = gameBoard[1][0] + gameBoard[1][1] + gameBoard[1][2];
break;
case 2:
line = gameBoard[2][0] + gameBoard[2][1] + gameBoard[2][2];
break;
case 3:
line = gameBoard[0][0] + gameBoard[1][0] + gameBoard[2][0];
break;
case 4:
line = gameBoard[0][1] + gameBoard[1][1] + gameBoard[2][1];
break;
case 5:
line = gameBoard[0][2] + gameBoard[1][2] + gameBoard[2][2];
break;
case 6:
line = gameBoard[0][0] + gameBoard[1][1] + gameBoard[2][2];
break;
case 7:
line = gameBoard[0][2] + gameBoard[1][1] + gameBoard[2][0];
break;
}
//For X winner
if (line.equals("XXX")) {
return "X";
}
// For O winner
else if (line.equals("OOO")) {
return "O";
}
}
I've been trying to figure out how to ignore the blank space/digits/letters by using the character.isDigit & character.isLetter method when the users enters a String.. Can you guys please advise me?
When I tried the input with GETLOAN (Without the space) it works well...
But when I enter a space between e..g. Get Loan, the program shows an error..
public static void main(String[] args) {
String letters;
char phoneDigit;
Scanner kb = new Scanner(System.in);
System.out.println("Enter letters : ");
letters = kb.next();
for (int i = 0; i < 7; i++) {
phoneDigit = letters.charAt(i);
// Using character.isDigit...
if (Character.isDigit(phoneDigit) == true || Character.isLetter(phoneDigit) == true);
{
if (i == 3) {
System.out.println("-");
} //If
if (phoneDigit >= 'A' && phoneDigit <= 'C'
|| phoneDigit >= 'a' && phoneDigit <= 'c') {
System.out.println("2");
} else if (phoneDigit >= 'D' && phoneDigit <= 'F'
|| phoneDigit >= 'd' && phoneDigit <= 'f') {
System.out.println("3");
} else if (phoneDigit >= 'G' && phoneDigit <= 'I'
|| phoneDigit >= 'g' && phoneDigit <= 'i') {
System.out.println("4");
} else if (phoneDigit >= 'J' && phoneDigit <= 'L'
|| phoneDigit >= 'j' && phoneDigit <= 'l') {
System.out.println("5");
} else if (phoneDigit >= 'M' && phoneDigit <= 'O'
|| phoneDigit >= 'm' && phoneDigit <= 'o') {
System.out.println("6");
} else if (phoneDigit >= 'P' && phoneDigit <= 'S'
|| phoneDigit >= 'p' && phoneDigit <= 's') {
System.out.println("7");
} else if (phoneDigit >= 'T' && phoneDigit <= 'V'
|| phoneDigit >= 't' && phoneDigit <= 'v') {
System.out.println("8");
} else if (phoneDigit >= 'W' && phoneDigit <= 'Z'
|| phoneDigit >= 'W' && phoneDigit <= 'z') {
System.out.println("9");
} // If
} // If
} // For loop
} //PSVM
remove the semicolon(;) from here
if (Character.isDigit(phoneDigit) == true || Character.isLetter(phoneDigit) == true);//semicolon
; means end of statement.This means if conditions ended there.The statements under if will always be executed irrespective of what if returns(true or false) so the rest of statements under {} will simply behave as non static blocks
When I tried the input with GETLOAN (Without the space) it works well... But when I enter a space between e..g. Get Loan, the program shows an error..
You are getting error when you enter space because of the reason I specified above as the statements under if will always be executed
If you enter two words separated by a space, e.g. "get loan", the Scanner produces two output elements, i.e. the invocation of kb.next() just returns "get". A second invocation would return "loan". The Scanner class is not the right class to use for your purpose.
Use something like
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter String");
String s = br.readLine();
to read from the console.
System.out.print() is not displaying everything in the output box and when I enter to many characters it automatically makes a new line. I am entering 645 characters and when I press enter it should give me the corresponding 215 characters. Should i be using something other than System.out.print() for this?
import java.io.*;
public class Animal {
public static void main(String[] args) {
int A = 0;
int B = 1;
int C = 2;
System.out.print("codons=");
String str = read();
for (int num = 0; num <= str.length() / 3; num++) {
if (str.charAt(A) == 'T' && str.charAt(B) == 'A' && str.charAt(C) == 'G') {
System.out.print("a");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'G' && str.charAt(C) == 'T') {
System.out.print("b");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'T' && str.charAt(C) == 'T') {
System.out.print("c");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'T' && str.charAt(C) == 'T') {
System.out.print("d");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'A' && str.charAt(C) == 'A') {
System.out.print("e");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'G' && str.charAt(C) == 'C') {
System.out.print("f");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'A' && str.charAt(C) == 'C') {
System.out.print("g");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'C' && str.charAt(C) == 'A') {
System.out.print("h");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'T' && str.charAt(C) == 'G') {
System.out.print("i");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'T' && str.charAt(C) == 'T') {
System.out.print("j");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'C' && str.charAt(C) == 'A') {
System.out.print("k");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'A' && str.charAt(C) == 'C') {
System.out.print("l");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'A' && str.charAt(C) == 'A') {
System.out.print("m");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'G' && str.charAt(C) == 'C') {
System.out.print("n");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'G' && str.charAt(C) == 'T') {
System.out.print("o");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'C' && str.charAt(C) == 'A') {
System.out.print("p");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'T' && str.charAt(C) == 'A') {
System.out.print("q");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'T' && str.charAt(C) == 'A') {
System.out.print("r");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'C' && str.charAt(C) == 'T') {
System.out.print("s");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'G' && str.charAt(C) == 'A') {
System.out.print("t");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'C' && str.charAt(C) == 'C') {
System.out.print("u");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'T' && str.charAt(C) == 'G') {
System.out.print("v");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'T' && str.charAt(C) == 'C') {
System.out.print("w");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'G' && str.charAt(C) == 'T') {
System.out.print("x");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'A' && str.charAt(C) == 'T') {
System.out.print("y");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'G' && str.charAt(C) == 'G') {
System.out.print("z");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'C' && str.charAt(C) == 'T') {
System.out.print("0");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'T' && str.charAt(C) == 'T') {
System.out.print("1");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'C' && str.charAt(C) == 'T') {
System.out.print("2");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'A' && str.charAt(C) == 'T') {
System.out.print("3");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'G' && str.charAt(C) == 'A') {
System.out.print("4");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'C' && str.charAt(C) == 'G') {
System.out.print("5");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'C' && str.charAt(C) == 'C') {
System.out.print("6");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'A' && str.charAt(C) == 'T') {
System.out.print("7");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'G' && str.charAt(C) == 'C') {
System.out.print("8");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'T' && str.charAt(C) == 'A') {
System.out.print("9");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'T' && str.charAt(C) == 'A') {
System.out.print(" ");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'G' && str.charAt(C) == 'G') {
System.out.println("");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'G' && str.charAt(C) == 'C') {
System.out.print(">");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'G' && str.charAt(C) == 'G') {
System.out.print("<");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'C' && str.charAt(C) == 'T') {
System.out.print("+");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'A' && str.charAt(C) == 'G') {
System.out.print("}");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'A' && str.charAt(C) == 'C') {
System.out.print("/");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'C' && str.charAt(C) == 'A') {
System.out.print("=");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'G' && str.charAt(C) == 'A') {
System.out.print(".");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'A' && str.charAt(C) == 'G') {
System.out.print("!");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'A' && str.charAt(C) == 'G') {
System.out.print(":");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'G' && str.charAt(C) == 'A') {
System.out.print("'");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'T' && str.charAt(C) == 'G') {
System.out.print(",");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'C' && str.charAt(C) == 'G') {
System.out.print("#");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'C' && str.charAt(C) == 'C') {
System.out.print("-");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'G' && str.charAt(C) == 'G') {
System.out.print("newline");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'T' && str.charAt(C) == 'C') {
System.out.print("\\");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'A' && str.charAt(C) == 'A') {
System.out.print("{");
} else if (str.charAt(A) == 'G' && str.charAt(B) == 'A' && str.charAt(C) == 'C') {
System.out.print("(");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'C' && str.charAt(C) == 'C') {
System.out.print("&");
} else if (str.charAt(A) == 'C' && str.charAt(B) == 'C' && str.charAt(C) == 'G') {
System.out.print(")");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'T' && str.charAt(C) == 'C') {
System.out.print("$");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'G' && str.charAt(C) == 'G') {
System.out.print("]");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'T' && str.charAt(C) == 'C') {
System.out.print("#");
} else if (str.charAt(A) == 'T' && str.charAt(B) == 'G' && str.charAt(C) == 'T') {
System.out.print(";");
} else if (str.charAt(A) == 'A' && str.charAt(B) == 'T' && str.charAt(C) == 'G') {
System.out.print("*");
}
A += 3;
B += 3;
C += 3;
}
System.out.println("");
}
public static String read() {
byte[] buffer = new byte[647];
try {
int numBytes = System.in.read(buffer);
} catch (IOException e) {
System.out.print("Error: " + e);
System.exit(1);
}
String str = new String(buffer);
return (str);
}
public static void write(String str) {
System.out.print(str);
}
}
It's unclear what you're trying to do but I'll try to give you some pointers in the hope they will help solve your problem.
Format your code correctly. It's impossible to read otherwise.
Use meaningful variables names. A, B, C, and str are all meaningless. People (yourself included) will have an easier time reading your code if you provide hints via clear variable and method names.
When you find yourself re-writing the same lines of code over and over again (like your massive list of conditionals) that's a good hint you should restructure your code. It looks like you're trying to map groups of three characters to single characters, a Map<String, String> can do this easily in roughly three lines.
In that vein, look closely at the functionality provided by String, particularly String.substring() - you can get each three-letter substring easily, without manually extracting each character.
Avoid repeated function calls; even if you keep your str.charAt() behavior, you can put them at the top of your for loop and assign them to variables so they're only done once per iteration, then each conditional simply checks the variables. str.charAt() is fast, but many other methods aren't, and there's no need to waste the effort of calling the same method over and over again.
There's no need to directly read from System.in's byte stream. You can simply use a Scanner or if necessary a BufferedReader.
You have a println midway through your conditional block, for the first "GGG" case. Is that intentional? If not, it might be why you're seeing unexpected new lines. Otherwise, there's nothing in your code that will generate undesirable new lines, it's possible your terminal is simply wrapping the single line across multiple lines visually so you can see the whole output.
You never use your write() method; you should probably just delete that.
This will give you 215 characters, only if in your input string each time any if condition satisfied. Otherwise it will not be able to print anything. if you still think, that your input string satisfy the conditions and you are not getting output as expected then share your input for this program.
One more correction to your question, for the below condition, you are using System.out.println whereas for others it is System.out.print, if this condition get's satisfied then you will get the other characters in new line.
else if (str.charAt(A) == 'G' && str.charAt(B) == 'G'
&& str.charAt(C) == 'G') {
System.out.println("");
}
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
I have coded the next function. But surely someone has a more elegant way to perform this task.
/**
*
* HTML 4 Specification
* ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number
* of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
* #param s
* #return
*/
public static String sanitizeHTMLIdAttribute(String s) {
String sanitize = "";
if(s!=null) {
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) == '-' || s.charAt(i) == '_' || s.charAt(i) == ':' ||
s.charAt(i) == '.' || s.charAt(i) == '0' || s.charAt(i) == '1' ||
s.charAt(i) == '2' || s.charAt(i) == '3' || s.charAt(i) == '4' ||
s.charAt(i) == '5' || s.charAt(i) == '6' || s.charAt(i) == '7' ||
s.charAt(i) == '8' || s.charAt(i) == '9' ||
s.charAt(i) == 'a' || s.charAt(i) == 'b' || s.charAt(i) == 'c' ||
s.charAt(i) == 'd' || s.charAt(i) == 'e' || s.charAt(i) == 'f' ||
s.charAt(i) == 'g' || s.charAt(i) == 'h' || s.charAt(i) == 'i' ||
s.charAt(i) == 'j' || s.charAt(i) == 'k' || s.charAt(i) == 'l' ||
s.charAt(i) == 'm' || s.charAt(i) == 'n' || s.charAt(i) == 'o' ||
s.charAt(i) == 'p' || s.charAt(i) == 'q' || s.charAt(i) == 'r' ||
s.charAt(i) == 's' || s.charAt(i) == 't' || s.charAt(i) == 'u' ||
s.charAt(i) == 'w' || s.charAt(i) == 'x' || s.charAt(i) == 'y' ||
s.charAt(i) == 'z' ||
s.charAt(i) == 'A' || s.charAt(i) == 'B' || s.charAt(i) == 'C' ||
s.charAt(i) == 'D' || s.charAt(i) == 'E' || s.charAt(i) == 'F' ||
s.charAt(i) == 'G' || s.charAt(i) == 'H' || s.charAt(i) == 'I' ||
s.charAt(i) == 'J' || s.charAt(i) == 'K' || s.charAt(i) == 'L' ||
s.charAt(i) == 'M' || s.charAt(i) == 'N' || s.charAt(i) == 'O' ||
s.charAt(i) == 'P' || s.charAt(i) == 'Q' || s.charAt(i) == 'R' ||
s.charAt(i) == 'S' || s.charAt(i) == 'T' || s.charAt(i) == 'U' ||
s.charAt(i) == 'W' || s.charAt(i) == 'X' || s.charAt(i) == 'Y' ||
s.charAt(i) == 'Z') {
sanitize += s.charAt(i);
}
}
if(sanitize.length()>0) {
while(sanitize.charAt(0) == '0' || sanitize.charAt(0) == '1' ||
sanitize.charAt(0) == '2' || sanitize.charAt(0) == '3' ||
sanitize.charAt(0) == '4' || sanitize.charAt(0) == '5' ||
sanitize.charAt(0) == '6' || sanitize.charAt(0) == '7' ||
sanitize.charAt(0) == '8' || sanitize.charAt(0) == '9') {
sanitize = sanitize.substring(1, sanitize.length());
}
}
return sanitize;
}
return null;
}
I would do something like this:
/**
*
* HTML 4 Specification ID and NAME tokens must begin with a letter
* ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]),
* hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
*
* #param s
* #return
*/
public static String sanitizeHTMLIdAttribute(String s) {
if (s == null) return null;
StringBuilder sb = new StringBuilder();
int firstLegal = 0;
while (firstLegal < s.length() && !isAZ(s.charAt(firstLegal)))
++firstLegal;
for (int i = firstLegal; i < s.length(); ++i){
final char ch = s.charAt(i);
if (isOkIdInnerChar(ch)) sb.append(ch);
}
return sb.length() == s.length()? s : sb.toString();
}
private static boolean isOkIdInnerChar(char ch) {
return isAZ(ch) || isNum(ch) || isSpecial(ch);
}
private static boolean isSpecial(char ch) {
switch (ch) {
case '-': case '_':
case ':': case '.':
return true;
default:
return false;
}
}
private static boolean isAZ(char ch) {
return ('A' <= ch && ch <= 'Z') || ('a' <= ch && ch <= 'z');
}
private static boolean isNum(char ch) {
return '0' <= ch && ch <= '9';
}
... except that I'd probably prefer to throw an NullPointerException if s == null, and IllegalArgumentException if s contains no legal characters, but that's a matter of preference, of course. Some extra features:
If s is a valid ID, it's returned as-is to save space (fewer string instances floating around) and time (String construction is expensive -- yes, I know allocation is cheap, but there's more going on there than allocation).
I don't use Character.isDigit 'cause it returns true for all Unicode digits, including stuff like "٣"
I don't use Character.isLetter 'cause it returns true for all Unicode letters, including stuff like "å"
You could significantly shorten your code by using Character.isLetterOrDigit(char); e.g.
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isLetterOrDigit(c) || c == '.' || etc ...) {
}
}
You could do this in conjunction with storing the permitted punctuation characters in a Set; e.g.
private static final Set<Character> ALLOWED =
new HashSet<Character>(Arrays.asList('.', '-', '_', ':'));
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (ALLOWED.contains(c)) {
}
}
You might want to check the expressions (regex isn't my forte), but this should drop invalid characters:
private static Pattern INVALID_LEADING = Pattern.compile("^[^a-zA-Z]+");
private static Pattern INVALID = Pattern
.compile("[^\\w\\u002e\\u003a\\u002d\\u005f]+");
private static String sanitize(String id) {
Matcher matcher = INVALID_LEADING.matcher(id);
if (matcher.find()) {
id = matcher.replaceFirst("");
}
Matcher invalid = INVALID.matcher(id);
if (invalid.find()) {
id = invalid.replaceAll("");
}
return id;
}
If you aren't happy with regex, be aware that many of your characters are in contiguous ranges, so can be detected with methods like this:
private static boolean isLatinDigit(char ch) {
return ch >= '0' && ch <= '9';
}