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

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.

Related

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 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.

Tic-tac-toe java: what to do if the user inputs a position that's already taken?

Here is the code I have written so far. My game works just fine but the problem I have is if the user inputs a position that's already taken, yes it keeps asking the user for input, but what i would want it to do it say: This position is unavailable and then reask the user until it's good. I thought about a for loop, but with the loop I have, it says it's unavailable even if it is not...I have been on this for days. If someone could give me some hints I would appreciate it.
import java.util.Scanner;
public class A3Q1_40011419 {
//Creating the board for the user input
static char [][] board = {{'1','2','3'}, {'4','5','6'},{'7','8','9'}};
static Scanner keyboard = new Scanner (System.in);
//Keeping track of the turns
public static int turns = 0;
//Drawing the board
public static void drawBoard() {
int row = 0;
int col = 0;
int turn = 0;
for (row = 0; row < board.length; row++){
for (col = 0; col < board[row].length; col++){
System.out.print(board[row][col]);
System.out.print(" ");
}
System.out.println();
}
}
//Asking user for input
public static void getInput (int playerNum) {
char piece;
char location = ' ';
if (playerNum != 1){
System.out.println("Player X - Enter the position you wish to mark.");
location = keyboard.next().charAt(0);
piece = 'X';
}
else{
System.out.println("Player O - Enter the position you wish to mark.");
location = keyboard.next().charAt(0);
piece = 'O';
}
if (location == '1')
if (board[0][0]=='1')
board[0][0] = piece;
else getInput(playerNum);
else if (location == '2')
if (board[0][1] == '2')
board[0][1] = piece;
else getInput(playerNum);
else if (location == '3')
if (board[0][2] == '3')
board[0][2] = piece;
else getInput(playerNum);
else if (location == '4')
if (board[1][0] == '4')
board[1][0] = piece;
else getInput(playerNum);
else if (location == '5')
if (board[1][1] == '5')
board[1][1] = piece;
else getInput(playerNum);
else if (location == '6')
if (board[1][2] == '6')
board[1][2] = piece;
else getInput(playerNum);
else if (location == '7')
if (board[2][0] == '7')
board[2][0] = piece;
else getInput(playerNum);
else if (location == '8')
if (board[2][1] == '8')
board[2][1] = piece;
else getInput(playerNum);
else if (location == '9')
if (board[2][2] == '9')
board[2][2] = piece;
else getInput(playerNum);
else if (location != '1' || location !='2' || location !='3' || location != '4' || location !='5' || location !='6' || location != '7' || location != '8'|| location !='9'){
System.out.println("That is not a valid position - must be between 1 and 9 inclusive.");
getInput(playerNum);
}
for (int i = 0; i<board.length; i++){
for (int j = 0; j<board.length; j++)
/*if (location == '1' || location == '2' || location == '3'|| location == '4' || location == '5'|| location == '6' || location == '7' || location == '8' || location == '9')*/
if (board[i][j] == 'X' || board[i][j] == 'O'){
System.out.println("Position not available"); //This is was i tried to do so far to check is the position was available on the board. Not working
}
getInput(playerNum);
}
}
//Checking if position available
public static void isAvailable(){ //This is a method i thought of creating to check if the position was available but I have not used it yet.
char location_1 = ' ';
char location_2 = ' ';
char location_3 = ' ';
char location_4 = ' ';
char location_5 = ' ';
char location_6 = ' ';
char location_7 = ' ';
char location_8 = ' ';
char location_9 = ' ';
}
/*Checking if there is a winner by checking if the cells in the board are equal to each other
*and checking if the cell isn't empty. If one isn't empty and they're all equal, then
none of them is empty.*/
public static char isWinner() {
if (board[0][0] == board[1][1] && board[0][0] == board[2][2] && board[0][0]!='1')
return board[0][0];
else if (board[0][0] == board[1][0] && board[0][0] == board[2][0] && board[0][0]!='1')
return board[0][0];
else if (board[0][0]==board[0][1] && board[0][0]==board[0][2] && board[0][0]!='1')
return board[0][0];
else if (board[0][2] == board[1][1] && board[0][2] == board[2][0] && board[0][2] !='3')
return board[0][2];
else if (board[0][2] == board[1][2] && board[0][2] == board[2][2] && board[0][2] != '3')
return board[0][2];
else if (board[2][0] == board [2][1] && board[2][0] == board[2][2] && board[2][0] != '7')
return board[2][0];
else if (board[1][0] == board [1][1] && board[1][0] == board[1][2] && board[1][0] != '4')
return board[1][0];
else if (board[0][1] == board[1][1] && board[0][1] == board[2][1] && board[0][1] != '2')
return board[0][1];
else
return 'Y';
}
//New board for a new game
public static void newBoard() {
board[0][0] = '1';
board[0][1] = '2';
board[0][2] = '3';
board[1][0] = '4';
board[1][1] = '5';
board[1][2] = '6';
board[2][0] = '7';
board[2][1] = '8';
board[2][2] = '9';
}
//Main method
public static void main(String[] args) {
int game = 0;
int playerNum = 1;
String answer;
do {
turns = 0;
newBoard();
while (isWinner() == 'Y') {
drawBoard();
isWinner();
playerNum *= -1;
getInput(playerNum);
turns++;
System.out.println(turns);
if (turns == 9) {
break;
}
}
drawBoard();
if (isWinner() == 'X')
System.out.println("Player X wins");
else if (isWinner()=='O')
System.out.println("Player O wins");
else
System.out.println("It's a tie!");
System.out.println("Would you like to play another game?");
answer = keyboard.next().toLowerCase();
}
while (answer.equals("yes"));
}
}
I would suggest:
You move your check for available position before inserting the new input.
Instead of a loop to check all positions of the grid, you check only the position the player is asking.
Please find a working code below:
public class A3Q1_40011419 {
//Creating the board for the user input
static char [][] board = {{'1','2','3'}, {'4','5','6'},{'7','8','9'}};
static Scanner keyboard = new Scanner (System.in);
//Keeping track of the turns
public static int turns = 0;
//Drawing the board
public static void drawBoard() {
int row = 0;
int col = 0;
int turn = 0;
for (row = 0; row < board.length; row++){
for (col = 0; col < board[row].length; col++){
System.out.print(board[row][col]);
System.out.print(" ");
}
System.out.println();
}
}
//Asking user for input
public static void getInput (int playerNum) {
char piece;
char location = ' ';
if (playerNum != 1){
System.out.println("Player X - Enter the position you wish to mark.");
location = keyboard.next().charAt(0);
piece = 'X';
}
else{
System.out.println("Player O - Enter the position you wish to mark.");
location = keyboard.next().charAt(0);
piece = 'O';
}
//------------------------
// Your new check
int locationInt = Integer.parseInt("" + location);
int x = (locationInt-1)/3;
int y = ((locationInt-1)%3);
if (board[x][y] == 'X' || board[x][y] == 'O'){
System.out.println("Position not available"); //This is was i tried to do so far to check is the position was available on the board. Not working
getInput(playerNum);
return;
}
//------------------------
if (location == '1')
if (board[0][0]=='1')
board[0][0] = piece;
else getInput(playerNum);
else if (location == '2')
if (board[0][1] == '2')
board[0][1] = piece;
else getInput(playerNum);
else if (location == '3')
if (board[0][2] == '3')
board[0][2] = piece;
else getInput(playerNum);
else if (location == '4')
if (board[1][0] == '4')
board[1][0] = piece;
else getInput(playerNum);
else if (location == '5')
if (board[1][1] == '5')
board[1][1] = piece;
else getInput(playerNum);
else if (location == '6')
if (board[1][2] == '6')
board[1][2] = piece;
else getInput(playerNum);
else if (location == '7')
if (board[2][0] == '7')
board[2][0] = piece;
else getInput(playerNum);
else if (location == '8')
if (board[2][1] == '8')
board[2][1] = piece;
else getInput(playerNum);
else if (location == '9')
if (board[2][2] == '9')
board[2][2] = piece;
else getInput(playerNum);
else if (location != '1' || location !='2' || location !='3' || location != '4' || location !='5' || location !='6' || location != '7' || location != '8'|| location !='9'){
System.out.println("That is not a valid position - must be between 1 and 9 inclusive.");
getInput(playerNum);
}
}
//Checking if position available
public static void isAvailable(){ //This is a method i thought of creating to check if the position was available but I have not used it yet.
char location_1 = ' ';
char location_2 = ' ';
char location_3 = ' ';
char location_4 = ' ';
char location_5 = ' ';
char location_6 = ' ';
char location_7 = ' ';
char location_8 = ' ';
char location_9 = ' ';
}
/*Checking if there is a winner by checking if the cells in the board are equal to each other
*and checking if the cell isn't empty. If one isn't empty and they're all equal, then
none of them is empty.*/
public static char isWinner() {
if (board[0][0] == board[1][1] && board[0][0] == board[2][2] && board[0][0]!='1')
return board[0][0];
else if (board[0][0] == board[1][0] && board[0][0] == board[2][0] && board[0][0]!='1')
return board[0][0];
else if (board[0][0]==board[0][1] && board[0][0]==board[0][2] && board[0][0]!='1')
return board[0][0];
else if (board[0][2] == board[1][1] && board[0][2] == board[2][0] && board[0][2] !='3')
return board[0][2];
else if (board[0][2] == board[1][2] && board[0][2] == board[2][2] && board[0][2] != '3')
return board[0][2];
else if (board[2][0] == board [2][1] && board[2][0] == board[2][2] && board[2][0] != '7')
return board[2][0];
else if (board[1][0] == board [1][1] && board[1][0] == board[1][2] && board[1][0] != '4')
return board[1][0];
else if (board[0][1] == board[1][1] && board[0][1] == board[2][1] && board[0][1] != '2')
return board[0][1];
else
return 'Y';
}
//New board for a new game
public static void newBoard() {
board[0][0] = '1';
board[0][1] = '2';
board[0][2] = '3';
board[1][0] = '4';
board[1][1] = '5';
board[1][2] = '6';
board[2][0] = '7';
board[2][1] = '8';
board[2][2] = '9';
}
//Main method
public static void main(String[] args) {
int game = 0;
int playerNum = 1;
String answer;
do {
turns = 0;
newBoard();
while (isWinner() == 'Y') {
drawBoard();
isWinner();
playerNum *= -1;
getInput(playerNum);
turns++;
System.out.println(turns);
if (turns == 9) {
break;
}
}
drawBoard();
if (isWinner() == 'X')
System.out.println("Player X wins");
else if (isWinner()=='O')
System.out.println("Player O wins");
else
System.out.println("It's a tie!");
System.out.println("Would you like to play another game?");
answer = keyboard.next().toLowerCase();
}
while (answer.equals("yes"));
}
}

System.out.print() is not displaying everything I expect and is unexpectedly printing new lines

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

String to Char || Char to String

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

Categories