首页 > 解决方案 > 我想通过 for 循环创建计数器变量

问题描述

我想创建计数器变量(int ball=0)但它不起作用。

理想情况下,我想记录 ball =1 ,ball=2,,,,, 每次我得到球输入

我希望它显示四球!在第 4 位。

ball → ball!
ball → ball!
ball → ball!
ball → fourball!

但现在每次都显示球!

import java.util.*;
public class Main{
    public static void main(String[] args) {
        System.out.println("type number 5~7");
        Scanner sc = new Scanner(System.in);
        String number = sc.nextLine();
        int u = Integer.parseInt(number);
        System.out.println(u + "times will be played ");
        for (int i=0; i<u; i++) {
            String result = sc.nextLine();
            if (result.equals("ball")) {
                int ball = 1;
                ball ++;
                System.out.println(ball);
                if (ball >= 4) {
                    System.out.println("fourball!");
                    break;
                } else {
                    System.out.println("ball!");
                }
            }

        }//for終わり



            /*else if (result.equals("strike")) {
                for (int strike=0; strike<=5; strike++) {
                    if (strike >= 2) {
                        System.out.println("out!");
                        break;
                    } else {
                        System.out.println("strike!");
                    }
                }//if
            }//else if 
            else{
                System.out.println("type strike or ball");
            }

             */
        //}//for
    }//main

}//Main





标签: javafor-loop

解决方案


只需像这样在 for 循环之外设置球计数器

import java.util.*;

public class Main{
    public static void main(String[] args) {
        System.out.println("type number 5~7");
        Scanner sc = new Scanner(System.in);
        String number = sc.nextLine();
        int u = Integer.parseInt(number);
        System.out.println(u + "times will be played ");
        int ball = 0;
        for (int i=0; i<u; i++) {
            String result = sc.nextLine();
            if (result.equals("ball")) {
                ball ++;
                System.out.println(ball);
                if (ball >= 4) {
                    System.out.println("fourball!");
                    break;
                } else {
                    System.out.println("ball!");
                }
            }

        }

推荐阅读