Reverse rubik's cube algorithm - java

I have been all day strugglingh through this simple function, but i can't get it working as I would like to. It may seem simple at first, and there is indeed another entry in Stack Overflow which talks about it. However, things get messy when brackets are introduced.
Let's say we can get an algorithm for a Rubiks cube which will look something like
(R U R' U) U' (R U' R')
It is important to note that after every move, whether it has a "'" or not, there is a space, except for those before the end brackets.
Now, for every algorithm on a Rubik's cube there exists its inverse, the one which undoes it. For example, the inverse of R is R' and of U is U, and the inverse of R U is U' R'. Thus, the inverse of the example is:
(R U R') U (U' R U' R')
It is also important to nothe that there are many moves (F, B, D, U, u, f, M, S, x, y, z...)
Also every alg has its own inverse (R has R' and vice versa,
Can you get any function in Java for that?
I have tried infinite loops of ifelse, for, switch...
I will leave some of my tries just for reference
String fullAlg = text.toString() + " ";
String reversedAlg = "hh";
int numSpaces = 1;
int pos1 = 0, pos2 = 0;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == ' ' && numSpaces == 0) {
numSpaces++;
pos1 = i;
}
if (text.charAt(i) == ' ' && numSpaces == 1) {
numSpaces++;
pos2 = i;
}
if (numSpaces == 2) {
if (fullAlg.substring(pos1, pos2).matches("[a-zA-Z]+")){
Toast.makeText(this, "YES", Toast.LENGTH_SHORT).show();
}
switch (fullAlg.substring(pos1, pos2)) {
//Begin with (
case "(" + "[a-zA-Z]+":
reversedAlg += ")'" + fullAlg.substring(pos1, pos2).charAt(1);
break;
case "(" + "[a-zA-Z]+" + "\'":
reversedAlg += ")" + fullAlg.substring(pos1, pos2).charAt(1);
break;
case "(" + "[a-zA-Z]+" + "2":
reversedAlg += ")2" + fullAlg.substring(pos1, pos2).charAt(1);
break;
//No ()
case "[a-zA-Z]+":
reversedAlg += " '" + fullAlg.substring(pos1, pos2).charAt(0);
break;
case "[a-zA-Z]+" + "\'":
reversedAlg += " '" + fullAlg.substring(pos1, pos2).charAt(0);
break;
case "[a-zA-Z]+" + "2":
reversedAlg += " 2" + fullAlg.substring(pos1, pos2).charAt(0);
break;
//End with )
case "[a-zA-Z]+" + ")":
reversedAlg += " '" + fullAlg.substring(pos1, pos2).charAt(1) + "(";
break;
case "[a-zA-Z]+" + "\'" + ")":
reversedAlg += " " + fullAlg.substring(pos1, pos2).charAt(1) + "(";
break;
case "[a-zA-Z]+" + "2" + ")":
reversedAlg += " )2" + fullAlg.substring(pos1, pos2).charAt(1) + "(";
break;
//Encapsulated in ()
case "(" + "[a-zA-Z]+" + ")":
reversedAlg += " )'" + fullAlg.substring(pos1, pos2).charAt(1) + "(";
break;
case "(" + "[a-zA-Z]+" + "\'" + ")":
reversedAlg += " )" + fullAlg.substring(pos1, pos2).charAt(1) + "(";
break;
case "(" + "[a-zA-Z]+" + "2" + ")":
reversedAlg += " )2" + fullAlg.substring(pos1, pos2).charAt(1) + "(";
break;
}
numSpaces = 0;
}
}
StringBuilder returnAlg = new StringBuilder(reversedAlg).reverse();
algTV.setText(fullAlg.substring(pos1, pos2));
}
Or this one
String fullAlg = text.toString();
String fullAldReversed = "";
int posStart = 0, posEnd = 0;
for (int i = 0; i < fullAlg.length(); i++) {
if (fullAlg.charAt(i) == '('){
posStart = i;
} else if (fullAlg.charAt(i) == ')'){
posEnd = i;
fullAldReversed += "(" + reverseAlg(fullAlg.substring(posStart, posEnd)) + ")";
posStart = 0;
}
}
if (posEnd == 0){
fullAldReversed = "" + reverseAlg(fullAlg);
}
algTV.setText(fullAldReversed);
}
private StringBuilder reverseAlg(CharSequence text) {
StringBuilder builder;
if (!(text.charAt(0) == ' ' || text.charAt(text.length() - 1) == ' ')) {
builder = new StringBuilder(text + " ");
} else {
builder = new StringBuilder(text);
}
int subStart = 0;
StringBuilder auxBuilder;
String substring = "", auxString = "";
for (int i = 0; i < builder.length(); i++) {
substring = "";
int subEnd = i;
int identifierMove = 0;
for (int j = subStart; j <= subEnd; j++) {
if (builder.charAt(j) == '\'')
identifierMove = 1;
else if (builder.charAt(j) == '2')
identifierMove = 2;
else if (identifierMove == 0)
identifierMove = 3;
}
String letterMove;
switch (identifierMove) {
case 1:
letterMove = builder.substring(subStart, subEnd - 1);
subStart = subEnd + 1;
substring = " " + letterMove;
break;
case 2:
letterMove = builder.substring(subStart, subEnd - 1);
subStart = subEnd + 1;
substring = " 2" + letterMove;
break;
case 3:
letterMove = builder.substring(subStart, subEnd);
subStart = subEnd + 1;
substring = " '" + letterMove;
break;
}
auxString += substring;
}
auxBuilder = new StringBuilder(auxString);
auxBuilder.reverse().toString();
return auxBuilder;
}
Thank you!!

