You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开发Higher or Lower数字应用时,空EditText解析Int致崩溃求助

Fixing the Crash When Input is Empty in "Higher or Lower Number" App

Hey there! I’ve run into this exact headache with input fields and integer parsing before—nothing’s more frustrating than an empty input taking down your whole app. Let’s break down how to fix this quickly and cleanly.

The Root Cause

When your EditText is empty (or just has random whitespace), calling Integer.parseInt() on that empty string throws a NumberFormatException. Android doesn’t handle this exception automatically, so it immediately crashes the app instead of gracefully handling the mistake.

Step-by-Step Fix

Here’s how to handle empty inputs, invalid non-numeric entries, and keep your users in the loop:

  1. Validate input first
    Trim any whitespace from the input string and check if it’s empty before trying to parse it. This catches cases where the user taps the button without typing anything, or just enters spaces.

  2. Add a safety net with try-catch
    Even with the initial check, users might enter letters, symbols, or decimals. Wrapping the parsing in a try-catch prevents crashes from those invalid entries too.

  3. Give clear, friendly feedback
    Instead of crashing, show a simple Toast message telling the user what went wrong—no confusing error screens required.

Example Code

Here’s what your button click listener should look like after the fix:

Button guessButton = findViewById(R.id.guess_button);
EditText numberInput = findViewById(R.id.number_input);

guessButton.setOnClickListener(v -> {
    // Get and clean up the input text
    String inputText = numberInput.getText().toString().trim();
    
    // Exit early if input is empty
    if (inputText.isEmpty()) {
        Toast.makeText(this, "Whoa, enter a number first!", Toast.LENGTH_SHORT).show();
        return;
    }
    
    // Safely parse the integer
    try {
        int userGuess = Integer.parseInt(inputText);
        // Your existing "higher or lower" game logic goes here
    } catch (NumberFormatException e) {
        // Handle non-integer inputs
        Toast.makeText(this, "Oops, that's not a valid whole number. Try again!", Toast.LENGTH_SHORT).show();
        // Optional: Log the error for debugging
        e.printStackTrace();
    }
});

This way, your app won’t crash when the input is empty, and users get helpful hints instead of a confusing crash screen.

内容的提问来源于stack exchange,提问作者Kashan Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:43:44