我想创建计数器变量(int ball = 0),但是它不起作用。
理想情况下,每次输入球时,我都要保持记录ball = 1,ball = 2,...
我希望它显示四分球!在第四名。
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
答案 0 :(得分:0)
只需将球计数器设置在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!");
}
}
}