Sorry for the delay! Your attempts are quite overcomplicated in my opinion. I thought it was the best choice to make a class to represent the Rubix cube algorithm because it's a bit complicated and the class will also leave room for further expansion. Anyways, the way it works is simple. The class constructor takes a string as an input and converts the text into integers for easier storage and manipulation. From here, reversing the algorithm is super simple! All you have to do is reverse the order of the array and multiply all the integers by -1! (Their opposites i.e. R' are stored as negatives.) Then, if you want to output it as a string, you may use the toStrng() function to display the Algorithm.
import java.util.ArrayList;
import java.util.Arrays;
class RubixAlg {
//We will store our list of moves as integers. (And also parentheses) Any X' is the negative value of X
//For example, U corresponds to 2, and U' corresponds to -2.
ArrayList<Integer> moves = new ArrayList<Integer>();
RubixAlg(String input){
String input1 = input+" ";//Adding a space to the end prevents the algorithm from breaking when it checks for an apostrophe where no text exists.
while(input1.length()>0){
println(input1.charAt(0));
//This part figures out what character is the first in the string, what move that corresponds to, and then deletes it until there's no more characters.
switch(input1.charAt(0)){
case ' ':
input1=input1.substring(1);
break;
case '(':
moves.add(1);
input1=input1.substring(1);
break;
case ')':
moves.add(-1);
input1=input1.substring(1);
break;
case 'U':
if(input1.charAt(1)=='\''){
moves.add(-2);
input1=input1.substring(2);
} else {
moves.add(2);
input1=input1.substring(1);
}
break;
case 'D':
if(input1.charAt(1)=='\''){
moves.add(-3);
input1=input1.substring(2);
} else {
moves.add(3);
input1=input1.substring(1);
}
break;
case 'F':
if(input1.charAt(1)=='\''){
moves.add(-4);
input1=input1.substring(2);
} else {
moves.add(4);
input1=input1.substring(1);
}
break;
case 'B':
if(input1.charAt(1)=='\''){
moves.add(-5);
input1=input1.substring(2);
} else {
moves.add(5);
input1=input1.substring(1);
}
break;
case 'R':
if(input1.charAt(1)=='\''){
moves.add(-6);
input1=input1.substring(2);
} else {
moves.add(6);
input1=input1.substring(1);
}
break;
case 'L':
if(input1.charAt(1)=='\''){
moves.add(-7);
input1=input1.substring(2);
} else {
moves.add(7);
input1=input1.substring(1);
}
break;
default:
input1=input1.substring(1);
break;
}
}
}
String toStrng(){
String output = "";
for(int i=0;i<moves.size();i++){
//println(moves.get(i));
int move = moves.get(i);
switch(move){
case 1:
output+="(";
break;
case -1:
output=output.substring(0,output.length()-1);
output+=")";
break;
case 2:
output+="U ";
break;
case -2:
output+="U\' ";
break;
case 3:
output+="D ";
break;
case -3:
output+="D\' ";
break;
case 4:
output+="F ";
break;
case -4:
output+="F\' ";
break;
case 5:
output+="B ";
break;
case -5:
output+="B\' ";
break;
case 6:
output+="R ";
break;
case -6:
output+="R\' ";
break;
case 7:
output+="L ";
break;
case -7:
output+="L\' ";
break;
default:
break;
}
}
return output;
}
void revers(){
//What this algorithm does is pretty simple. It changes the direction by multiplying all of the stored integers by -1, and then reversing their order.
Integer[] intermediate = new Integer[moves.size()];
intermediate=moves.toArray(new Integer[0]);
intermediate=ReverseNegArray(intermediate);
for(int i=0;i<intermediate.length;i++){
moves.set(i,intermediate[i]);
}
}
}
Integer[] ReverseNegArray(Integer[] x){
Integer[] y = new Integer[x.length];
for(int i = 1;i<=x.length;i++){
println(-x[x.length-i]);
y[i-1]=-x[x.length-i];
}
return y;
}

