Array of Characters not updated properly java - java
I am trying to make pong in a terminal on windows in java.
I have an array of characters (called board) and the paddle positions are updated by the following code
public void movePaddles()
{
int inp = 0;
try
{
inp = System.in.read();
}
catch(Exception e)
{
return;
}
int olr = rtop;
int oll = ltop;
switch(inp)
{
case 'w':
ltop -=1;
break;
case 's':
ltop += 1;
break;
case 'i':
rtop -= 1;
break;
case 'k':
rtop += 1;
break;
}
updatePaddle('L',oll);
updatePaddle('R',olr);
}
public void updatePaddle(char side,int oldtop)
{
int edge = 0;
int top = 0;
// Leave 1 char of space
if (side == 'L')
{
edge = 1;
top = ltop;
}
else if (side == 'R')
{
edge = y-2;
top = rtop;
}
for (int i = oldtop;i < paddleSize+1;i++)
{
board[i][edge] = ' ';
}
for (int i = top;i < paddleSize+2;i++)
{
board[i][edge] = paddleChar;
}
}
What ends up happening is that the paddles disappear when moving down, making the game unplayable. What am I doing wrong?
(full code on github at https://github.com/Tookmund/Text-Pong)
I did try debugging my program before I posted my question but not properly it appears.
Basically I needed to add the value of the current location (top/oldtop) so that the loop would not exit prematurely because i was initially bigger that the paddleSize.
Related
How do you input a Array's of ints and chars to a method that requires chars and ints
I have two classes that do two different things. I am trying to get my FileAccess class to use my encryption class to to encode a set number of phrases in a text file. The first 10 numbers in the file give the program the key value and that should be stored as a int and what comes after the file should be stored as a array of char and those need to be called by the encryption class to code the phrase. I do not know why I can't call my encryption class and I am stumped. Sorry for being unclear I am trying to design an code that will accept a number of phrases as input and allow the user to encrypt it through the use of an encryption key. This key should be made up of an integer number between-2000000 and +2000000.The encryption algorithm uses the key to shift the letters of the alphabet to the right or left.For example A encoded with a key of 3 would produce D three letters to its right in the alphabet. If the key is so large that the new letter goes past the end of the alphabet, the program should wrap around to a letter near the beginning of the alphabet. The FileAccess class – This class should read several phrases from a file. The first line of the file should contain an integer indicating the number of phrases in the file. The first 10 characters of each phrase in the file should contain the encryption key to be used in the encryption and decryption process for that phrase. This class should provide a way to access this information by other classes. Finally, this class should have a second method to allow phrases to be saved into a new file. I tried to be as clear as i can now. My problem is I cant call my encode method in my encryption class Here is the code for the File Access. public class FileAccess { public static String[] load(String fileName) throws IOException { FileReader file = new FileReader(fileName); //open file for reading BufferedReader input = new BufferedReader(file); int sizeF = Integer.parseInt(input.readLine()); // variable for the size of the array String infoInFile[] = new String[sizeF]; // declare and create a string array for (int i = 0; i < sizeF; i++) { // loop to read the file into the array infoInFile[i] = input.readLine(); } input.close();//close the file return infoInFile; } public static int[] key(String finalKey[]) { int finaloutput[] = new int[5]; String temp; for (int i = 0; i < finalKey.length; i++) { temp = finalKey[i].substring(0, 11); finaloutput[i] = Integer.parseInt(temp); System.out.println(finaloutput[i]); } return finaloutput; } public static char[] phrase(String EndOfPhrase[]) { char letter[] = new char[5]; for (int j = 0; j < EndOfPhrase.length; j++) { String phrase; phrase = EndOfPhrase[j].substring(11); char temp = phrase.charAt(1); letter = phrase.toCharArray(); System.out.println(letter); } return letter; } public static void main(String[] args) throws IOException { String output[]; // call the loader int[] keyTest; char[] phraseTest; String display; output = FileAccess.load("phrase.txt"); keyTest = key(output); phraseTest = phrase(output); for (int i = 0; i < output.length; i++) { } } } I am not sure if I should have that for loop, but scice the encryption encode method only takes in 1 char at a time and codes I think I need a for loop to keep calling it HERE IS THE CODE FOR THE encryption code public class Encryption { public static boolean isNotALetter(char character) { // returns false if the character is a letter boolean yorn = false; return yorn; } public static char encode(char letter, int key) { // returns an encrypted character char encryptedcharacter = 0; int truevalueofkey = 0; int valueofletter; int newvalueofletter; valueofletter = Encryption.lettertovalue(letter); truevalueofkey = key % 26; newvalueofletter = (valueofletter + truevalueofkey)%26; encryptedcharacter = Encryption.valueToLetter(newvalueofletter); // add truevalueofkey to key to get return encryptedcharacter; } public static char decode(char letter, int key) { // returns a decrypted character char decodedcharacter = 0; int dtruevalueofkey = 0; int dvalueofletter; int dnewvalueofletter; dvalueofletter = Encryption.lettertovalue(letter); dtruevalueofkey = key % 26; dnewvalueofletter = (dvalueofletter - dtruevalueofkey)%26; decodedcharacter = Encryption.valueToLetter(dnewvalueofletter); return decodedcharacter; } public static int lettertovalue(char letter) { // get value of each letter ex A = 1 int value = 0; // convert to string based on char switch (letter) { case 'a': { value = 1; break; } case 'b': { value = 2; break; } case 'c': { value = 3; break; } case 'd': { value = 4; break; } case 'e': { value = 5; break; } case 'f': { value = 6; break; } case 'g': { value = 7; break; } case 'h': { value = 8; break; } case 'i': { value = 9; break; } case 'j': { value = 10; break; } case 'k': { value = 11; break; } case 'l': { value = 12; break; } case 'm': { value = 13; break; } case 'n': { value = 14; break; } case 'o': { value = 15; break; } case 'p': { value = 16; break; } case 'q': { value = 17; break; } case 'r': { value = 18; break; } case 's': { value = 19; break; } case 't': { value = 20; break; } case 'u': { value = 21; break; } case 'v': { value = 22; break; } case 'w': { value = 23; break; } case 'x': { value = 24; break; } case 'y': { value = 25; break; } case 'z': { value = 26; break; } } return value; } public static char valueToLetter(int value) { char letter = 0; if (value == 1) { letter = 'a'; } if (value == 2) { letter = 'b'; } if (value == 3) { letter = 'c'; } if (value == 4) { letter = 'd'; } if (value == 5) { letter = 'e'; } if (value == 6) { letter = 'f'; } if (value == 7) { letter = 'g'; } if (value == 8) { letter = 'h'; } if (value == 9) { letter = 'i'; } if (value == 10) { letter = 'j'; } if (value == 11) { letter = 'k'; } if (value == 12) { letter = 'l'; } if (value == 13) { letter = 'm'; } if (value == 14) { letter = 'n'; } if (value == 15) { letter = 'o'; } if (value == 16) { letter = 'p'; } if (value == 17) { letter = 'q'; } if (value == 18) { letter = 'r'; } if (value == 19) { letter = 's'; } if (value == 20) { letter = 't'; } if (value == 21) { letter = 'u'; } if (value == 22) { letter = 'v'; } if (value == 23) { letter = 'w'; } if (value == 24) { letter = 'x'; } if (value == 25) { letter = 'w'; } if (value == 26) { letter = 'z'; } return letter; } public static void main(String[] args) { String yrn = "y"; while (yrn == "y") { String alsdjkf = JOptionPane.showInputDialog(null, "Enter the letter"); char enchar = alsdjkf.charAt(0); int keyr = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter the key")); char newchar = Encryption.decode(enchar, keyr); JOptionPane.showMessageDialog(null, newchar); yrn = JOptionPane.showInputDialog(null, "yes or no"); } } } This is what is in the text file: 2 00000000003 The cook worked 12 hours in the darkened kitchen! 00000000025 Did Fred look well? That’s it!
Unfortunately it's quite hard to tell from your question what you are trying to do. I think you want each line to be interpreted as 10 digits and then a phrase to be encoded by the key represented by the digits. Assuming that's correct, I have several suggestions for changes to your code. I recommend you try these and then come back if they don't solve your problem. FileAccess.load is unnecessary. You can use Files.lines to get all lines in a file in a single statement (use Stream.toArray if you really need it to be in an array). The massive switch statements to just turn char to int are not needed. You can do math on char values such as letter - 'a' to simplify these. Use a regular expression rather than decoding each line yourself. "(\\d{10}) (.*)" will read the key and phrase in a single statement. Once you have the key and phrase you can call your "encryption" code for each line. And just a warning: if you come back and say "I'm not allowed to use X or Y in my answer" then my comment will be "that would have been useful to know before I put time into trying to help you"!
Experiencing issues with overwriting previous instance of ArrayList object initialization
EDIT: I may have fixed it by making the instance variable static? If so, why does this fix it? This was something my prof glossed over in my intro to OOP class, so I never really learned about it. so, I'm not sure if I'm using terrible coding practice and just don't realize it, but I'm having a single crippling issue with my program, despite this one issue, everything appears to be running fine. This program takes strings from an argument file and executes the commands based on the instructions. However, when I issue the command "x = x + 5" I experience a crippling issue. My class titled Work creates another instance of my other class Read. When it does this, the ArrayList that I define at the top of Read is overwritten with a new instance, and thus, deletes the whole list of variables. I'm unable to find a way to make the initialization execute only once. Where am I going wrong? Work: import java.util.*; public class Work { static int Precedence(char ch){ switch (ch){ case '+': case '-': return 1; case '*': case '/': case '%': return 2; case '^': return 3; } return -1; } String infixConverter(String infix){ Variable tvar = new Variable(); //consider removing these~ Read reader = new Read(); String pfix = new String(""); Stack<Character> stack = new Stack<>(); for (int i=0; i<infix.length(); ++i) { char curr = infix.charAt(i); // if (Character.isLetterOrDigit(curr)||curr==' ') { if (Character.isDigit(curr)||curr==' ') { pfix += curr; } else if (Character.isLetter(curr)){ // Read reader = new Read(); if (reader.varExists(curr)){ // Variable tvar = new Variable(); int n = reader.getIndex(curr); tvar = reader.vars.get(n); pfix += tvar.getValue(); } else{ //error } //implement this below //check for letter within the string, if the string is } else if (curr == '('){ stack.push(curr); } else if (curr == ')'){ while (!stack.isEmpty() && stack.peek() != '(') { pfix += stack.pop(); } if (!stack.isEmpty() && stack.peek() != '(') { return "Invalid Expression"; // invalid expression } else { stack.pop(); } } else { while (!stack.isEmpty() && Precedence(curr) <= Precedence(stack.peek())) { pfix += stack.pop(); } stack.push(curr); } } while (!stack.isEmpty()) { pfix += stack.pop(); } int sol = postfixEvaluation(pfix); pfix = Integer.toString(sol); return pfix; } Integer postfixEvaluation(String pfix){ Stack<Integer> stack = new Stack<>(); for(int i = 0; i < pfix.length(); i++){ char curr = pfix.charAt(i); if(curr == ' '){ continue; } else if(Character.isDigit(curr)){ int num = 0; while(Character.isDigit(curr)){ num = num*10 + (int)(curr-'0'); i++; if (i==pfix.length()){break;} curr = pfix.charAt(i); } i--; stack.push(num); //include variables and be able to insert them into here } else{ int val1 = stack.pop(); int val2 = stack.pop(); switch(curr){ case '+': stack.push(val2+val1); break; case '-': stack.push(val2-val1); break; case '/': stack.push(val2/val1); break; case '%': stack.push(val2%val1); break; case '*': stack.push(val2*val1); break; } } } return stack.pop(); } } Read: import java.util.*; public class Read { ArrayList<Variable> vars = new ArrayList<Variable>();//FIX THIS SHIT AHHHHHHHHH Variable tempvar = new Variable(); Work eval = new Work(); private int lnNum = 1; private String arg=""; public void thing() { String thing,thing2; if (arg.contains("print")){ String real=""; int i = arg.indexOf('t'); if (i!=4){}//error thing = arg.substring(0,i); if (thing!="print"){}//error thing2 = arg.substring(i+2,arg.length()); real = eval.infixConverter(thing2); System.out.println(real); } else if (arg.contains("read")){ Scanner in = new Scanner(System.in); int i = arg.indexOf('d'); if (i!=3){}//error thing = arg.substring(0,i+1); if (thing!="read"){}//error thing2 = arg.substring(i+2,arg.length()); char c2 = thing2.charAt(0); if (thing2.length()>1){}//error System.out.println("Enter a value for "+thing2+": "); String vv = in.nextLine(); vv = eval.infixConverter(vv); int vvv = Integer.parseInt(vv); tempvar.setValue(c2, vvv); vars.add(tempvar); } else if (arg.contains("=")){ int i = arg.indexOf('='); int tempval; thing = arg.substring(0,i-1); thing2 = arg.substring(i+2,arg.length()); if(thing.length()>1){}//error thing2=eval.infixConverter(thing2); char c = thing.charAt(0); if (vars.contains(thing)){ tempval = Integer.parseInt(thing2); tempvar.setValue(c,tempval); int f = vars.indexOf(thing); } else if(Character.isLetter(c)){ tempval = Integer.parseInt(thing2); tempvar.setValue(c,tempval); vars.add(tempvar); } else{ //error } } else{ } } boolean varExists(char c){ for (int i = 0; i<vars.size(); i++){ tempvar = vars.get(i); if (tempvar.getTitle()==c){ return true; } } return false; } int getIndex(char c) { for (int i = 0; i <= vars.size(); i++) { tempvar = vars.get(i); if (tempvar.getTitle() == c) { return i; } } return -1; } int inLineNum(){ lnNum++; return lnNum; } void setArg(String c){ arg=c; } }
Java maze won't print
I have to make a maze for a java assignment, and I was able to finish most of it. I was provided with an outline of the code that had all the methods. Can someone help me? My issue is that the maze wont print out, and I can't figure out why. package maze; public class Maze { private char direction; private int r; // x position of the mouse private int c; //y position of the mouse private boolean exitFound = false; public Maze(int[][] arrMaze) { this.r = arrMaze.length - 1; this.c = 0; } //Prints out the maze without solution public void displayMaze(int[][] arrMaze) { //display the maze putting blank spaces where there are 1's in the array and putting //another symbol where there are 0's to show the maze without the solution for(int i=0; i<arrMaze.length; i++){ System.out.println(" "); for(int j=0; j<arrMaze[i].length; j++){ if(arrMaze[i][j] == 0){ System.out.print("#"); } if(arrMaze[i][j] == 1) { System.out.print(" "); } if(arrMaze[i][j] == 2){ System.out.print("#"); } if(arrMaze[i][j] == 3){ System.out.println("~"); } } } } //displays the Maze with the path taken public void displayPath(int[][] arrMaze) { //show the user how far the mouse has gone since the start. //The path the mouse has gone will be filled in but the path ahead will not. for (int i = 0; i < arrMaze.length; i++) { System.out.println(" "); for (int j = 0; j < arrMaze[i].length; j++) { if (arrMaze[i][j] == 3) { System.out.print("#"); } else if (arrMaze[i][j] == 2) { System.out.print("~"); } else if (arrMaze[i][j] == 0) { System.out.print("#"); } else { } } } } public boolean takeStep(int[][] newMaze) { // moveNorth(newMaze) for (int i = 0; i < newMaze.length; i++) { System.out.println(" "); for (int j = 0; j < newMaze[i].length; j++) { if (newMaze[r][c] == 3) { moveNorth(newMaze); System.out.print("~"); } else if (newMaze[r][c] == 2) { System.out.print("#"); } else { } } } return isAnExit(newMaze); } public void moveNorth(int[][] arrMaze) { //complete the code here /*method will check for a 0 or a 1 in the position above the current position * and then if not a 0 will change the current position to the row above it, but in the same column. */ if (arrMaze[r][c - 1] != 0) { arrMaze[r][c - 1] = 3; arrMaze[r][c + 1] = 2; } else { moveSouth(arrMaze); } displayPath(arrMaze); } public void moveSouth(int[][] arrMaze) { //method will check for a 0 or a 1 in the position below the current position and then if not a 0 //it will change the current position to the row below it, but in the same column. if (arrMaze[r][c + 1] != 0) { arrMaze[r][c + 1] = 3; arrMaze[r][c + 1] = 2; } else { moveNorth(arrMaze); } displayPath(arrMaze); } public void moveEast(int[][] arrMaze) { //method will check for a 0 or a 1 in the position to the right of  the current position and then if //not a 0 will change the current position to the column to the right but the same row. if (arrMaze[r + 1][c] != 0) { arrMaze[r + 1][c] = 3; arrMaze[r - 1][c] = 2; } else { moveWest(arrMaze); } displayPath(arrMaze); } public void moveWest(int[][] arrMaze) { //method will check for a 0 or a 1 in the position to the left of  the current position and then if //not a 0 will change the current position to the column to the left but the same row. if (arrMaze[r - 1][c] != 0) { arrMaze[r - 1][c] = 3; arrMaze[r + 1][c] = 2; } else { } displayPath(arrMaze); } private boolean isAnExit(int[][] arrMaze) { //method will return true if the user arrives into the last column of the array because there is only one //location in the last column that is a 1, so if the user reaches the array[i].length then that means that it found an exit. if (arrMaze[r][c] > arrMaze.length) { exitFound = true; } else { exitFound = false; } return exitFound; } //finds the path without stopping at every step //method will show the complete path from start to finish of the maze and the suggested route to the end. public void findExit(int[][] arrMaze) { if (arrMaze[r][c] > arrMaze.length) { for (int i = 0; i < arrMaze.length; i++) { takeStep(arrMaze); } } } } This is the test code. I was provided the test code, and I haven't changed it. package maze; import java.util.Scanner; public class TestMaze { public static void main(String[] args) { int[][] mazeArray = { {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0}, {0,0,0,1,1,1,1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,1,1,1,1,1}, {0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0}, {0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0}, {1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}}; Maze myMaze = new Maze(mazeArray); boolean keepAsking = true; Scanner scan = new Scanner(System.in); String input = ""; myMaze.displayPath(mazeArray); System.out.println("Maze"); do { System.out.println("T = Take a step | S = Show path | Q = Quit"); System.out.print("Enter command: "); input = scan.nextLine(); input.trim(); input.toLowerCase(); if(input.equals("t")) { keepAsking = !myMaze.takeStep(mazeArray); System.out.println("Which direction would you like to go? N, S, E, W?"); String direction = scan.nextLine(); if(direction.equalsIgnoreCase("n")) myMaze.moveNorth(mazeArray); if(direction.equalsIgnoreCase("s")) myMaze.moveSouth(mazeArray); if(direction.equalsIgnoreCase("e")) myMaze.moveEast(mazeArray); if(direction.equalsIgnoreCase("w")) myMaze.moveWest(mazeArray); } else if(input.equals("s")) { myMaze.findExit(mazeArray); keepAsking = false; } else if(input.equals("q")) { keepAsking = false; } else { System.out.println("ERR: Invalid input"); } } while(keepAsking); System.out.println("Quitting program..."); scan.close(); } }
You need to call displayMaze() (in displayPath()) to print it. Currently, you're not calling the method, meaning that your code will never print the maze as it's no being instructed to. Also, where are you assigning values to r and c? I think you meant to use i and j in your displayPath() method ([i][j] instead of [r][c]).
I imagine you're throwing an error somewhere because your r and c values are undefined everywhere they are used. Try adding code to initialize and update these values, then you should see your maze print.
Connect 4 right to left diagonal check
There's probably a very simple solution to this but I can't figure out where I'm doing something wrong. I'm making a small game with android studio that is connect 4. There is a 5x7 matrix of single cells, and 5 imageviews above that when clicked on put a fiche in the right place. Up to this point it's all working fine. When I however have to check if someone won, I thought I could break up the process in 4 main functions: one that check horizontally, one vertically, one diagonally left to right and one diagonally right to left. Now they all work perfectly except the right to left one. I'll post the code below: private void checkRightLeftDiagonally() { int winCondition = 0; boolean goingRight = true; int y = 1; int i = 4; int j = 0; while (y < 6 && won == false) { while (i > 0 && j < 7 && won == false) { if (cells[j][i].getFull() == true && players[playerTurn].getFicheColor() == cells[j][i].getFicheColor()) { winCondition++; winningCells.add(cells[j][i]); } else { winCondition = 0; winningCells.clear(); } if (winCondition == 4) { won = true; for (int x = 0; x < 4; x++) { winningCells.get(x).won(); } } i--; j++; } if(goingRight == true) { if(y<=4) { i=4-y; j=0; y++; } else { goingRight = false; y=0; i=0; j=0+y; } } if(goingRight == false) { i=0; j=0+y; y++; } if(won == false) { winCondition = 0; winningCells.clear(); } } if(won == false) { winCondition = 0; winningCells.clear(); } } And here is one of the arrow imageview code: imgArrows[0].setOnClickListener(new View.OnClickListener() { #Override public void onClick(View view) { if(cells[0][0].getFull() == false && won == false) { int i = 0; while(cells[i][0].getFull() == false) { i++; if(i>6) break; } i--; cells[i][0].ficheDown(players[playerTurn]); checkVertically(); checkHorizantally(); checkLeftRightDiagonally(); checkRightLeftDiagonally(); playerTurn++; if(playerTurn==2) { playerTurn = 0; } } } }); I've also made the cell class, which is here if it could help you public class Cell { private boolean full; private Player.FicheColor ficheColor; private ImageView fiche; public Cell(Player currentPlayer, ImageView img) { full = false; ficheColor = currentPlayer.getFicheColor(); fiche = img; img.setAlpha(0f); } public void ficheDown(Player currentPlayer) { full = true; ficheColor = currentPlayer.getFicheColor(); switch(ficheColor) { case red: fiche.setImageResource(R.drawable.redfiche); break; case blue: fiche.setImageResource(R.drawable.bluefiche); break; case green: fiche.setImageResource(R.drawable.greenfiche); break; case white: fiche.setImageResource(R.drawable.whitefiche); break; case black: fiche.setImageResource(R.drawable.whitefiche); break; } fiche.setAlpha(1f); } public Player.FicheColor getFicheColor() { return ficheColor; } public boolean getFull() { return full; } public void won(){ fiche.setColorFilter(Color.GREEN); } public void reset() { fiche.clearColorFilter(); } } Thank a lot, even just for reading
In the end the problem was that in the first paragraph of code the int i needed to be set to 4 and that solved it. Thanks to everyone that tried to help me
how to convert a char array back into string [duplicate]
This question already has answers here: How to convert a char array back to a string? (14 answers) Closed 9 years ago. i am doing a porter stemmer.....the code gives me output in char array....but i need to convert that into string to proceed with futher work.....in the code i have given 2 words "looking" and "walks"....that is returned as look and walk(but in char array)...the output is printed in stem() function /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package file; import java.util.Vector; /** * * #author sky */ public class stemmer { public static String line1; private char[] b; private int i, /* offset into b */ i_end, /* offset to end of stemmed word */ j, k; private static final int INC = 50; /* unit of size whereby b is increased */ public stemmer() { //b = new char[INC]; i = 0; i_end = 0; } /** * Add a character to the word being stemmed. When you are finished * adding characters, you can call stem(void) to stem the word. */ public void add(char ch) { System.out.println("in add() function"); if (i == b.length) { char[] new_b = new char[i+INC]; for (int c = 0; c < i; c++) new_b[c] = b[c]; b = new_b; } b[i++] = ch; } /** Adds wLen characters to the word being stemmed contained in a portion * of a char[] array. This is like repeated calls of add(char ch), but * faster. */ public void add(char[] w, int wLen) { if (i+wLen >= b.length) { char[] new_b = new char[i+wLen+INC]; for (int c = 0; c < i; c++) new_b[c] = b[c]; b = new_b; } for (int c = 0; c < wLen; c++) b[i++] = w[c]; } public void addstring(String s1) { b=new char[s1.length()]; for(int k=0;k<s1.length();k++) { b[k] = s1.charAt(k); System.out.println(b[k]); } i=s1.length(); } /** * After a word has been stemmed, it can be retrieved by toString(), * or a reference to the internal buffer can be retrieved by getResultBuffer * and getResultLength (which is generally more efficient.) */ public String toString() { return new String(b,0,i_end); } /** * Returns the length of the word resulting from the stemming process. */ public int getResultLength() { return i_end; } /** * Returns a reference to a character buffer containing the results of * the stemming process. You also need to consult getResultLength() * to determine the length of the result. */ public char[] getResultBuffer() { return b; } /* cons(i) is true <=> b[i] is a consonant. */ private final boolean cons(int i) { switch (b[i]) { case 'a': case 'e': case 'i': case 'o': case 'u': return false; case 'y': return (i==0) ? true : !cons(i-1); default: return true; } } /* m() measures the number of consonant sequences between 0 and j. if c is a consonant sequence and v a vowel sequence, and <..> indicates arbitrary presence, <c><v> gives 0 <c>vc<v> gives 1 <c>vcvc<v> gives 2 <c>vcvcvc<v> gives 3 .... */ private final int m() { int n = 0; int i = 0; while(true) { if (i > j) return n; if (! cons(i)) break; i++; } i++; while(true) { while(true) { if (i > j) return n; if (cons(i)) break; i++; } i++; n++; while(true) { if (i > j) return n; if (! cons(i)) break; i++; } i++; } } /* vowelinstem() is true <=> 0,...j contains a vowel */ private final boolean vowelinstem() { int i; for (i = 0; i <= j; i++) if (! cons(i)) return true; return false; } /* doublec(j) is true <=> j,(j-1) contain a double consonant. */ private final boolean doublec(int j) { if (j < 1) return false; if (b[j] != b[j-1]) return false; return cons(j); } /* cvc(i) is true <=> i-2,i-1,i has the form consonant - vowel - consonant and also if the second c is not w,x or y. this is used when trying to restore an e at the end of a short word. e.g. cav(e), lov(e), hop(e), crim(e), but snow, box, tray. */ private final boolean cvc(int i) { if (i < 2 || !cons(i) || cons(i-1) || !cons(i-2)) return false; { int ch = b[i]; if (ch == 'w' || ch == 'x' || ch == 'y') return false; } return true; } private final boolean ends(String s) { int l = s.length(); int o = k-l+1; if (o < 0) return false; for (int i = 0; i < l; i++) if (b[o+i] != s.charAt(i)) return false; j = k-l; return true; } /* setto(s) sets (j+1),...k to the characters in the string s, readjusting k. */ private final void setto(String s) { int l = s.length(); int o = j+1; for (int i = 0; i < l; i++) b[o+i] = s.charAt(i); k = j+l; } /* r(s) is used further down. */ private final void r(String s) { if (m() > 0) setto(s); } /* step1() gets rid of plurals and -ed or -ing. e.g. caresses -> caress ponies -> poni ties -> ti caress -> caress cats -> cat feed -> feed agreed -> agree disabled -> disable matting -> mat mating -> mate meeting -> meet milling -> mill messing -> mess meetings -> meet */ private final void step1() { if (b[k] == 's') { if (ends("sses")) k -= 2; else if (ends("ies")) setto("i"); else if (b[k-1] != 's') k--; } if (ends("eed")) { if (m() > 0) k--; } else if ((ends("ed") || ends("ing")) && vowelinstem()) { k = j; if (ends("at")) setto("ate"); else if (ends("bl")) setto("ble"); else if (ends("iz")) setto("ize"); else if (doublec(k)) { k--; { int ch = b[k]; if (ch == 'l' || ch == 's' || ch == 'z') k++; } } else if (m() == 1 && cvc(k)) setto("e"); } } /* step2() turns terminal y to i when there is another vowel in the stem. */ private final void step2() { if (ends("y") && vowelinstem()) b[k] = 'i'; } /* step3() maps double suffices to single ones. so -ization ( = -ize plus -ation) maps to -ize etc. note that the string before the suffix must give m() > 0. */ private final void step3() { if (k == 0) return; /* For Bug 1 */ switch (b[k-1]) { case 'a': if (ends("ational")) { r("ate"); break; } if (ends("tional")) { r("tion"); break; } break; case 'c': if (ends("enci")) { r("ence"); break; } if (ends("anci")) { r("ance"); break; } break; case 'e': if (ends("izer")) { r("ize"); break; } break; case 'l': if (ends("bli")) { r("ble"); break; } if (ends("alli")) { r("al"); break; } if (ends("entli")) { r("ent"); break; } if (ends("eli")) { r("e"); break; } if (ends("ousli")) { r("ous"); break; } break; case 'o': if (ends("ization")) { r("ize"); break; } if (ends("ation")) { r("ate"); break; } if (ends("ator")) { r("ate"); break; } break; case 's': if (ends("alism")) { r("al"); break; } if (ends("iveness")) { r("ive"); break; } if (ends("fulness")) { r("ful"); break; } if (ends("ousness")) { r("ous"); break; } break; case 't': if (ends("aliti")) { r("al"); break; } if (ends("iviti")) { r("ive"); break; } if (ends("biliti")) { r("ble"); break; } break; case 'g': if (ends("logi")) { r("log"); break; } } } /* step4() deals with -ic-, -full, -ness etc. similar strategy to step3. */ private final void step4() { switch (b[k]) { case 'e': if (ends("icate")) { r("ic"); break; } if (ends("ative")) { r(""); break; } if (ends("alize")) { r("al"); break; } break; case 'i': if (ends("iciti")) { r("ic"); break; } break; case 'l': if (ends("ical")) { r("ic"); break; } if (ends("ful")) { r(""); break; } break; case 's': if (ends("ness")) { r(""); break; } break; } } /* step5() takes off -ant, -ence etc., in context <c>vcvc<v>. */ private final void step5() { if (k == 0) return; /* for Bug 1 */ switch (b[k-1]) { case 'a': if (ends("al")) break; return; case 'c': if (ends("ance")) break; if (ends("ence")) break; return; case 'e': if (ends("er")) break; return; case 'i': if (ends("ic")) break; return; case 'l': if (ends("able")) break; if (ends("ible")) break; return; case 'n': if (ends("ant")) break; if (ends("ement")) break; if (ends("ment")) break; /* element etc. not stripped before the m */ if (ends("ent")) break; return; case 'o': if (ends("ion") && j >= 0 && (b[j] == 's' || b[j] == 't')) break; /* j >= 0 fixes Bug 2 */ if (ends("ou")) break; return; /* takes care of -ous */ case 's': if (ends("ism")) break; return; case 't': if (ends("ate")) break; if (ends("iti")) break; return; case 'u': if (ends("ous")) break; return; case 'v': if (ends("ive")) break; return; case 'z': if (ends("ize")) break; return; default: return; } if (m() > 1) k = j; } /* step6() removes a final -e if m() > 1. */ private final void step6() { j = k; if (b[k] == 'e') { int a = m(); if (a > 1 || a == 1 && !cvc(k-1)) k--; } if (b[k] == 'l' && doublec(k) && m() > 1) k--; } /** Stem the word placed into the Stemmer buffer through calls to add(). * Returns true if the stemming process resulted in a word different * from the input. You can retrieve the result with * getResultLength()/getResultBuffer() or toString(). */ public void stem() { // step1(); // System.out.println("hello in stem"); // step2(); // step3(); // step4(); // step5(); // step6(); // // i_end = k+1; // i = 0; System.out.println(i); k = i - 1; if (k > 1) { step1(); step2(); step3(); step4(); step5(); step6(); } for(int c=0;c<=k;c++) System.out.println(b[c]); i_end = k+1; i = 0; } public static void main(String[] args) { stemmer s = new stemmer(); s.addstring("looking"); s.stem(); s.addstring("walks"); s.stem(); //System.out.println("Output " +s.b); } }
- Use Character class method toString(); Eg: class Test { public static void main (String[] args) throws java.lang.Exception { char c = 'a'; String s = Character.toString(c); System.out.println(s); } } - Now use this above explained method to convert all the character array items into String.
char[] data = new char[10]; String text = String.valueOf(data);
to convert a char[] to string use this way String x=new String(char[]) example char x[]={'a','m'}; String z=new String(x); System.out.println(z); output am
char[] a = new char[10]; for(int i=0;i<10;i++) { a[i] = 's'; } System.out.println(new String(a)); or System.out.println(String.copyValueOf(a));