Square of a number in Eclipse not working - java

This is the code for a calculator app for Android I'm making:
package com.example.calculator;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Iterator;
import java.util.Stack;
import java.lang.Math;
import android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.view.View;
import android.view.View.OnClickListener;
public class main extends Activity {
GridView mKeypadGrid;
TextView userInputText;
TextView memoryStatText;
Stack<String> mInputStack;
Stack<String> mOperationStack;
KeypadAdapter mKeypadAdapter;
TextView mStackText;
boolean resetInput = false;
boolean hasFinalResult = false;
String mDecimalSeperator;
double memoryValue = Double.NaN;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DecimalFormat currencyFormatter = (DecimalFormat) NumberFormat
.getInstance();
char decimalSeperator = currencyFormatter.getDecimalFormatSymbols()
.getDecimalSeparator();
mDecimalSeperator = Character.toString(decimalSeperator);
setContentView(R.layout.main);
// Create the stack
mInputStack = new Stack<String>();
mOperationStack = new Stack<String>();
// Get reference to the keypad button GridView
mKeypadGrid = (GridView) findViewById(R.id.grdButtons);
// Get reference to the user input TextView
userInputText = (TextView) findViewById(R.id.txtInput);
userInputText.setText("0");
memoryStatText = (TextView) findViewById(R.id.txtMemory);
memoryStatText.setText("");
mStackText = (TextView) findViewById(R.id.txtStack);
// Create Keypad Adapter
mKeypadAdapter = new KeypadAdapter(this);
// Set adapter of the keypad grid
mKeypadGrid.setAdapter(mKeypadAdapter);
// Set button click listener of the keypad adapter
mKeypadAdapter.setOnButtonClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Button btn = (Button) v;
// Get the KeypadButton value which is used to identify the
// keypad button from the Button's tag
KeypadButton keypadButton = (KeypadButton) btn.getTag();
// Process keypad button
ProcessKeypadInput(keypadButton);
}
});
mKeypadGrid.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
}
});
}
private void ProcessKeypadInput(KeypadButton keypadButton) {
//Toast.makeText(this, keypadButton.getText(), Toast.LENGTH_SHORT).show();
String text = keypadButton.getText().toString();
String currentInput = userInputText.getText().toString();
int currentInputLen = currentInput.length();
String evalResult = null;
double userInputValue = Double.NaN;
switch (keypadButton) {
case BACKSPACE: // Handle backspace
// If has operand skip backspace
if (resetInput)
return;
int endIndex = currentInputLen - 1;
// There is one character at input so reset input to 0
if (endIndex < 1) {
userInputText.setText("0");
}
// Trim last character of the input text
else {
userInputText.setText(currentInput.subSequence(0, endIndex));
}
break;
case SIGN: // Handle -/+ sign
// input has text and is different than initial value 0
if (currentInputLen > 0 && currentInput != "0") {
// Already has (-) sign. Remove that sign
if (currentInput.charAt(0) == '-') {
userInputText.setText(currentInput.subSequence(1,
currentInputLen));
}
// Prepend (-) sign
else {
userInputText.setText("-" + currentInput.toString());
}
}
break;
case CE: // Handle clear input
userInputText.setText("0");
break;
case SQUARE:
double squareInput = Double.valueOf(currentInput);
userInputText.setText(squareInput+"*"+squareInput);
break;
case C: // Handle clear input and stack
userInputText.setText("0");
clearStacks();
break;
case DECIMAL_SEP: // Handle decimal separator
if (hasFinalResult || resetInput) {
userInputText.setText("0" + mDecimalSeperator);
hasFinalResult = false;
resetInput = false;
} else if (currentInput.contains("."))
return;
else
userInputText.append(mDecimalSeperator);
break;
case DIV:
case PLUS:
case MINUS:
case MULTIPLY:
if (resetInput) {
mInputStack.pop();
mOperationStack.pop();
} else {
if (currentInput.charAt(0) == '-') {
mInputStack.add("(" + currentInput + ")");
} else {
mInputStack.add(currentInput);
}
mOperationStack.add(currentInput);
}
mInputStack.add(text);
mOperationStack.add(text);
dumpInputStack();
evalResult = evaluateResult(false);
if (evalResult != null)
userInputText.setText(evalResult);
resetInput = true;
break;
case CALCULATE:
if (mOperationStack.size() == 0)
break;
mOperationStack.add(currentInput);
evalResult = evaluateResult(true);
if (evalResult != null) {
clearStacks();
userInputText.setText(evalResult);
resetInput = false;
hasFinalResult = true;
}
break;
case M_ADD: // Add user input value to memory buffer
userInputValue = tryParseUserInput();
if (Double.isNaN(userInputValue))
return;
if (Double.isNaN(memoryValue))
memoryValue = 0;
memoryValue += userInputValue;
displayMemoryStat();
hasFinalResult = true;
break;
case M_REMOVE: // Subtract user input value to memory buffer
userInputValue = tryParseUserInput();
if (Double.isNaN(userInputValue))
return;
if (Double.isNaN(memoryValue))
memoryValue = 0;
memoryValue -= userInputValue;
displayMemoryStat();
hasFinalResult = true;
break;
case MC: // Reset memory buffer to 0
memoryValue = Double.NaN;
displayMemoryStat();
break;
case MR: // Read memoryBuffer value
if (Double.isNaN(memoryValue))
return;
userInputText.setText(doubleToString(memoryValue));
displayMemoryStat();
break;
case MS: // Set memoryBuffer value to user input
userInputValue = tryParseUserInput();
if (Double.isNaN(userInputValue))
return;
memoryValue = userInputValue;
displayMemoryStat();
hasFinalResult = true;
break;
default:
if (Character.isDigit(text.charAt(0))) {
if (currentInput.equals("0") || resetInput || hasFinalResult) {
userInputText.setText(text);
resetInput = false;
hasFinalResult = false;
} else {
userInputText.append(text);
resetInput = false;
}
}
break;
}
}
private void clearStacks() {
mInputStack.clear();
mOperationStack.clear();
mStackText.setText("");
}
private void dumpInputStack() {
Iterator<String> it = mInputStack.iterator();
StringBuilder sb = new StringBuilder();
while (it.hasNext()) {
CharSequence iValue = it.next();
sb.append(iValue);
}
mStackText.setText(sb.toString());
}
private String evaluateResult(boolean requestedByUser) {
if ((!requestedByUser && mOperationStack.size() != 4)
|| (requestedByUser && mOperationStack.size() != 3))
return null;
String left = mOperationStack.get(0);
String operator = mOperationStack.get(1);
String right = mOperationStack.get(2);
String tmp = null;
if (!requestedByUser)
tmp = mOperationStack.get(3);
double leftVal = Double.parseDouble(left.toString());
double rightVal = Double.parseDouble(right.toString());
double result = Double.NaN;
if (operator.equals(KeypadButton.DIV.getText())) {
result = leftVal / rightVal;
} else if (operator.equals(KeypadButton.MULTIPLY.getText())) {
result = leftVal * rightVal;
} else if (operator.equals(KeypadButton.PLUS.getText())) {
result = leftVal + rightVal;
} else if (operator.equals(KeypadButton.MINUS.getText())) {
result = leftVal - rightVal;
}
String resultStr = doubleToString(result);
if (resultStr == null)
return null;
mOperationStack.clear();
if (!requestedByUser) {
mOperationStack.add(resultStr);
mOperationStack.add(tmp);
}
return resultStr;
}
private String doubleToString(double value) {
if (Double.isNaN(value))
return null;
long longVal = (long) value;
if (longVal == value)
return Long.toString(longVal);
else
return Double.toString(value);
}
private double tryParseUserInput() {
String inputStr = userInputText.getText().toString();
double result = Double.NaN;
try {
result = Double.parseDouble(inputStr);
} catch (NumberFormatException nfe) {
}
return result;
}
private void displayMemoryStat() {
if (Double.isNaN(memoryValue)) {
memoryStatText.setText("");
} else {
memoryStatText.setText("M = " + doubleToString(memoryValue));
}
}
}
To find the square of an inputted number, I use the following code:
case SQUARE:
double squareInput = Double.valueOf(currentInput);
userInputText.setText(squareInput+"*"+squareInput);
break;
But when the input the numbers 9 and 9, it just displays *9*9.* It doesn't display the output as 81.
Why is this, and can someone help me fix it?