I have a partial solution, that will be complete if you can convert your String representation into an Algorithm object. This represents a Rubik's cube algorithm as a sequence of individual moves, and other nested algorithms, where each move has a side and a direction (i.e. whether it is inverted or not).
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
public class Rubiks
{
public static void main(String[] args)
{
// (R U R' U) U' (R U' R')
Instruction g1 = new Algorithm(Move.fore('R'), Move.fore('U'), Move.back('R'), Move.back('U'));
Instruction g2 = new Algorithm(Move.fore('R'), Move.back('U'), Move.back('R'));
Instruction full = new Algorithm(g1, Move.back('U'), g2);
System.out.println("This algorithm: " + full);
System.out.println("Inverts to be: " + full.inverted());
}
}
class Move implements Instruction
{
private final char side;
private final boolean inverse;
private Move(final char side, final boolean inverse)
{
this.side = side;
this.inverse = inverse;
}
public static Move fore(final char side)
{
return new Move(side, false);
}
public static Move back(final char side)
{
return new Move(side, true);
}
public Move inverted()
{
return new Move(side, !inverse);
}
#Override
public String toString()
{
return side + (inverse ? "'" : "");
}
#Override
public String toSubString()
{
return toString();
}
}
class Algorithm implements Instruction
{
private final Deque<Instruction> moves;
private Algorithm(Deque<Instruction> moves)
{
this.moves = moves;
}
public Algorithm(Instruction... moves)
{
this.moves = new ArrayDeque<>(Arrays.asList(moves));
}
public Algorithm inverted()
{
Deque<Instruction> newMoves = new ArrayDeque<>(moves.size());
for (Instruction instruction : (Iterable<Instruction>) moves::descendingIterator)
{
newMoves.add(instruction.inverted());
}
return new Algorithm(newMoves);
}
#Override
public String toString()
{
StringBuilder sb = new StringBuilder();
boolean first = true;
for (Instruction instruction : moves)
{
if(! first)
{
sb.append(' ');
}
first = false;
sb.append(instruction.toSubString());
}
return sb.toString();
}
}
interface Instruction
{
/**
* Returns the inverse of this instruction
* #return an instruction that undoes this instruction
*/
Instruction inverted();
/**
* Returns the string representation of the instruction, if it were nested in another instruction
* #return the result of toString, with parentheses if this is a complex instruction
*/
default String toSubString()
{
return "(" + toString() + ")";
}
}
I've used the Rubiks class to demonstrate that it works on the initial example you provided. It outputs the following:
This algorithm: (R U R' U') U' (R U' R')
Inverts to be: (R U R') U (U R U' R')
However I realise this answer may require you to implement more complicated logic to convert to this form if you are required to start out with a string representation of your algorithm, as parsing is not a trivial task.

After I read some answers I came up with this. Hope anyone who has the same question can get positive feedback. Thanks to everyone who tried to help me!
private void reverseAlg(CharSequence text) {
StringBuilder fullAlg;
if (!(text.charAt(0) == ' ' || text.charAt(text.length() - 1) == ' ')) {
fullAlg = new StringBuilder(text + " ");
} else {
fullAlg = new StringBuilder(text);
}
StringBuilder reversedAlg = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
if (fullAlg.charAt(i) != '(' && fullAlg.charAt(i) != ')' && fullAlg.charAt(i) != ' '
&& fullAlg.charAt(i) != '\'' && fullAlg.charAt(i) != '2') {
if (fullAlg.charAt(i + 1) == '\'') {
if (fullAlg.charAt(i + 2) == ')') {
reversedAlg.append(fullAlg.charAt(i)).append(")");
} else {
reversedAlg.append(fullAlg.charAt(i));
}
} else if (fullAlg.charAt(i + 1) == ' ') {
reversedAlg.append("\'").append(fullAlg.charAt(i));
} else if (fullAlg.charAt(i + 1) == '2') {
if (fullAlg.charAt(i + 2) == ')') {
reversedAlg.append("2").append(fullAlg.charAt(i)).append(")");
} else {
reversedAlg.append("2").append(fullAlg.charAt(i));
}
} else if (fullAlg.charAt(i + 1) == ')') {
reversedAlg.append("\'").append(fullAlg.charAt(i)).append(")");
}
} else if (fullAlg.charAt(i) == ' ' || fullAlg.charAt(i) == '(') {
reversedAlg.append(fullAlg.charAt(i));
}
}
StringBuilder aux = new StringBuilder(reversedAlg.toString()).reverse();
for (int i = 0; i < aux.length(); i++) {
if (aux.charAt(i) == '(') {
aux.setCharAt(i, ')');
} else if (aux.charAt(i) == ')') {
aux.setCharAt(i, '(');
}
}
algTV.setText(aux);
}

