簡體   English   中英

我想通過 for 循環創建計數器變量

[英]I want to create counter variable by for loop

我想創建計數器變量 (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





只需像這樣將球計數器設置在 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!");
                }
            }

        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM