java - 我想通过 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
解决方案
只需像这样在 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!");
}
}
}
推荐阅读
- oracle - 在 Oracle 12c 中向用户授予所有权限
- asp.net-core - 如何在使用 FromBody 的 POST 请求处理程序中获取 json 解析错误详细信息
- zoho - Zoho Creator - 从日历报告中获取日历日期并粘贴到另一个表单中
- android - 刷新时如何阻止选项卡式视图上的片段闪烁?
- wordpress - 当类别中的帖子超过 6 个时显示“手风琴”
- javascript - 数组的 JavaScript 哈希
- html - 当屏幕尺寸减小时,是否可以将垂直线更改为水平线?
- sql - to_Char(DATE) 与时间
- javascript - 停止正在运行的脚本
- jquery - 使用 jquery (ASP.NET MVC) 选择一个或多个或所有复选框