Related

Printing out the line number a Char was found on in a String

i'm writing a program to scan for mathematical operators in a given string, when the program finds a match, i want to return the operator and the line that it was found on, below is my attempt.
public class Testing {
public enum TokenType {
OP_MULTIPLY,
OP_DIVIDE,
OP_MOD,
OP_ADD,
OP_SUBTRACT,
OP_LESS,
OP_LESSEQUAL,
OP_GREATER,
OP_GREATEREQUAL,
OP_EQUAL,
OP_NOTEQUAL,
OP_NOT,
OP_ASSIGN,
OP_AND,
OP_OR,
OP_DOT
}
public static String inputString = "public class HelloWorld {\n"
+ " public static void-*//-- main(String[] args) {\n" + " // to print out+8+*+ hello world\n"
+ " System.out.println(\"Hello World!\");\n" + " }\n" + "}\n";
public static void lineNumber(String lineNumber) {
int count = 1;
String[] lines = inputString.split("\\r?\\n");
for (String line : lines) {
System.out.println("line " + count++);
}
int n = inputString.length();
for (int i = 0; i < n; i++) {
char ch = inputString.charAt(i);
getOP(ch);
}
}
public static TokenType getOP(char ch) {
switch (ch) {
case '+':
System.out.println(TokenType.OP_ADD + ", " + ch);
return TokenType.OP_ADD;
case '-':
System.out.println(TokenType.OP_SUBTRACT + ", " + ch);
return TokenType.OP_SUBTRACT;
case '/':
System.out.println(TokenType.OP_DIVIDE + ", " + ch);
return TokenType.OP_DIVIDE;
case '*':
System.out.println(TokenType.OP_MULTIPLY + ", " + ch);
return TokenType.OP_MULTIPLY;
}
return null;
}
public static void main(String[] args) {
lineNumber(inputString);
}
}
This is my current output:
line 1
line 2
line 3
line 4
line 5
line 6
OP_SUBTRACT, -
OP_MULTIPLY, *
OP_DIVIDE, /
OP_DIVIDE, /
OP_SUBTRACT, -
OP_SUBTRACT, -
OP_DIVIDE, /
OP_DIVIDE, /
OP_ADD, +
OP_ADD, +
OP_MULTIPLY, *
OP_ADD, +
What im trying to achieve:
Line 1: OP_ADD, +
Line 3: OP_MULTIPLY, *
etc.
Thanks
Your code might look as follows:
public class Testing {
enum TokenType {
OP_MULTIPLY,
OP_DIVIDE,
OP_MOD,
OP_ADD,
OP_SUBTRACT,
OP_LESS,
OP_LESSEQUAL,
OP_GREATER,
OP_GREATEREQUAL,
OP_EQUAL,
OP_NOTEQUAL,
OP_NOT,
OP_ASSIGN,
OP_AND,
OP_OR,
OP_DOT
}
public static void main(String[] args) {
lineNumber();
}
public static final String inputString = "public class HelloWorld {\n" +
" public static void-*//-- main(String[] args) {\n" +
" // to print out+8+*+ hello world\n" +
" System.out.println(\"Hello World!\");\n" +
" }\n" +
"}\n";
private static void lineNumber() {
String[] lines = inputString.split("\\r?\\n");
for (int i = 0; i < lines.length; i++) {
String line = lines[i];
for (int j = 0; j < line.length(); j++) {
TokenType tokenType = getOP(line.charAt(j));
if (tokenType != null) {
System.out.printf("Line %d: %s, %s\n", i + 1, tokenType.name(), line.charAt(j));
}
}
}
}
private static TokenType getOP(char ch) {
switch (ch) {
case '+':
return TokenType.OP_ADD;
case '-':
return TokenType.OP_SUBTRACT;
case '/':
return TokenType.OP_DIVIDE;
case '*':
return TokenType.OP_MULTIPLY;
// more
}
return null;
}
}
Nested loop allows for keeping current line index.
Also, your getOP method should be responsible only for determining a math operation based on the character value. It shouldn't print anything, it's a responsibility of the lineNumber.
Output:
Line 2: OP_SUBTRACT, -
Line 2: OP_MULTIPLY, *
Line 2: OP_DIVIDE, /
Line 2: OP_DIVIDE, /
Line 2: OP_SUBTRACT, -
Line 2: OP_SUBTRACT, -
Line 3: OP_DIVIDE, /
Line 3: OP_DIVIDE, /
Line 3: OP_ADD, +
Line 3: OP_ADD, +
Line 3: OP_MULTIPLY, *
Line 3: OP_ADD, +
You should do your operation checking for each separate line, instead of doing it on the whole input at once.
public static void lineNumber (String inputString)
{
int count = 1;
String[] lines = inputString.split("\\r?\\n");
for (String line : lines) {
System.out.println("line " + count++);
int n = line.length();
for (int i = 0; i < n; i++)
{
char ch = line.charAt(i);
getOP(ch);
}
}
}
So the key was to get the line numbering inside the same loop as the symbol printing. I also added some complexity to avoid printing line numbers with nothing on them.
public class Testing {
public enum TokenType {
OP_MULTIPLY,
OP_DIVIDE,
OP_MOD,
OP_ADD,
OP_SUBTRACT,
OP_LESS,
OP_LESSEQUAL,
OP_GREATER,
OP_GREATEREQUAL,
OP_EQUAL,
OP_NOTEQUAL,
OP_NOT,
OP_ASSIGN,
OP_AND,
OP_OR,
OP_DOT
}
public static String inputString = "public class HelloWorld {\n" +
" public static void-*//-- main(String[] args) {\n" +
" // to print out+8+*+ hello world\n" +
" System.out.println(\"Hello World!\");\n" +
" }\n" +
"}\n";
public static void lineNumber(String lineNumber) {
int count = 0;
String[] lines = inputString.split("\\r?\\n");
for (String line: lines) {
count++;
int n = line.length();
boolean first = true;
for (int i = 0; i < n; i++) {
char ch = line.charAt(i);
if (getOP(ch, first, count) != null) {
first = false;
}
}
System.out.println();
}
}
public static TokenType getOP(char ch, boolean firstOnLine, int lineNum) {
if (firstOnLine && (ch == '+' || ch == '-' || ch == '/' || ch == '*')) {
System.out.print("line " + lineNum + " ");
}
switch (ch) {
case '+':
System.out.println(TokenType.OP_ADD + ", " + ch);
return TokenType.OP_ADD;
case '-':
System.out.println(TokenType.OP_SUBTRACT + ", " + ch);
return TokenType.OP_SUBTRACT;
case '/':
System.out.println(TokenType.OP_DIVIDE + ", " + ch);
return TokenType.OP_DIVIDE;
case '*':
System.out.println(TokenType.OP_MULTIPLY + ", " + ch);
return TokenType.OP_MULTIPLY;
}
return null;
}
public static void main(String[] args) {
lineNumber(inputString);
}
}

