How to Compare Two String and count them? [duplicate] - java

This question already has answers here:
How to Delete Item Without Deleting Position in Recycler View?
(2 answers)
Closed 4 years ago.
I am trying to count clicks based on getAdapterPosition(). And it works properly. Below the code
#Override
public void onClick(View v) {
// Do button click handling here
if ( posisi2==getAdapterPosition() ) {
clickcount--;
tombolbaca.setText("Baca " + clickcount + "x");
if (clickcount <= 0)
{
mTitle.setVisibility(View.GONE);
rl2.setVisibility(View.GONE);
}
} // adapter
} // onClick
But when I am trying to count clicks using the comparison of two string, I got the problem. The result is, the computer can only count that once. Can you help me to fix the problem? The problem lays here:
public Button tombolbaca;
private int klik10 = 10;
#Override
public void onClick(View v) {
tombolbaca = (Button) v.findViewById(R.id.buttonbaca);
// Problem here
if( tombolbaca.getText().toString().equals("Baca 10x") ) {
klik10--;
tombolbaca.setText("Baca " + klik10 + "x");
if (klik10 <= 0)
{
mTitle.setVisibility(View.GONE);
rl2.setVisibility(View.GONE);
}
}
} // onclick

Ok, got it now.
The problem is in logics: this is your code, written by text instead of code
if( tombolbaca.getText().toString().equals("Baca 10x"){ // this line says "if the text is exactly Baca 10x, go on"
klik10--; // this line says: "make the value of klik10 = klik10 -1
tombolbaca.setText("Baca " + klik10 + "x"); //this line says "set text of tombolbaca as the composition of the strings and the value of klik10
if (klik10 <= 0) //if klik10 is equal or less than 0, do this
{
mTitle.setVisibility(View.GONE);
rl2.setVisibility(View.GONE);
}
So, the problem lays here:
First iteration:
klik10 = 10
it enter the first if
klik10 will now be 9
text will be Baca 9x
not less than 1, so skip the if
Second iteration
klik10 = 9 (because you set it before)
not going into if
so, the problem is that you are going in only if text is Baca 10x, but after the first iteration it won't be that anymore.
A solution could be this:
#Override
public void onClick(View v) {
klik10--;
tombolbaca.setText("Baca " + klik10 + "x");
if (klik10 <= 0)
{
mTitle.setVisibility(View.GONE);
rl2.setVisibility(View.GONE);
}
}
The if, as it is written, is not necessary. you can just remove it and the code will work.
If not, tell me why there is the if clause and I will fix above code :)
PS:
If you want to check if the text is the correct counter, do the following if:
if(tombolbaca.getText().String().equals("Baca " + klik10.toString() + "x"){
...

In second attempt the comparation will be between "Baca 9x".equals("Baca 10x") and your if statement not will work
Try as follow
if( !tombolbaca.getText().toString().equals("Baca 0x") ) { //using "Baca 0x"
...
}

Related

How to make backspace on calculator? [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
How to remove the last character from a string?
(37 answers)
What is a StringIndexOutOfBoundsException? How can I fix it?
(1 answer)
Closed 2 years ago.
I am making the calculator app.
I tried to make the delete button, but there are errors.
(1) If I press backspace when there is no number, the app closed suddenly.
(2) If I press a new number after deleting the number, the previous deleted number shows up again.
I searched a lot about it but I cannot understand them as a beginner.
I would appreciate it if you can explain it easily.
public class MainActivity extends AppCompatActivity {
TextView workingsTV;
TextView resultsTV;
String workings = "";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initTextView();
}
private void initTextView()
{
workingsTV = (TextView)findViewById(R.id.workingsTextView);
resultsTV = (TextView)findViewById(R.id.resultTextView);
}
private void setWorkings(String givenValue)
{
workings = workings + givenValue;
workingsTV.setText(workings);
}
public void equalsOnClick(View view)
{
Double result = null;
ScriptEngine engine = new ScriptEngineManager().getEngineByName("rhino");
try {
result = (Double) engine.eval(workings);
if (result != null)
{
int intVal = (int) result.doubleValue();
if (result == intVal)
{//Check if it's value is equal to its integer part
resultsTV.setText(String.valueOf(intVal));
}
else
{
resultsTV.setText(String.valueOf(result));
}
}
}
catch (ScriptException e) {
Toast.makeText(this, "Invalid Input", Toast.LENGTH_SHORT).show();
}
}
public void deleteOnClick(View view)
{
String del_number = workingsTV.getText().toString();
workingsTV.setText(del_number.substring(0,del_number.length() - 1));
}
Problem 1 is because del_number.length() is 0, so del_number.length()-1 is -1 which is an illegal parameter to substring. The easiest way to fix it is to not do anything if the length is 0.
Problem 2 is because you don't reset the variable workings when you delete. It needs to be set to "". Or don't have that variable at all and always use the workingsTV.getText() be the source of truth.
I found the solution.
I edit the code like this to prevent the app closed suddenly.
public void deleteOnClick(View view) {
if(workingsTV.getText().toString().length() >= 1) {
String getResultText = workingsTV.getText().toString();
String subString = getResultText.substring(0, getResultText.length() -1);
workingsTV.setText(subString);
}
else
{
workingsTV.setText(CLEAR_INT_TEXT);
}
}
But still I had a problem that the letter I deleted comes back when I press a new number.
The solution was this.
workings = workings.substring(0, workings.length() -1);
The letter at workings should be deleted as well like workingsTV
So here is full code for delete
public void deleteOnClick(View view) {
if(workingsTV.getText().toString().length() >= 1) {
String getResultText = workingsTV.getText().toString();
String subString = getResultText.substring(0, getResultText.length() -1);
workingsTV.setText(subString);
workings = workings.substring(0, workings.length() -1);
}
else
{
workingsTV.setText(CLEAR_INT_TEXT);
}
}

Android, String Array can't go BACKWARDS from [0] TO [6(last String)] (Button = Button -1), CRASH

Whenever my back_button reaches the String[0] and I try proceeding going backwards my App just crashes.
Instead of simply going from String[0] to my currently last string [6] and continue to go backwards (if the conditions are met), why it doesnt do that ?
My code for that Button, btw im new to programming and I know my Code is EXTREMLY TRASH.. but, that's another topic, please xD :
back_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
forward_button.setVisibility(View.GONE);
backButton();
if (mediator == 10) {
forward_button.setVisibility(View.VISIBLE);
backk--;
display.setText(list[backk]);
}
if (backk == currentnumber-5 ) {
back_button.setClickable(false);
}
if (backk != currentnumber-5) {
back_button.setClickable(true);
back_button.setEnabled(true);
}
if (mediator != 10){
back_button.setEnabled(false);
display.setText(list[currentnumber]);
}
}
});
Btw. I thought it maybe has something to do with this Code right here in my other's Button Logic, maybe there is a similiar function to call for when going from String [0] to String [last string(6)] ?
if (currentnumber == list.length) {
currentnumber = 0;
backk = 0;
back = 1;
EDIT : I deleted if ( backk < 0 ) { ... , I dont know why it was in there to begin with, sorry, that wasnt supposed to be in there.
In your block, make the following change:
if (mediator == 10) {
forward_button.setVisibility(View.VISIBLE);
backk--;
// If we go below the size of the array, add the array
// size to loop back to the last element in the array
if (backk < 0){
backk += list.length;
}
display.setText(list[backk]);
}
If you explain what it is you're trying to accomplish and post more of your code, I might be able to help clean up your code a little with comments on why I make the choices I do. But the change above will fix that array out of bounds crash.

Making a button do multiple things [duplicate]

This question already has answers here:
Keep pressing a button so that a counter keeps adding by 1 every time
(2 answers)
Closed 5 years ago.
What i need this code to do is that I want it so that once you click the button for the first time, it displays if it's correct and if the button is pressed a second time it displays a new question.
I have updated the code. I have tried implementing the use of counters with the help of some comments however it still does not function correctly.
if(view.getId()==R.id.btnEnter){
counter++;
if(!answerDisplayed.endsWith("?")) {
int useranswer= Integer.parseInt(answerDisplayed.substring(5));
if(useranswer==calculatedAnswer){
//correct
}else{
//incorrect
}
}
if(counter ==2) {
randomQuestion();
}
}
counter = 0;
if(view.getId() == R.id.btnEnter && counter == 0) {
counter++;
// do something
}else{
randomQuestion();
}
at your randomQuestion(), you should decrease the counter.
void randomQuestion(){
.
.
.
--counter;
}

Android/Java EditableTextView Line Count

I am trying to teach myself Android Java programming and I have started by attempting to create a simple text editor.
I wanted to have a line count down the left hand side like standard IDEs, and I couldn't really find anywhere on StackExchange or the internet on the definitive "best practice" way to do something like this.
So I created my own logic based on what I read, but I wanted to just check that this was the best and most efficient way to do it -- and also if this happens to help anyone out looking to do the same thing.
// START onCreate
// #mEditText = Main AutoCompleteTextView
// #mLineCount = Line Count TextView
mEditText.addTextChangedListener(new TextWatcher() {
// Set current line variable
private int currentLine;
// Text Watcher
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// Before new text is inserted, get the current line count
currentLine = mEditText.getLineCount();
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Do nothing
}
#Override
public void afterTextChanged(Editable e) {
// Update Line Count
// #mEditText: AutoCompleteTextView Input
// #mLineCount: TextView Output
// #currentLine: Integer
updateLineCount(mEditText, mLineCount, currentLine);
}
});
// END onCreate
public void updateLineCount(AutoCompleteTextView editText, TextView lineText, int currentLine){
// Get updated Line Count
int lineCount = editText.getLineCount();
// If that Line Count exists and IS NOT the "before" Line Count (to stop repeating)
if(lineCount > 0 && lineCount != currentLine){
// If "before" Line Count is smaller, push Line Count up
if(currentLine < lineCount){
lineText.append(Integer.toString(lineCount) + "\n");
}
// Else if "before" Line Count is greater (ie. you have deleted a line), push Line Count down
else {
// Get Text of current lineText TextView, replace with a substring of
// the current lineText TextView - the length of the deleted line
// (ie. Line 9 = 1 Character + 1 for the line break; Line 10 = 2 Characters + 1 etc)
lineText.setText(lineText.getText().toString().substring(0, lineText.getText().toString().length() - (Integer.toString(lineCount+1).length() + 1)));
}
}
return;
}
So yeah, this is working fine -- but I am especially not sure about that last line -- Seems abit ... resource wasteful .. to be replacing the entire lineText TextView content each time a line is deleted.
Is there an anti-append that might work better in this situation?
Thanks,
Jamie
if(lineCount > 0 && lineCount != currentLine){
What happend if I select all text and delete all.
That will not meet the condition. So, mabe text line still display "5 lines" rather than "0 line"

App does not respond while trying to access charsequence elements through a loop

i m trying to make a calculator which can solve long expressions like 30+55-(2+7-20)
but i m having some logical problem in my equal button... beq
i have tested that logical problem is in for loop but couldnt understand. any help is greatl appreciated. heres my code
beq.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (status==1){
get=tvdisp1.getText(); //tvdisp1 represents textView top expression bar
// tvdisp2.setText(get); //tvdisp2 represents 2nd textView answer bar
if(get.charAt(0)=='x') {status=0;} //to check for syntax error
if(get.charAt(0)=='รท') {status=0;} // same
for(int i =0; i <= get.length(); i++ ) { // loop to check if the first character is digit or character.
if (Character.isDigit(get.charAt(i))) {
//is digit
}
else {
//is operator
}
}
if (cbracq_c>obracs_c){status=0;} // if number of closing brackets > opening brackets
if ( status == 0 ) { tvdisp1.setText("Syntax Error AC to reset");}
}
}
});
it is just as Jon Skeet said.
You count 1 to far -> get.length() gives u a length (for example) 5, so you have index from 0 to 4. But in your loop you are also try to access index 5 because of the "<=". Just change it to "<" and it should work

Categories