You are converting number as String by adding "*". Instead you need is:
userInputText.setText(String.valueOf(squareInput*squareInput));
The way it works is:
First it sees 9 then you append a string "" which returns 9 and now you append another double to existing string which append 9 to existing string and thus you get "9*9"

Your formula is incorrect.
Try this.
double squareInput = Double.valueOf(currentInput);
userInputText.setText(String.format("%f", squareInput * squareInput));

You are setting the string value instead of square calcluated valued.
Do like this :
userInputText.setText(String.valueOf(squareInput*squareInput));

You ony concatinate the values a s a String. If you what the square you need to calculate and add it to the textfield:
userInputText.setText(squareInput+"*"+squareInput+"="+(squareInput*squareInput) );

Use the following code...It might be helpful for you..
case SQUARE:
double squareInput = Double.valueOf(currentInput);
userInputText.setText(String.valueOf(squareInput*squareInput));
break;

change your code to this
case SQUARE:
double squareInput = Double.valueOf(currentInput);
userInputText.setText(""+squareInput*squareInput);
break;

Related

I try to create a vocabulary loop in android

I am trying to make an app that alike vocabulary card.
I have an Answer array(array size = 4).
I am creating random an english word then I am adding true value of english word in answer array and I am removing true value of english word in turkish array in order to not use again in random.I am doing same things to other answer array include wrong value.
Problem is that array size is going to 0.for example my total array 20 .when I remove true value,array size is going to 19-18-17... per click then program close.
Here is my code:
package de.murattekinlive.pwords;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class WordsActivity extends AppCompatActivity {
TextView textView;
TextView deneme;
DataBase dataBase;
Button btn_r1,btn_r2,btn_r3,btn_r4;
String [] TR_WORDS;
String [] EN_WORDS;
String [] Answer;
int control_id = 0;
int random ;
Random control;
Random rnd;
int tr,en;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_words);
textView = (TextView) findViewById(R.id.textView);
deneme = (TextView) findViewById(R.id.textView3);
dataBase = new DataBase(getApplicationContext());
rnd= new Random();
btn_r1 = (Button)findViewById(R.id.button_random1);
btn_r1.setOnClickListener(new myClickListener());
btn_r2 = (Button)findViewById(R.id.button_random2);
btn_r2.setOnClickListener(new myClickListener());
btn_r3 = (Button)findViewById(R.id.button_random3);
btn_r3.setOnClickListener(new myClickListener());
btn_r4 = (Button)findViewById(R.id.button_random4);
btn_r4.setOnClickListener(new myClickListener());
ArrayList<Words> enWordlist = (ArrayList<Words>) dataBase.allEnWords();
ArrayList<Words> trWordlist =(ArrayList<Words>) dataBase.allTrWords();
TR_WORDS = new String[trWordlist.size()];
EN_WORDS = new String[enWordlist.size()];
for(int i=0;i<enWordlist.size();i++){
EN_WORDS[i] =enWordlist.get(i).getWORD().toString();
TR_WORDS[i] =trWordlist.get(i).getTR1().toString();
}
tr = new Random().nextInt(TR_WORDS.length);
/*btn_r1.setText(TR_WORDS[en]);
btn_r2.setText(TR_WORDS[new Random().nextInt(TR_WORDS.length)]);
btn_r3.setText(TR_WORDS[new Random().nextInt(TR_WORDS.length)]);
btn_r4.setText(TR_WORDS[new Random().nextInt(TR_WORDS.length)]);*/
ReStart();
}
private class myClickListener implements View.OnClickListener{
public void onClick(View v){
switch ( v.getId() ) {
case R.id.button_random1:
break;
case R.id.button_random2:
break;
case R.id.button_random3:
break;
case R.id.button_random4:
break;
default:
break;
}
WordsActivity.this.ReStart();
}
}
public void ReStart(){
Answer = new String[4];
control = new Random();
control_id = control.nextInt(4);
en = new Random().nextInt(EN_WORDS.length);
final List<String> newTRList = new ArrayList<>();
textView.setText(EN_WORDS[en]);
final int sayi1,sayi2;
sayi1 = TR_WORDS.length;
Collections.addAll(newTRList,TR_WORDS);
// I added true turkish word in answer array
for(int i=0;i<TR_WORDS.length;i++){
if(en == i){
Answer[control_id]=TR_WORDS[i].toString();
newTRList.remove(TR_WORDS[i].toString()); //remove true value from array in order to not use again.
}
}
TR_WORDS = newTRList.toArray(new String[newTRList.size()]);
//I added another values in answer array and I want to remove values that is used because
//I dont want to see same value in answer array.
for(int i=0;i<=3;i++){
if(i == control_id){
}
else if(i == 0){
random=rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 1){
random=rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 2){
random=rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 3){
random=rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
}
sayi2 =TR_WORDS.length;
deneme.setText(sayi1+"/"+sayi2);
for(int i=0;i<=3;i++){
if(i == control_id){
}
else if(i == 0){
random =rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 1){
random =rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 2){
random =rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 3){
random =rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
}
for(int j=0;j<=3;j++){
if(j==0){
btn_r1.setText(Answer[j].toString());
}
else if(j==1){
btn_r2.setText(Answer[j].toString());
}
else if(j==2){
btn_r3.setText(Answer[j].toString());
}
else if(j==3){
btn_r4.setText(Answer[j].toString());
}
}
}
}
Change your for loop to:
for(int i=TR_WORDS.length; i >=0 ;i--){
if(en == i){
Answer[control_id]=TR_WORDS[i].toString();
newTRList.remove(TR_WORDS[i].toString()); //remove true value from array in order to not use again.
}
}
And all the other ones that include a remove in a similar a fashion.

How to set textview as method output in andrioid?

I have just started to use android studio recently and currently I am working on a Roman Numeral Translator app. The app's interface looks like this: Application interface
The user will use the keypad to input a integer which will show up on the TextView shown above. When they hit the convert button it will take the integer they have entered and convert it (the program will be able to catch the input if contains a string or character). Then the app will reset the TextView to the result after the user hits the "convert" button.
Currently, my main activity contains the onClickListeners for the buttons and a separate translator method for the translations. My problem is with the "convert" button I'm not sure how to get the input from the translator method and set it as TextView when it finishes converting. Here is the sample of my code:
"Convert" button listener- `
convert.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
TextView numeralInput = (TextView) findViewById(R.id.textView);
String intValue = numeralInput.getText().toString();
try{
int integer = Integer.parseInt(intValue);
if (integer > 0 && integer <= 4999){
translator(integer);
}else{
numeralInput.setText("Please enter an integer between 0 and 4,999.");
}
}catch(NumberFormatException e){
numeralInput.setText("Invalid input try again.");
}
}
}
);
`
Translator Method- `
public static void translator(int integer) {
LinkedList<String> stack = new LinkedList<String>();
// if (integer > 0 && integer <= 4999) {
//ArrayList<Integer> placement = new ArrayList<Integer>();
int place = (int) Math.log10(integer);
for (int i = 0; i <= place; i++) {
//while(integer > 0){
//System.out.println(integer);
int placeOfValue = integer % 10;
//stack.push(placeOfValue);
//System.out.print(stack);
//System.out.print(placeOfValue +":" + i);
String placement = "";
switch (i) {
case 0:
placement = ones(placeOfValue);
break;
case 1:
placement = tens(placeOfValue);
break;
case 2:
placement = hundreds(placeOfValue);
break;
case 3:
placement = thousands(placeOfValue);
break;
default:
break;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
stack.push(placement);
}
integer = integer / 10;
//System.out.print(placement);
// System.out.println(placement.size());
//}
// for(int j = 0; j < placement.size(); j++){
// double tenthPower = Math.floor(Math.log10(placement.get(j)));
// double place = Math.pow(10, tenthPower);
// System.out.println(place);
//
// }
// }
while (!stack.isEmpty()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
System.out.print(stack.pop());
}
}
// } else {
// System.out.println("Please enter an integer between 0 and 4,999.");
// }
}
}
`
The other methods inside translator is like a library for the roman numerals each containing a numeral for each of the place values as shown below.
Thousands method- `
public static String thousands(int integer) {
String thouValue = "";
switch (integer) {
case 1:
thouValue = "M";
//System.out.print("M");
break;
case 2:
thouValue = "MM";
//System.out.print("MM");
break;
case 3:
thouValue = "MMM";
//System.out.print("MMM");
break;
case 4:
thouValue = "MMMM";
//System.out.print("MMMM");
break;
default:
thouValue = "";
break;
}
return thouValue;
}
`
Make your translator() method return a string which contains the final output.
So before the while statement in that method, declare a string such as
String result = null; and in the loop append the popped values to this variable like, result += stack.pop().
Now, the place where you call the translator(integer) method, do numeralInput.setText(translator(integer)) instead of translator(integer)
You need to make your TextView a class member and initialise it in your oncreate bundle, so that you can access the textview elsewhere in the activity.
TextView numeralInput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
numeralInput = (TextView) findViewById(R.id.textView);
convert.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
String intValue = numeralInput.getText().toString();
try{
int integer = Integer.parseInt(intValue);
if (integer > 0 && integer <= 4999){
translator(integer);
}else{
numeralInput.setText("Please enter an integer between 0 and 4,999.");
}
}catch(NumberFormatException e){
numeralInput.setText("Invalid input try again.");
}
}
}
);