How to detect whitespace of operator

I have some problem about my code.
I want to detect whitespace of operator like " + ", " +", "+ " or "+".
I want my output is
Whitespace of an operator is "A"
How can I modify my code?
My code is here.
Scanner input = new Scanner (new File(PATH to file));
int plus1;
int plus2;
int plus3;
int plus4;
String sPlus = "";
while (in.hasNext()) {
String line = in.nextLine();
in.hasNextLine();
LOC++;
if (line.length() > 0) {
plus1 = -1;
plus2 = -1;
plus3 = -1;
plus4 = -1;
while (true) {
plus1 = line.indexOf(" + ", plus1 + 1);
plus2 = line.indexOf(" +", plus2 + 1);
plus3 = line.indexOf("+ ", plus3 + 1);
plus4 = line.indexOf("+", plus4 + 1);
if (plus1 > 0) {
sPlus = "A";
}
if (plus2 > 0) {
sPlus = "B";
}
if (plus3 > 0) {
sPlus = "C";
}
if(plus4 > 0){
sPlus = "D";
}
if ((plus1 < 0) || (plus2 < 0) || (plus3 < 0) || (plus4 < 0)) break;
}
}
}
There are two problems with your logic:
You are using trim() in line.indexOf(" +".trim(), plus2+1), which returns the index of "+" NOT " +"
Any one occurrence of " + " will be counted 4 times, because line.indexOf(" +") will also count occurrences of " + "
For 2. it would be much easier to use line.indexOf('+'), and then check before and after the index to see how many whitespaces there are:
int plus = line.indexOf('+');
if(plus == -1) break;
if(line.charAt(plus-1) == ' ') {
if(line.charAt(plus+1) == ' ') //A;
else //B;
}
else if(line.charAt(plus+1) == ' ') {
//C
}
else {
//D
}
Proper else-if could be help.
if (line.indexOf(" + ") != -1) sPlus = "A";
else if (line.indexOf(" +") != -1) sPlus = "B";
else if (line.indexOf("+ ") != -1) sPlus = "C";
else if (line.indexOf("+") != -1) sPlus = "D";
else break;

