1

I tried to create a Guess Number Game, which I set up a range of number and edit text for user to enter the number. I tried to input, for example "50" but when I tried to delete, I could only delete the "0". If I keep delete the number "5" the app crashed. Here are my MainActivity codes:

import java.util.Random;

public class MainActivity extends AppCompatActivity {
  TextView textViewChoice, textViewStatus;
  EditText editTextNum ;

Button buttonSetting;
SharedPreferences preferences;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textViewChoice = (TextView) findViewById(R.id.textViewChoice);
    textViewStatus =(TextView) findViewById(R.id.textviewStatus);
    editTextNum = (EditText) findViewById(R.id.edittextGuess);

    buttonSetting =(Button) findViewById(R.id.buttonSetting);
    preferences = getSharedPreferences("LIMITS",MODE_PRIVATE);




    buttonSetting.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(MainActivity.this, SecondaryActivity.class);
            startActivity(intent);
        }
    });
}

@Override
protected void onStart() {
    super.onStart();
    final int MinNumber = preferences.getInt("Seekbar Min", 0);
    final int MaxNumber = preferences.getInt("Seekbar Max", 0);
    textViewChoice.setText("" + MinNumber + "-" + MaxNumber);

    editTextNum.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            Random random = new Random();
            int RanNum = random.nextInt(MaxNumber-MinNumber)+MinNumber;
            String StringEditNum= editTextNum.getText().toString();
            int EditNum = Integer.parseInt(StringEditNum);
            if (EditNum >RanNum){
                textViewStatus.setText("Enter Higher Number");
            }
            else if(EditNum <RanNum){
                textViewStatus.setText("Enter Lower Numer!");


            }
            else if (StringEditNum.equals("")){
                Toast.makeText(MainActivity.this,"Error!",Toast.LENGTH_SHORT).show();
            }
            else {
                textViewStatus.setText("You won! You Nutz!");
            }

        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    });

}

@Override
protected void onStop() {
    super.onStop();
}

@Override
protected void onDestroy() {
    super.onDestroy();
}
}

After I debugged I get this:

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.user.ggame, PID: 3291 java.lang.NumberFormatException: For input string: "" at java.lang.Integer.parseInt(Integer.java:620) at java.lang.Integer.parseInt(Integer.java:643) at com.example.user.ggame.MainActivity$2.onTextChanged(MainActivity.java:71) at android.widget.TextView.sendOnTextChanged(TextView.java:9359) at android.widget.TextView.handleTextChanged(TextView.java:9446) at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:11904) at android.text.SpannableStringBuilder.sendTextChanged(SpannableStringBuilder.java:1252) at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:573) at android.text.SpannableStringBuilder.delete(SpannableStringBuilder.java:229) at android.text.SpannableStringBuilder.delete(SpannableStringBuilder.java:227) at android.text.method.BaseKeyListener.backspaceOrForwardDelete(BaseKeyListener.java:370) at android.text.method.BaseKeyListener.backspace(BaseKeyListener.java:71) at android.text.method.BaseKeyListener.onKeyDown(BaseKeyListener.java:479) at android.text.method.NumberKeyListener.onKeyDown(NumberKeyListener.java:148) at android.widget.TextView.doKeyDown(TextView.java:7316) at android.widget.TextView.onKeyDown(TextView.java:7093) at android.view.KeyEvent.dispatch(KeyEvent.java:2688) at android.view.View.dispatchKeyEvent(View.java:11662) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827) at com.android.internal.policy.DecorView.superDispatchKeyEvent(DecorView.java:437) at com.android.internal.policy.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1818) at android.app.Activity.dispatchKeyEvent(Activity.java:3252) at android.support.v7.app.AppCompatActivity.dispatchKeyEvent(AppCompatActivity.java:534) at android.support.v7.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:58) at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.dispatchKeyEvent(AppCompatDelegateImplBase.java:316) at com.android.internal.policy.DecorView.dispatchKeyEvent(DecorView.java:351) at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:4714) at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4586) at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4128) at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4181) at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4147) at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4274) at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4155) at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4331) at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4128) at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4181) at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4147) at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4155) at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4128) at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4181) at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4147) at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4307) at android.view.ViewRootImpl$ImeInputStage.onFinishedInputEvent(ViewRootImpl.java:4468) at android.view.inputmethod.InputMethodManager$PendingEvent.run(InputMethodManager.java:2435) at android.view.inputmethod.InputMethodManager.invokeFinishedInputEventCallback(InputMethodManager.java:1998) E/AndroidRuntime: at android.view.inputmethod.InputMethodManager.finishedInputEvent(InputMethodManager.java:1989) at android.view.inputmethod.InputMethodManager$ImeInputEventSender.onInputEventFinished(InputMethodManager.java:2412) at android.view.InputEventSender.dispatchInputEventFinished(InputEventSender.java:141) at android.os.MessageQueue.nativePollOnce(Native Method) at android.os.MessageQueue.next(MessageQueue.java:325) at android.os.Looper.loop(Looper.java:142) at android.app.ActivityThread.main(ActivityThread.java:6541) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

yivi
  • 42,438
  • 18
  • 116
  • 138
Minh
  • 63
  • 1
  • 1
  • 5

6 Answers6

2

Your issue is here in this line:

 String StringEditNum= editTextNum.getText().toString();
 int EditNum = Integer.parseInt(StringEditNum);

While clearing the 5 the value of StringEditNum will be empty string and you cannot parseInt empty string so it is crashing

try adding this :

String StringEditNum= editTextNum.getText().toString();
int EditNum = 0;
if(!StringEditNum.equals("")){
   EditNum = Integer.parseInt(StringEditNum);
}
Abubakker Moallim
  • 1,610
  • 10
  • 20
