[英]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.