Java: Number of specific character reports

I've made a program to count the number of each letters in a phrase
What I want the resulting text to return is
Enter a phrase
"Cow goes to the market"
There are 1 C('s), 3 O('s), 1 W('s), 1 G('s), 3 E('s), 1 S('s), 3 T('s).. /* you get the gist */ in your phrase.
I want the results to be concatenated into a string instead of just a multi-lined report.
import java.util.*;
public class charCount
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner (System.in);
//Prompt for user entry
System.out.println("Enter a phrase: ");
String letterN = keyboard.nextLine();
charCount(letterN);
}
public static int charCount(String letterN)
{ //variable initializations
int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z;
a = b = c = d = e = f = g = h = i = j = k = l = m = n = o = p = q = r = s = t = u = v = w = x = y = z = 0;
int total = 0;
total += 1;
//for loop
for(int countN = 0; countN < letterN.length(); countN++) {
switch(letterN.charAt(countN)) {
case 'a':
a++;
break;
case 'b':
b++;
break;
case 'c':
c++;
break;
case 'd':
d++;
break;
case 'e':
e++;
break;
case 'f':
f++;
break;
case 'g':
g++;
break;
case 'h':
h++;
break;
case 'i':
i++;
break;
case 'j':
j++;
break;
case 'k':
k++;
break;
case 'l':
l++;
break;
case 'm':
m++;
break;
case 'n':
n++;
break;
case 'o':
o++;
break;
case 'p':
p++;
break;
case 'q':
q++;
break;
case 'r':
r++;
break;
case 's':
s++;
break;
case 't':
t++;
break;
case 'u':
u++;
break;
case 'v':
v++;
break;
case 'w':
w++;
break;
case 'x':
x++;
break;
case 'y':
y++;
break;
case 'z':
z++;
break;
}
}
//Console logs
System.out.println("Below are the individual character counts for your string");
System.out.println("A: " + a);
System.out.println("B: " + b);
System.out.println("C: " + c);
System.out.println("D: " + d);
System.out.println("E: " + e);
System.out.println("F: " + f);
System.out.println("G: " + g);
System.out.println("H: " + h);
System.out.println("I: " + i);
System.out.println("J: " + j);
System.out.println("K: " + k);
System.out.println("L: " + l);
System.out.println("M: " + m);
System.out.println("N: " + n);
System.out.println("O: " + o);
System.out.println("P: " + p);
System.out.println("Q: " + q);
System.out.println("R: " + r);
System.out.println("S: " + s);
System.out.println("T: " + t);
System.out.println("U: " + u);
System.out.println("V: " + v);
System.out.println("W: " + w);
System.out.println("X: " + x);
System.out.println("Y: " + y);
System.out.println("Z: " + z);
return total;
}
}
My problem is, I can of course concatenate a System.out.println(); with the int vars but it simply prints the number of letters. I don't know ahead of time what people will type so I need my program to detect if the letter = true and thus returns the character and number inside the report.
I've looked for solutions and cannot find a thing. I can't wrap my mind around this yet and frankly I have no idea how to word this inquiry.
Thank you guys ahead of time
Use a Map to store the characters you have encountered, and how many times they are seen. Using TreeMap will mean that when you iterate over the map the entries are sorted in natural order
import java.util.*;
public class CharCount {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
//Prompt for user entry
System.out.println("Enter a phrase: ");
String letterN = keyboard.nextLine();
charCount(letterN);
}
public static void charCount(String letterN) {
Map<Character, Long> charMap = new TreeMap<>();
for (char aChar : letterN.toCharArray()) {
if (charMap.containsKey(aChar)) {
charMap.put(aChar, charMap.get(aChar) + 1);
}
else {
charMap.put(aChar, 1L);
}
// this if/else can be written using the ternary operator as:
// charMap.put(aChar, charMap.containsKey(aChar) ? charMap.get(aChar) + 1 : 1L);
}
for (Character character : charMap.keySet()) {
System.out.println(character + ": " + charMap.get(character));
}
}
}