Math.sqrt showing error in Eclipse

This is the code for a calculator app for Android I'm making:
package com.example.calculator;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Iterator;
import java.util.Stack;
import java.lang.Math;
import android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.view.View;
import android.view.View.OnClickListener;
public class main extends Activity {
GridView mKeypadGrid;
TextView userInputText;
TextView memoryStatText;
Stack<String> mInputStack;
Stack<String> mOperationStack;
KeypadAdapter mKeypadAdapter;
TextView mStackText;
boolean resetInput = false;
boolean hasFinalResult = false;
String mDecimalSeperator;
double memoryValue = Double.NaN;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DecimalFormat currencyFormatter = (DecimalFormat) NumberFormat
.getInstance();
char decimalSeperator = currencyFormatter.getDecimalFormatSymbols()
.getDecimalSeparator();
mDecimalSeperator = Character.toString(decimalSeperator);
setContentView(R.layout.main);
// Create the stack
mInputStack = new Stack<String>();
mOperationStack = new Stack<String>();
// Get reference to the keypad button GridView
mKeypadGrid = (GridView) findViewById(R.id.grdButtons);
// Get reference to the user input TextView
userInputText = (TextView) findViewById(R.id.txtInput);
userInputText.setText("0");
memoryStatText = (TextView) findViewById(R.id.txtMemory);
memoryStatText.setText("");
mStackText = (TextView) findViewById(R.id.txtStack);
// Create Keypad Adapter
mKeypadAdapter = new KeypadAdapter(this);
// Set adapter of the keypad grid
mKeypadGrid.setAdapter(mKeypadAdapter);
// Set button click listener of the keypad adapter
mKeypadAdapter.setOnButtonClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Button btn = (Button) v;
// Get the KeypadButton value which is used to identify the
// keypad button from the Button's tag
KeypadButton keypadButton = (KeypadButton) btn.getTag();
// Process keypad button
ProcessKeypadInput(keypadButton);
}
});
mKeypadGrid.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
}
});
}
private void ProcessKeypadInput(KeypadButton keypadButton) {
//Toast.makeText(this, keypadButton.getText(), Toast.LENGTH_SHORT).show();
String text = keypadButton.getText().toString();
String currentInput = userInputText.getText().toString();
int currentInputLen = currentInput.length();
String evalResult = null;
double userInputValue = Double.NaN;
switch (keypadButton) {
case BACKSPACE: // Handle backspace
// If has operand skip backspace
if (resetInput)
return;
int endIndex = currentInputLen - 1;
// There is one character at input so reset input to 0
if (endIndex < 1) {
userInputText.setText("0");
}
// Trim last character of the input text
else {
userInputText.setText(currentInput.subSequence(0, endIndex));
}
break;
case SIGN: // Handle -/+ sign
// input has text and is different than initial value 0
if (currentInputLen > 0 && currentInput != "0") {
// Already has (-) sign. Remove that sign
if (currentInput.charAt(0) == '-') {
userInputText.setText(currentInput.subSequence(1,
currentInputLen));
}
// Prepend (-) sign
else {
userInputText.setText("-" + currentInput.toString());
}
}
break;
case CE: // Handle clear input
userInputText.setText("0");
break;
case SQRT:
userInputText.setText(Math.sqrt(currentInput));
break;
case C: // Handle clear input and stack
userInputText.setText("0");
clearStacks();
break;
case DECIMAL_SEP: // Handle decimal separator
if (hasFinalResult || resetInput) {
userInputText.setText("0" + mDecimalSeperator);
hasFinalResult = false;
resetInput = false;
} else if (currentInput.contains("."))
return;
else
userInputText.append(mDecimalSeperator);
break;
case DIV:
case PLUS:
case MINUS:
case MULTIPLY:
if (resetInput) {
mInputStack.pop();
mOperationStack.pop();
} else {
if (currentInput.charAt(0) == '-') {
mInputStack.add("(" + currentInput + ")");
} else {
mInputStack.add(currentInput);
}
mOperationStack.add(currentInput);
}
mInputStack.add(text);
mOperationStack.add(text);
dumpInputStack();
evalResult = evaluateResult(false);
if (evalResult != null)
userInputText.setText(evalResult);
resetInput = true;
break;
case CALCULATE:
if (mOperationStack.size() == 0)
break;
mOperationStack.add(currentInput);
evalResult = evaluateResult(true);
if (evalResult != null) {
clearStacks();
userInputText.setText(evalResult);
resetInput = false;
hasFinalResult = true;
}
break;
case M_ADD: // Add user input value to memory buffer
userInputValue = tryParseUserInput();
if (Double.isNaN(userInputValue))
return;
if (Double.isNaN(memoryValue))
memoryValue = 0;
memoryValue += userInputValue;
displayMemoryStat();
hasFinalResult = true;
break;
case M_REMOVE: // Subtract user input value to memory buffer
userInputValue = tryParseUserInput();
if (Double.isNaN(userInputValue))
return;
if (Double.isNaN(memoryValue))
memoryValue = 0;
memoryValue -= userInputValue;
displayMemoryStat();
hasFinalResult = true;
break;
case MC: // Reset memory buffer to 0
memoryValue = Double.NaN;
displayMemoryStat();
break;
case MR: // Read memoryBuffer value
if (Double.isNaN(memoryValue))
return;
userInputText.setText(doubleToString(memoryValue));
displayMemoryStat();
break;
case MS: // Set memoryBuffer value to user input
userInputValue = tryParseUserInput();
if (Double.isNaN(userInputValue))
return;
memoryValue = userInputValue;
displayMemoryStat();
hasFinalResult = true;
break;
default:
if (Character.isDigit(text.charAt(0))) {
if (currentInput.equals("0") || resetInput || hasFinalResult) {
userInputText.setText(text);
resetInput = false;
hasFinalResult = false;
} else {
userInputText.append(text);
resetInput = false;
}
}
break;
}
}
private void clearStacks() {
mInputStack.clear();
mOperationStack.clear();
mStackText.setText("");
}
private void dumpInputStack() {
Iterator<String> it = mInputStack.iterator();
StringBuilder sb = new StringBuilder();
while (it.hasNext()) {
CharSequence iValue = it.next();
sb.append(iValue);
}
mStackText.setText(sb.toString());
}
private String evaluateResult(boolean requestedByUser) {
if ((!requestedByUser && mOperationStack.size() != 4)
|| (requestedByUser && mOperationStack.size() != 3))
return null;
String left = mOperationStack.get(0);
String operator = mOperationStack.get(1);
String right = mOperationStack.get(2);
String tmp = null;
if (!requestedByUser)
tmp = mOperationStack.get(3);
double leftVal = Double.parseDouble(left.toString());
double rightVal = Double.parseDouble(right.toString());
double result = Double.NaN;
if (operator.equals(KeypadButton.DIV.getText())) {
result = leftVal / rightVal;
} else if (operator.equals(KeypadButton.MULTIPLY.getText())) {
result = leftVal * rightVal;
} else if (operator.equals(KeypadButton.PLUS.getText())) {
result = leftVal + rightVal;
} else if (operator.equals(KeypadButton.MINUS.getText())) {
result = leftVal - rightVal;
}
String resultStr = doubleToString(result);
if (resultStr == null)
return null;
mOperationStack.clear();
if (!requestedByUser) {
mOperationStack.add(resultStr);
mOperationStack.add(tmp);
}
return resultStr;
}
private String doubleToString(double value) {
if (Double.isNaN(value))
return null;
long longVal = (long) value;
if (longVal == value)
return Long.toString(longVal);
else
return Double.toString(value);
}
private double tryParseUserInput() {
String inputStr = userInputText.getText().toString();
double result = Double.NaN;
try {
result = Double.parseDouble(inputStr);
} catch (NumberFormatException nfe) {
}
return result;
}
private void displayMemoryStat() {
if (Double.isNaN(memoryValue)) {
memoryStatText.setText("");
} else {
memoryStatText.setText("M = " + doubleToString(memoryValue));
}
}
}
To find the Square root of an inputted number, I use the following code:
import java.lang.Math;
case SQRT:
userInputText.setText(Math.sqrt(currentInput));
break;
But its showing error in this line:
userInputText.setText(Math.sqrt(currentInput));
Error: The method sqrt(double) in the type Math is not applicable for the arguments (String)
Why is this, and can someone help me fix it? Thanks in advance.
Read the error message:
userInputText.setText(Math.sqrt(currentInput));
Error: The method sqrt(double) in the type Math is not applicable for the arguments (String)
It's telling you that you're calling Math.sqrt with a String argument where it expects a double (a floating point numeric value). And, indeeed, that is the case:
String currentInput = userInputText.getText().toString();
If you have a string and you want to turn that into a double, you should be looking at something like Double.parseDouble():
double dInput;
try {
dInput = Double.parseDouble(currentInput);
catch (NumberFormatException e) {
doSomethingIntelligent();
}
// Now have dInput which can be passed to `sqrt()`.
Keep in mind that, once you have the square root as a double, you can't just blindly pass that to setText(), you'll need to turn it back into a string first.
Provided you're certain the initial string will be a valid double, you can replace your problematic line:
userInputText.setText(Math.sqrt(currentInput));
with something like:
double dVal = 0;
try {
dVal = Double.parseDouble(currentInput);
} catch (NumberFormatException e) {}
dVal = Math.sqrt(dVal);
userInputText.setText(String.valueOf(dVal));
Because Math.sqrt method takes double argument. Parse your string to double.
userInputText.setText(String.valueof(Math.sqrt(Double.parseDouble(currentInput))));

" character is not getting typed in my auto-typer program

This program reads from a file and types its contents out line by line or at the ends of sentences depending on config settings. It uses Java.awt.Robot to do this, and all the keyboard characters can be typed except the apostrophe and quotation characters. The key is function on my keyboard and other scripts can type it. I can't figure out why this program cannot type it correctly.
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
public class SmartRobot extends Robot {
public int count70=0;
public SmartRobot() throws AWTException {
super();
}
public void keyType(int keyCode) {
if(keyCode == -1)
return;
keyPress(keyCode);
delay(2);
keyRelease(keyCode);
}
public void keyType(int keyCode, int keyCodeModifier) {
keyPress(keyCodeModifier);
keyPress(keyCode);
delay(2);
keyRelease(keyCode);
keyRelease(keyCodeModifier);
}
public void type(String text) {
if(text.length()>1 && text.substring(0, 1).equals("\\")){
Driver.codeTimeEnd = System.nanoTime();
delay(Integer.parseInt(text.substring(2, text.length()))-(int) (Driver.codeTimeEnd-Driver.codeTimeStart)/1000000000);
return;
}
String textUpper = text.toUpperCase();
for (int i=0; i<text.length(); ++i) {
typeChar(textUpper.charAt(i));
}
if(!Driver.enterAtPeriods || !Driver.enterUnder60)keyPress(KeyEvent.VK_ENTER);
Driver.codeTimeEnd = System.nanoTime();
if(!Driver.enterUnder60)
delay(Driver.lineDelay-(int)(Driver.codeTimeEnd- Driver.codeTimeStart)/1000000000);
else
delay(2);
}
public void typeChar(char c) {
boolean shift = true;
int keyCode;
switch (c) {
case '~':keyCode = (int)'`';break;
case '!':keyCode = (int)'1';break;
case '#':keyCode = (int)'2';break;
case '#':keyCode = (int)'3';break;
case '$':keyCode = (int)'4';break;
case '%':keyCode = (int)'5';break;
case '^':keyCode = (int)'6';break;
case '&':keyCode = (int)'7';break;
case '*':keyCode = (int)'8';break;
case '(':keyCode = (int)'9';break;
case ')':keyCode = (int)'0';break;
case ':':keyCode = (int)';';break;
case '_':keyCode = (int)'-';break;
case '+':keyCode = (int)'=';break;
case '|':keyCode = (int)'\\';break;
case '"':keyCode = (int)'\'';break;
case '?':keyCode = (int)'/';break;
case '{':keyCode = (int)'[';break;
case '}':keyCode = (int)']'; break;
case '<':keyCode = (int)',';break;
case '>':keyCode = (int)'.';break;
case '“':keyCode = (int)'\'';break;
case '”':keyCode = (int)'\'';break;
case '…':keyCode = (int)' ';break;
case '‘':keyCode = (int)'\'';break;
case '’':keyCode = (int)'\'';break;
default:
// System.out.println(c);
keyCode = (int)c;
// System.out.println(keyCode);
shift = false;
}
if(Driver.enterUnder60){
count70++;
if(count70>70)
if(c == ' '){
count70 = 0;
keyType(KeyEvent.VK_ENTER);
delay(Driver.lineDelay-(int)(Driver.codeTimeEnd-Driver.codeTimeStart)/1000000000);
return;
}
}
if(Driver.enterAtPeriods){
if(c == '.'){
count70 = 0;
keyType(KeyEvent.VK_ENTER);
delay(Driver.lineDelay-(int)(Driver.codeTimeEnd-Driver.codeTimeStart)/1000000000);
return;
}
}
if (shift){
keyType(keyCode, KeyEvent.VK_SHIFT);
System.out.println("works");
}
else
keyType(keyCode);
}
private int charToKeyCode(char c) {
switch (c) {
case ':':
return ';';
}
return (int)c;
}
}
The infile can be whatever you want it to be, and all characters will be shown, but the " will not be typed. I don't know if the type() method is ever accessed in its case.
Here is an example input:
"Hi, my name is koikoi."
The output comes out like this:
Hi, my name is koikoi.
When it should have the quotations on it. The typer does not recognize/read them. I can't find any flaws in my code and would like some advice. I can add the main method if requested.

Sokoban Java Performmove error

This is sokoban game in java. i'm having error when i try to perform a move. Anybody can point out the changes i have to make to make it work?
Here are the errors im getting
java.lang.StringIndexOutOfBoundsException: String index out of range: 49
at java.lang.String.charAt(Unknown Source)
at State.stateString(State.java:32)
at State.(State.java:15)
at boxpushing.perform(boxpushing.java:14)
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
public class State{
private int posX;
private int posY;
private ArrayList<Integer> goalX;
private ArrayList<Integer> goalY;
private char[][] state;
public State(String s){
state=stateString(s);
goalX=new ArrayList<Integer>();
goalY=new ArrayList<Integer>();
locatePositionPlayerAndTargets();
}
public char [][] stateString(String s){
//need to put the state string into respective array position
int width = s.indexOf("\n"); //to find how many number of rows below.
int height = s.length() / width;
char newState[][] = new char[height][width];
int index = 0;
for (int i = 0; i <height; i++){
for(int j = 0; j< width; j++){
newState[i][j]=s.charAt(index);
index++;
}
index++;
}
return newState;
}
public char[][] getState(){
return state;
}
private void locatePositionPlayerAndTargets(){
//for player on target, target and crate on target
for (int i=0; i< state.length; i++){
for(int j=0; j<state[0].length; j++){
if(state[i][j] == 'P'){
posX=j;
posY=i;
} else if (state[i][j] == '+' || state[i][j] == 'o' || state[i][j] == '#' ){
goalX.add(j); //save the goal/targets values (X and Y position)
goalY.add(i);
}
}
}
}
public ArrayList<Integer> getGoalY(){
return goalY; //return the goal/target Y's position
}
public ArrayList<Integer> getGoalX(){
return goalX; //return the goal/target X's position
}
public int getPosX(){
return posX;
}
public int getPosY(){
return posY;
}
public void setChar(int y, int x, char c){
//to save the current element on that particular coordinates/position
state[y][x] = c;
}
public char getChar(int y, int x){
//will return what is on that particular coordinates/position
return state[y][x];
}
//To replace the symbol/character after player move is initiated
public void replacePlayerOnMove(int dy, int dx){
// to get the char value on the current position
char charOnPos = state[posY][posX];
switch(charOnPos){
case '+':
//if current position has 'playerOnTarget' replace with target
setChar(posY,posX, 'o');
break;
case '#':
//if current position has 'crateontarget' replace with playeronTarget
setChar(posY,posX, '+');
break;
case 'P':
//if current position has 'player' replace with background
setChar(posY,posX, '.');
break;
}
posX += dx;
posY += dy;
}
//To replace the symbol/character player is pushing the crate
public void replacePlayerOnPush(int dy, int dx){
char charOnPos = state[posY][posX];
switch(charOnPos){
case '#':
//if current position has 'crateOnTarget' replace with 'playerontarget'
setChar(posY,posX, '+');
break;
case '*':
//if current position has 'crate' replace with player
setChar(posY,posX, 'P');
break;
}
}
//To replace the symbol/character when crate is moved
public void replaceCrateOnMove(int dy, int dx, char c){
switch(c){
case 'o':
setChar(posY,posX, '#');
break;
case '.':
setChar(posY,posX, '*');
break;
}
}
public boolean checkValidMove(int dx, int dy){
try{ // need to use try and catch as this might not work / error might occur furthe debugging needed
int tmpX = getPosX()+dx;
int tmpY = getPosY()+dy;
// this is for index out of bound array checks
// then also check for crate / wall for pushing iniatiation
char newPosition = getChar(tmpY, tmpX);
if (newPosition == '*' || newPosition == '#'){
return checkValidPush(dx,dy);
} else if (newPosition == '#'){
return false;
} else {
return true;
}
} catch (ArrayIndexOutOfBoundsException e){
//if outofbound occurs just return false (possible end of boundary/map)
return false;
} catch (Exception e){
System.out.println("Error Occur tadaaaa..Yeehaa =( ");
return false;
}
}
public boolean checkValidPush(int dx, int dy){
int tmpPushX = getPosX() + dx*2; //new position of crate (x coordinates)
int tmpPushY = getPosY() + dy*2; //new position of crate (x coordinates)
char newCratePosition = getChar(tmpPushY,tmpPushX);
if (newCratePosition != '#' && newCratePosition != '*' && newCratePosition != '#'){
return true;
} else {
return false; //crate new position is invalid (possible collision might occur)
}
}
public void cratePush(int my, int mx){
//new position of crate after moved
int newCratePosX = posX+mx*2;
int newCratePosY = posY+my*2;
//get current symbol / item on the new position above
char c = getChar(newCratePosY, newCratePosX);
//replace box with the symbol / item above.
replaceCrateOnMove(newCratePosY, newCratePosX, c);
}
public void playerMove(int mx, int my){
if (checkValidMove(mx, my)){
int tmpNewX = posX+mx;
int tmpNewY = posY+my;
char newPosition = getChar(tmpNewY, tmpNewX);
switch(newPosition){
case '#':
cratePush(my,mx);
replacePlayerOnMove(my,mx);
replacePlayerOnPush(my,mx);
return;
case '*':
cratePush(my,mx);
replacePlayerOnMove(my,mx);
replacePlayerOnPush(my,mx);
return;
case '.':
setChar(tmpNewY,tmpNewX,'P');
replacePlayerOnMove(my,mx);
return;
case 'o':
setChar(tmpNewY,tmpNewX,'+');
replacePlayerOnMove(my,mx);
return;
default:
System.out.println("The move is not valid");
return;
}
}
}
public String toString(){
String printString = "";
for (int i=0; i<state.length; i++){
for (int j=0; j<state[0].length; j++){
printString += state[i][j];
}
printString += "\n";
}
return printString;
}
}
Here are the boxpushing codes
public class boxpushing {
private final static char player = 'P';
private final static char playerOnTarget = '+';
private final static char wall = '#';
private final static char crate = '*';
private final static char crateOnTarget= '#';
private final static char target = 'o';
private final static char background = '.';
private State currentState;
public String perform(String state, char move){
currentState = new State(state);
performMove(move);
System.out.println("Before");
System.out.println(state);
System.out.println("");
return currentState.toString();
}
public void performMove(char moveInput){
switch (moveInput){
case 'u':
currentState.playerMove(0, 1);
break;
case 'd':
currentState.playerMove(0, -1);
break;
case 'l':
currentState.playerMove(-1, 0);
break;
case 'r':
currentState.playerMove(1, 0);
break;
}
}
}
Hint: One of the
index++;
is superfluous.
Figuring out which one is left as an exercise for the reader.

Categories