1

Check the code below.

editTextNum.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

      if(editTextNum.getText().toString().length() > 0)
      {
        Random random = new Random();
        int RanNum = random.nextInt(MaxNumber-MinNumber)+MinNumber;
        String StringEditNum= editTextNum.getText().toString();
        int EditNum = Integer.parseInt(StringEditNum);
        if (EditNum >RanNum){
            textViewStatus.setText("Enter Higher Number");
        }
        else if(EditNum <RanNum){
            textViewStatus.setText("Enter Lower Numer!");
        }
        else if (StringEditNum.equals("")){
            Toast.makeText(MainActivity.this,"Error!",Toast.LENGTH_SHORT).show();
        }
        else {
            textViewStatus.setText("You won! You Nutz!");
        }
      }
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
});
Pang
  • 9,564
  • 146
  • 81
  • 122
Jyubin Patel
  • 1,373
  • 7
  • 17
1

try below code

   Random random = new Random();
   int RanNum = random.nextInt(MaxNumber-MinNumber)+MinNumber;
   String StringEditNum= editTextNum.getText().toString();
    if(!StringEditNum.equals("")){
        int EditNum = Integer.parseInt(StringEditNum);
        if (EditNum >RanNum){
            textViewStatus.setText("Enter Higher Number");
        }else if(EditNum <RanNum){
            textViewStatus.setText("Enter Lower Numer!");
        }else {
            textViewStatus.setText("You won! You Nutz!");
        }
    } else{
            Toast.makeText(MainActivity.this,"Try again!",Toast.LENGTH_SHORT).show();
        }
Omkar
  • 3,040
  • 1
  • 22
  • 42
  • happy to help , Don't forget to mark as accept answer! check https://i.stack.imgur.com/LkiIZ.png – Omkar Dec 28 '17 at 07:09
0

Try this

  1. This will produce java.lang.IllegalArgumentException: n <= 0: 0 because bound should be random.nextInt(bound) 0<=bound

       Random random = new Random();
       int RanNum = random.nextInt(MaxNumber-MinNumber)+MinNumber;
    
       try this
    
        Random random = new Random();
        int RanNum = random.nextInt((MaxNumber-MinNumber)+1);
    

2.String should not be null when converting to integer

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        Random random = new Random();
        int RanNum = random.nextInt((MaxNumber-MinNumber)+1);
        String StringEditNum= editTextNum.getText().toString();
            if (!TextUtils.isEmpty(editTextNum.getText().toString()))
            {
                int EditNum = Integer.parseInt(StringEditNum);
                if (EditNum >RanNum){
                    textViewStatus.setText("Enter Higher Number");
                }
                else if(EditNum <RanNum){
                    textViewStatus.setText("Enter Lower Numer!");


                }
                else if (StringEditNum.equals("")){
                    Toast.makeText(MainActivity.this,"Error!",Toast.LENGTH_SHORT).show();
                }
                else {
                    textViewStatus.setText("You won! You Nutz!");
                }
            }else {

            }            

    }
Ramesh sambu
  • 3,577
  • 2
  • 24
  • 39
0

check StringEditNum not null or empty before convert it in to int

    if(!StringEditNum.equalsIgnoreCase("")){

            int EditNum = Integer.parseInt(StringEditNum);

    }
Anil Kanani
  • 260
  • 2
  • 19
0

The thing is you are using a textWatcher listener and whenever you write/delete something this listener is called. Now when you write the number 50 you write 5 and 0. Then when you delete it you first delete 0 which leaves 5. In this situation the following line is good

int EditNum = Integer.parseInt(StringEditNum);

but when you delete the 5 the StringEditNum becomes "" and the above line will cause a java.lang.NumberFormatException. so please check the code below to make it work perfectly

import java.util.Random;

public class MainActivity extends AppCompatActivity {
TextView textViewChoice, textViewStatus;
EditText editTextNum ;

Button buttonSetting;
SharedPreferences preferences;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

textViewChoice = (TextView) findViewById(R.id.textViewChoice);
textViewStatus =(TextView) findViewById(R.id.textviewStatus);
editTextNum = (EditText) findViewById(R.id.edittextGuess);

buttonSetting =(Button) findViewById(R.id.buttonSetting);
preferences = getSharedPreferences("LIMITS",MODE_PRIVATE);




  buttonSetting.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent intent = new Intent(MainActivity.this,        SecondaryActivity.class);
        startActivity(intent);
    }
});
}

@Override
protected void onStart() {
super.onStart();
final int MinNumber = preferences.getInt("Seekbar Min", 0);
final int MaxNumber = preferences.getInt("Seekbar Max", 0);
textViewChoice.setText("" + MinNumber + "-" + MaxNumber);

editTextNum.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        Random random = new Random();
        int RanNum = random.nextInt(MaxNumber-MinNumber)+MinNumber;
        String StringEditNum= editTextNum.getText().toString();
        if(!StringEditNum.equals("")){
        int EditNum = Integer.parseInt(StringEditNum);
        if (EditNum >RanNum){
            textViewStatus.setText("Enter Higher Number");
        }
        else if(EditNum <RanNum){
            textViewStatus.setText("Enter Lower Numer!");


        }

        else {
            textViewStatus.setText("You won! You Nutz!");
        }
    }else{
          Toast.makeText(MainActivity.this,"Error!",Toast.LENGTH_SHORT).show();
    }
 }
    @Override
    public void afterTextChanged(Editable editable) {

    }
});

}

@Override
protected void onStop() {
super.onStop();
}

@Override
protected void onDestroy() {
super.onDestroy();
}
}
Saurav Mir
  • 124
  • 1
  • 11