Java code prints right but returns wrong

The following code:
public class NewClass1 {
public static String mus = "";
public static String musCal(String[] signal, int[] time) {
int i = 0;
while (i < signal.length) {
switch (signal[i]) {
case "x": {
// System.out.print("x = ");
mus = mus + "x";
int sum = time[i];
if (signal[i + 1] == "C") {
i++;
while (i < signal.length && signal[i] == "C") {
sum += time[i];
i++;
}
} else
i++;
// System.out.print(sum + " ");
mus = sum + " ";
break;
}
case "y": {
// System.out.print("y = ");
mus = mus + "y ";
int sum = time[i];
if (signal[i + 1] == "C") {
i++;
while (i < signal.length && signal[i] == "C") {
sum += time[i];
i++;
}
} else
i++;
// System.out.print(sum + " ");
mus = sum + " ";
break;
}
case "z": {
// System.out.print("z = ");
mus = mus + "z ";
int sum = time[i];
if (signal[i + 1] == "C") {
i++;
while (i < signal.length && signal[i] == "C") {
sum += time[i];
i++;
}
} else
i++;
// System.out.print(sum + " ");
mus = sum + " ";
break;
}
}
}
return mus;
}
public static void main(String[] args) {
String signal[] = { "x", "y", "y", "C", "C", "z", "C", "C", "x", "C" };
int time[] = { 2, 5, 1, 4, 7, 8, 2, 6, 4, 3 };
musCal(signal, time);
System.out.print(mus);
}
}
The expected output from the code is:
x=2 y=5 y=12 z=16 x=7
If the comments signs // are removed to activate the System.out.print statements, the code gives the expected output. But when I was trying to collect this output in the form of 'String mus', as shown in the code, I got only the last element of the output string i.e. 7. Being new comer to java and programming, I need your help. Kindly help me to correct the return statement so that I may get the right output as String 'mus' by concatenating, or by any other suitable method.
you can also use this solution for :
replace mus=sum + " ";
with mus += sum + " ";
You overwrite mus at several places using
mus=sum + " ";
instead of concatenating it like
mus = mus + sum + " "
Also, you don't always use brackets for if and else, which is very bad code style and I condemn the Java inventors for making brackets optional if one only wants to execute a single line.

