Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am new to android developement.
Created calculator application.
Want to improve my code quality.
Will be helpfull for any advice to make the code better and more professional
(overall structure, splitting onto logical units, accordance to code conventions, methods and variables names, comments etc).
Here is my code:
public class OperationsAndFunctions {
static enum OperEnum {
SUM, SUBSTRACT, MULTIPLY, DIVIDE, EQUAL
}
static enum FuncEnum {
RESET, BACKSPACE, SIGN, PERCENT, POINT
}
}
public class LCalculator extends Activity {
private TextView mDisplay;
private boolean mDisplayIsEmpty = true;
private boolean mFirstNumberReceived;
private boolean mNumberEntered;
private boolean mPointEntered;
private double sNum1;
private double sNum2;
private static OperationsAndFunctions.OperEnum sOperation;
private static OperationsAndFunctions.FuncEnum sFunction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
mDisplay = (TextView) findViewById(R.id.tvDisplay);
mDisplay.setText("0");
}
// listening for number buttons pressing
public void num_Clicked(View view) {
Button button = (Button) view;
int number = 0;
// checking button ID
switch (button.getId()) {
case R.id.button1:
number = 1;
break;
case R.id.button2:
number = 2;
break;
case R.id.button3:
number = 3;
break;
case R.id.button4:
number = 4;
break;
case R.id.button5:
number = 5;
break;
case R.id.button6:
number = 6;
break;
case R.id.button7:
number = 7;
break;
case R.id.button8:
number = 8;
break;
case R.id.button9:
number = 9;
break;
case R.id.button0:
if (mDisplay.getText().toString().equals("0")) {
return;
}
number = 0;
break;
}
// setting a new digit onto display if it is empty
if (mDisplayIsEmpty) {
if (!(number == 0)) {
mDisplayIsEmpty = false;
}
mDisplay.setText(Integer.toString(number));
}
// appending digit if display isn't empty
else {
mDisplay.append(Integer.toString(number));
}
mNumberEntered = true;
}
// listenning for operational buttons pressing
public void op_Clicked(View view) {
Button button = (Button) view;
// calculating and printing result
// if a number has been entered before
// (Not entering here if another operation has been pressed before)
if (mNumberEntered) {
// if received first number and saved to sNum1
if (mFirstNumberReceived) {
sNum2 = Double.parseDouble(mDisplay.getText().toString());
printResult(calculateResult(sNum1, sOperation, sNum2));
sNum1 = Double.parseDouble(mDisplay.getText().toString());
}
// if not received first number - receiving it now
else {
sNum1 = Double.parseDouble(mDisplay.getText().toString());
mFirstNumberReceived = true;
}
mNumberEntered = false;
}
// checking operational buttons id
// and assigning appropriate operations enum value
switch (button.getId()) {
case R.id.buttonPlus:
sOperation = OperationsAndFunctions.OperEnum.SUM;
break;
case R.id.buttonMinus:
sOperation = OperationsAndFunctions.OperEnum.SUBSTRACT;
break;
case R.id.buttonMultiply:
sOperation = OperationsAndFunctions.OperEnum.MULTIPLY;
break;
case R.id.buttonDivide:
sOperation = OperationsAndFunctions.OperEnum.DIVIDE;
break;
case R.id.buttonEqual:
sOperation = OperationsAndFunctions.OperEnum.EQUAL;
break;
}
// next digit entered will be a new number
mDisplayIsEmpty = true;
mPointEntered = false;
}
// listening for functional buttons pressing
public void func_Clicked(View view) {
Button button = (Button) view;
// checking operational buttons id
// and assigning appropriate functions enum value
switch (button.getId()) {
case R.id.buttonAc:
sFunction = OperationsAndFunctions.FuncEnum.RESET;
break;
case R.id.buttonC:
sFunction = OperationsAndFunctions.FuncEnum.BACKSPACE;
break;
case R.id.buttonSign:
sFunction = OperationsAndFunctions.FuncEnum.SIGN;
break;
case R.id.buttonPercent:
sFunction = OperationsAndFunctions.FuncEnum.PERCENT;
break;
case R.id.buttonPoint:
sFunction = OperationsAndFunctions.FuncEnum.POINT;
break;
}
// implementing chosen function
implementFunction(sFunction);
}
// implementing function
private void implementFunction(OperationsAndFunctions.FuncEnum function) {
sFunction = function;
switch (function) {
case RESET:
reset();
break;
case BACKSPACE:
printResult(Double.parseDouble(backSpace(mDisplay.getText())
.toString()));
break;
case SIGN:
printResult(readDisplayState() * (-1));
break;
case PERCENT:
printResult(readDisplayState() / 100);
break;
case POINT:
if (!mPointEntered) {
if (!mDisplayIsEmpty) {
mDisplay.append(".");
} else {
mDisplay.setText("0.");
mDisplayIsEmpty = false;
}
mPointEntered = true;
}
break;
}
}
// reseting the calculator
private void reset() {
mDisplay.setText("0");
sNum1 = sNum2 = 0;
mDisplayIsEmpty = true;
mFirstNumberReceived = false;
mNumberEntered = false;
mPointEntered = false;
}
// deleting the last symbol on display
private CharSequence backSpace(CharSequence displayState) {
CharSequence result = displayState;
if (displayState.length() > 1) {
result = displayState.subSequence(0, displayState.length() - 1);
}
else if (displayState.length() == 1) {
result = "0";
}
return result;
}
// calculating the result
private double calculateResult(double num1,
OperationsAndFunctions.OperEnum operation, double num2) {
sNum1 = num1;
sNum2 = num2;
sOperation = operation;
double result = 0;
switch (operation) {
case SUM:
result = num1 + num2;
break;
case SUBSTRACT:
result = num1 - num2;
break;
case MULTIPLY:
result = num1 * num2;
break;
case EQUAL:
mDisplayIsEmpty = true;
mNumberEntered = false;
mFirstNumberReceived = false;
break;
case DIVIDE:
// division by zero
if (num2 == 0) {
showError();
break;
}
result = num1 / num2;
break;
}
return result;
}
// reading current displayNumber
private double readDisplayState() {
return Double.parseDouble(mDisplay.getText().toString());
}
// printing the result
private void printResult(Double result) {
// checking if the result having decimal part
// if not then we print integer value of it without point and zero(s)
if (result % 1 == 0) {
mDisplay.setText(Integer.toString(result.intValue()));
}
else {
mDisplay.setText(Double.toString(result));
}
}
// Error message (in case of division by zero)
private void showError() {
// printing error message
mDisplay.setText("Error");
// and reseting current state
sNum1 = sNum2 = 0;
mDisplayIsEmpty = true;
mFirstNumberReceived = false;
mNumberEntered = false;
mPointEntered = false;
}
}
Thank you very much in advance!
Code style can be either a personal preference, or an organizational guideline. If working for yourself, do what works best for you. Start with some published standard code guidelines (Android Style Guide) and then change things that you don’t like. If you are working within a group, be it an open source project or as part of a project with an employer, there are typically coding standards set forth by them. One bit of advice is even if you are not a fan of the chosen style, abide by it. Having an entire file show as updated just because you reformatted the style to match your preferences is not received well in a team environment. As far as code quality, there are tools (Static analysis) that you can run against your code to give you suggestions of what might be places that could cause problems. (Android Static Analysis)
Related
For an assignment we are creating a java program that accepts a java file, fixes messy code and outputs to a new file.
We are to assume there is only one bracket { } per line and that each bracket occurs at the end of the line. If/else statements also use brackets.
I am currently having trouble finding a way to indent every line after an opening bracket until next closing bracket, then decreasing indent after closing bracket until the next opening bracket. We are also required to use the methods below:
Updated code a bit:
public static void processJavaFile() {
}
}
This algorithm should get you started. I left a few glitches that you'll have to fix.
(For example it doesn't indent your { brackets } as currently written, and it adds an extra newline for every semicolon)
The indentation is handled by a 'depth' counter which keeps track of how many 'tabs' to add.
Consider using a conditional for loop instead of a foreach if you want more control over each iteration. (I wrote this quick n' dirty just to give you an idea of how it might be done)
public String parse(String input) {
StringBuilder output = new StringBuilder();
int depth = 0;
boolean isNewLine = false;
boolean wasSpaced = false;
boolean isQuotes = false;
String tab = " ";
for (char c : input.toCharArray()) {
switch (c) {
case '{':
output.append(c + "\n");
depth++;
isNewLine = true;
break;
case '}':
output.append("\n" + c);
depth--;
isNewLine = true;
break;
case '\n':
isNewLine = true;
break;
case ';':
output.append(c);
isNewLine = true;
break;
case '\'':
case '"':
if (!isQuotes) {
isQuotes = true;
} else {
isQuotes = false;
}
output.append(c);
break;
default:
if (c == ' ') {
if (!isQuotes) {
if (!wasSpaced) {
wasSpaced = true;
output.append(c);
}
} else {
output.append(c);
}
} else {
wasSpaced = false;
output.append(c);
}
break;
}
if (isNewLine) {
output.append('\n');
for (int i = 0; i < depth; i++) {
output.append(tab);
}
isNewLine = false;
}
}
return output.toString();
}
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.
I have a JButton called nextAd that increments my private int i; plus 1 each time it is clicked, which shows different images on each click. After the button is clicked a fourth time, I want my GUI to loop back to when the button was clicked 0 times, showing what was initially on the screen when I first ran the program.
Question: How can I make my switch statement loop back to what was initially on my screen when I first launch my GUI program?
I've omitted the rest of my code except for the button clicked action. If more code is required in order to answer the question, please let me know.
private class buttonListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
{
if(e.getSource() == nextAd)
{
i++;
}
switch (i){
case 1:
appleTitle.setVisible(false);
appleAdPic.setVisible(false);
appleLogo.setVisible(false);
IBMTitle.setVisible(true);
IBMAdPic.setVisible(true);
IBMLogo.setVisible(true);
break;
case 2:
IBMTitle.setVisible(false);
IBMAdPic.setVisible(false);
IBMLogo.setVisible(false);
microsoftTitle.setVisible(true);
microsoftAdPic.setVisible(true);
microsoftLogo.setVisible(true);
break;
case 3:
microsoftTitle.setVisible(false);
microsoftAdPic.setVisible(false);
microsoftLogo.setVisible(false);
samsungTitle.setVisible(true);
samsungAdPic.setVisible(true);
samsungLogo.setVisible(true);
break;
}
}
}
}
}
I think the easiest solution would be just to set the increment value to 0 at the end of actionPerformed() if i == 3;
public void actionPerformed(ActionEvent event) {
// ...
if (i == 3) {
i = 0; // Reset the ad counter to 0, to restart the ad loop
}
}
That way, the next time actionPerformed() is called, it will start at the beginning.
You could change the start of your event handler to:
if(e.getSource() == nextAd)
{
i = (i == 3 ? 1 : i + 1);
}
Can we not have a default case and inside you can set the so-called 0-times scenario ?
For e.g.:
default:
appleTitle.setVisible(false);
appleAdPic.setVisible(false);
appleLogo.setVisible(false);
IBMTitle.setVisible(false);
IBMAdPic.setVisible(false);
IBMLogo.setVisible(false);
break;
Probably the best way to do it would be to put the switch statement into a seperate method of return type void, much like
private class buttonListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
{
if(e.getSource() == nextAd)
{
i++;
}
switching()
}
}
}
public static void switching() {
switch (i){
case 1:
appleTitle.setVisible(false);
appleAdPic.setVisible(false);
appleLogo.setVisible(false);
IBMTitle.setVisible(true);
IBMAdPic.setVisible(true);
IBMLogo.setVisible(true);
break;
case 2:
IBMTitle.setVisible(false);
IBMAdPic.setVisible(false);
IBMLogo.setVisible(false);
microsoftTitle.setVisible(true);
microsoftAdPic.setVisible(true);
microsoftLogo.setVisible(true);
break;
case 3:
microsoftTitle.setVisible(false);
microsoftAdPic.setVisible(false);
microsoftLogo.setVisible(false);
samsungTitle.setVisible(true);
samsungAdPic.setVisible(true);
samsungLogo.setVisible(true);
break;
}
case 4:
i = 0;
switching();
break;
}
Here is what I would do :
if (e.getSource() == nextAd) {
if (i >= 3) {
i = 1;
} else {
i++;
}
}
Here was my solution.
Thanks everyone!
if(e.getSource() == nextAd)
{
i++;
{
if(i == 5)
{
i = 0;
samsungTitle.setVisible(false);
samsungAdPic.setVisible(false);
samsungLogo.setVisible(false);
}
switch (i){
case 1:
appleTitle.setVisible(true);
appleAdPic.setVisible(true);
appleLogo.setVisible(true);
break;
case 2:
appleTitle.setVisible(false);
appleAdPic.setVisible(false);
appleLogo.setVisible(false);
IBMTitle.setVisible(true);
IBMAdPic.setVisible(true);
IBMLogo.setVisible(true);
break;
case 3:
IBMTitle.setVisible(false);
IBMAdPic.setVisible(false);
IBMLogo.setVisible(false);
microsoftTitle.setVisible(true);
microsoftAdPic.setVisible(true);
microsoftLogo.setVisible(true);
break;
case 4:
microsoftTitle.setVisible(false);
microsoftAdPic.setVisible(false);
microsoftLogo.setVisible(false);
samsungTitle.setVisible(true);
samsungAdPic.setVisible(true);
samsungLogo.setVisible(true);
break;
}
}
}
}
}
}
}
If I have a switch statement testing the value of integer i, how can I execute the same code once?
For example:
switch(i) {
case 0:
if(j == 2) {
booleanA = true;
booleanB = false;
case 1:
if(j == 4) {
booleanA = true;
booleanB = false;
}
With 5 different cases, instead of me having to type out
booleanA = true;
booleanB = false;
five times, is there a way to say if one of the if statements is true, use this block of code? Is that possible?
Thanks!
You can do it without a switch statement...
int[] requiredJ = {2,4};
if (j == requiredJ[i]) {
booleanA = true;
booleanB = false;
}
I can not understand logic behind your code, but may be this can be done ( Like switch hit in cricket !!! :p).
Assign the values to your booleans, and revert in default case.
booleanA = true;
booleanB = false;
// more code blocks
switch(i) {
case 0:
// Process
break;
case 1:
// Process
break;
default :
booleanA = false;
booleanB = true;
}
I'm working on a card game app and i finished the basic stuff and now i'm trying to make it look professional.
the first thing I want to do is the effect of the distribution of cards,
i want to make a shuffle card effect.
when a card is given to a player, I want at least 500 milliseconds difference to the next card that will be distributed to him.
ideas?
this is a part from my code..
private void SetTheGame() {
SetShuffleSound();
for ( int i = 0; i < Imagename.length;i++) {
Imagename[i] = (ImageView) findViewById(WTF[i]);
CountCards();
Random = getRandom();
SwitchImages SwitchMe = new SwitchImages(myNewArray[Random]);
int first = SwitchMe.ChangeImages();
Imagename[i].setImageResource(myNewArray[Random]);
Imagename[i].setVisibility(View.VISIBLE);
CardsCount valueOfCard = new CardsCount(myNewArray[Random]);
int a = valueOfCard.WhatsMyValue();
String b = valueOfCard.TheFamily();
switch (i) {
case 0:
if (first != 0) {
Imagename[0].setImageResource(first);
}
FirstColumnComputer.add(a);
FirstColumnComputerFAMILY.add(b);
break;
case 1:
if (first != 0) {
Imagename[1].setImageResource(first);
}
SecondColumnComputer.add(a);
SecondColumnComputerFAMILY.add(b);
break;
case 2:
if (first != 0) {
Imagename[2].setImageResource(first);
}
ThirdColumnComputer.add(a);
ThirdColumnComputerFAMILY.add(b);
break;
case 3:
if (first != 0) {
Imagename[3].setImageResource(first);
}
FourColumnComputer.add(a);
FourColumnComputerFAMILY.add(b);
break;
case 4:
if (first != 0) {
Imagename[4].setImageResource(first);
}
FifthColumnComputer.add(a);
FifthColumnComputerFAMILY.add(b);
break;
case 5:
FirstColumnPlayer.add(a);
FirstColumnPlayerFAMILY.add(b);
break;
case 6:
SecondColumnPlayer.add(a);
SecondColumnPlayerFAMILY.add(b);
break;
case 7:
ThirdColumnPlayer.add(a);
ThirdColumnPlayerFAMILY.add(b);
break;
case 8:
FourColumnPlayer.add(a);
FourColumnPlayerFAMILY.add(b);
break;
case 9:
FifthColumnPlayer.add(a);
FifthColumnPlayerFAMILY.add(b);
break;
}
Cards.remove(Random);
// MakeTheCardPause();
}
SentTheLinkedList();
}
MakeTheCardPause() is the problem...
private void MakeTheCardPause() {
Thread Timer = new Thread()
{
public void run()
{
try{
sleep(1000);
}catch(InterruptedException e)
{
e.printStackTrace();
}finally
{
//do something...
}
}
};
Timer.start();
}
thanks!
Many ways you can do this. Thread.sleep(500) is the way was you suggested but it is not what I would recommend. Here are two alternatives
Message Handler
An example
Handler mHandler = new Handler(){
public void handleMessage(Message msg){
super.handleMessage(msg);
switch(msg.what){
case shuffle:
// Do something
break;
case doneShuffle:
//Do something
}
}
};
Asynch Tasks
Here is an example:
private class shuffleCards extends AsyncTask<Card, Integer, Long> {
protected Long doInBackground(Card card) {
//Do something
//shuffle deck
// Escape early if cancel() is called
if (isCancelled()) break;
}
return deck;
}
protected void onProgressUpdate(Integer... progress) {
//Number of shuffled cards??
}
protected void onPostExecute(Long result) {
//Show card
}
}
Remember this is just a background task to display results. Your main thread will be handling the actual card values and handing them over to the Asynch task.
Good Luck
What about this? You need to have the sleep in the working thread, your code above is creating a new thread and telling it to sleep, which has no noticeable effect to the user.
private void SetTheGame() {
SetShuffleSound();
for ( int i = 0; i < Imagename.length;i++) {
Imagename[i] = (ImageView) findViewById(WTF[i]);
CountCards();
Random = getRandom();
SwitchImages SwitchMe = new SwitchImages(myNewArray[Random]);
int first = SwitchMe.ChangeImages();
Imagename[i].setImageResource(myNewArray[Random]);
Imagename[i].setVisibility(View.VISIBLE);
CardsCount valueOfCard = new CardsCount(myNewArray[Random]);
int a = valueOfCard.WhatsMyValue();
String b = valueOfCard.TheFamily();
switch (i) {
case 0:
if (first != 0) {
Imagename[0].setImageResource(first);
}
FirstColumnComputer.add(a);
FirstColumnComputerFAMILY.add(b);
break;
case 1:
if (first != 0) {
Imagename[1].setImageResource(first);
}
SecondColumnComputer.add(a);
SecondColumnComputerFAMILY.add(b);
break;
case 2:
if (first != 0) {
Imagename[2].setImageResource(first);
}
ThirdColumnComputer.add(a);
ThirdColumnComputerFAMILY.add(b);
break;
case 3:
if (first != 0) {
Imagename[3].setImageResource(first);
}
FourColumnComputer.add(a);
FourColumnComputerFAMILY.add(b);
break;
case 4:
if (first != 0) {
Imagename[4].setImageResource(first);
}
FifthColumnComputer.add(a);
FifthColumnComputerFAMILY.add(b);
break;
case 5:
FirstColumnPlayer.add(a);
FirstColumnPlayerFAMILY.add(b);
break;
case 6:
SecondColumnPlayer.add(a);
SecondColumnPlayerFAMILY.add(b);
break;
case 7:
ThirdColumnPlayer.add(a);
ThirdColumnPlayerFAMILY.add(b);
break;
case 8:
FourColumnPlayer.add(a);
FourColumnPlayerFAMILY.add(b);
break;
case 9:
FifthColumnPlayer.add(a);
FifthColumnPlayerFAMILY.add(b);
break;
}
Cards.remove(Random);
long sleepMax = 1000L;
Random r = new Random();
long delay = (long) (r.nextDouble() * range);
Thread.sleep(delay);
}
SentTheLinkedList();
}