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

Java 8:如何实现用户输入循环及仅输入0的提示功能

解决你的Java统计程序问题

我来帮你搞定这两个问题!咱们先梳理下原有代码的不足,再给出完整的修正版本:

问题分析

  1. 缺少程序循环控制:原代码只处理了一轮整数输入,读取到0后就直接结束,没有根据用户输入的y/n来重启整个流程。
  2. 无仅输入0的提示:当用户一开始就输入0时,程序会直接输出全0的统计结果,没有友好提示。

修正后的完整代码

import java.util.Scanner;

public class CountPositiveNegativeAndAverageOfIntsProgram {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        char continueChoice;
        
        // 外层do-while循环控制整个程序是否重复执行
        do {
            // 每次循环开始时重置统计变量,避免累加之前的数据
            int countPositive = 0;
            int countNegative = 0;
            int total = 0;
            double average = 0.0;
            
            System.out.print("Enter an integer, the input ends if it is 0: ");
            int userInput = input.nextInt();
            
            // 处理整数输入的循环
            while (userInput != 0) {
                if (userInput > 0) {
                    countPositive++;
                } else {
                    countNegative++;
                }
                total += userInput;
                average = total / (countPositive + countNegative + 0.0);
                
                System.out.print("Enter an integer, the input ends if it is 0: ");
                userInput = input.nextInt();
            }
            
            // 判断是否仅输入了0,给出提示
            if (countPositive == 0 && countNegative == 0) {
                System.out.println("No numbers entered except 0.");
            } else {
                System.out.println("The number of positives is: " + countPositive);
                System.out.println("The number of negatives is: " + countNegative);
                System.out.println("The total is: " + total);
                System.out.println("The average is : " + average);
            }
            
            // 询问用户是否继续,兼容大小写输入
            System.out.print("Continue? (y/n) ");
            continueChoice = input.next().toLowerCase().charAt(0);
            
        // 当用户输入y/Y时继续循环,否则退出
        } while (continueChoice == 'y');
        
        input.close();
        System.out.println("Program ended.");
    }
}

关键改动说明

  • 外层do-while循环:把整个统计逻辑包裹起来,通过用户输入的y/n决定是否重启程序,完美解决循环控制问题。
  • 重置统计变量:每轮循环开始都重新初始化计数和总和变量,确保每轮统计都是独立的,不会和上次数据混淆。
  • 仅输入0的提示:通过判断正负计数都为0的情况,输出友好提示,替代原来的全0统计结果。
  • 大小写兼容:把用户输入的继续选项转为小写,输入Y或y都能生效,提升使用体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 15:52:43