While loop wont repeat itself

I need to let the user input an operand, input 2 integers, display the result, and repeat. It wont repeat and when you input an integer to continue, it terminates. Any help would be appreciated, Ive been stuck for a while now! Thanks.
package lab03;
import java.util.Scanner;
import javax.swing.JOptionPane;
/**
*
*/
public class Lab03 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int n, p, q = 1;
boolean run = true;
String operator;
while (run == true) {
operator = JOptionPane.showInputDialog("Enter one of + - * / ");
String trimOperator = operator.trim();
char m = trimOperator.charAt(0);
String firstOperand = JOptionPane
.showInputDialog("Enter first integer operand: ");
n = Integer.parseInt(firstOperand);
String secondOperand = JOptionPane
.showInputDialog("Enter second integer operand: ");
p = Integer.parseInt(secondOperand);
switch (m) {
case '+':
System.out.println(n + " plus " + p + " is " + (n + p));
run = false;
break;
case '-':
System.out.println(n + " minus " + p + " is " + (n - p));
run = false;
break;
case '*':
System.out
.println(n + " multiplied by " + p + " is " + (n * p));
run = false;
break;
case '/':
System.out.println(n + " divided by " + p + " is " + (n / p)
+ " with remainder " + (n % p));
run = false;
break;
default:
System.out.println("Invalid character");
run = false;
break;
}
String lastInteger = JOptionPane
.showInputDialog("Enter 0 to quit, or any other integer to continue. ");
q = Integer.parseInt(lastInteger);
System.out.println(q);
System.exit(0);
continue;
}
}
Sorry for lack of comments.

Categories