import java.util.Scanner;
public class good
{
public static void main(String[] args) {
Scanner variable = new Scanner(System.in);
int i = 0, counter = 0, n = 0;
for (i = 0; i < 5; i++) {
n = variable.nextInt();
}
if ((0 <= n) && (n <= 9)) {
counter++;
}
System.out.println("the number of values enterd from 0-9 is " + counter);
}
}
我的计划中没有错误,但我没有得到正确答案。例如:
----jGRASP exec: java good
5
6
4
the number of values enterd from 0-9 is 0
----jGRASP: operation complete.
我应该得到&#34; 3&#34; 但我得到&#34; 0&#34;
答案 0 :(得分:3)
您的代码无法正常工作,因为您的for循环中缺少括号。您只需执行n=variable.nextInt()
五次而不检查它,然后检查它。如果你包括括号,这应该有用。
答案 1 :(得分:2)
您需要在内部for循环周围使用大括号
import java.util.Scanner;
public class good
{
public static void main(String[] args)
{
Scanner variable=new Scanner(System.in);
int i=0,counter=0,n=0;
for(i=0;i<5;i++){
n=variable.nextInt();
if((0<=n)&&(n<=9))
counter++;
}
System.out.println("the number of values enterd from 0-9 is "+counter);
}
}
答案 2 :(得分:1)
当您的for
循环结束时,您的主要问题是无法理解。您应该在循环和{ }
语句周围添加括号if
,以便只有满足条件时才会执行这些括号内的代码。
public static void main(String[] args)
{
Scanner variable = new Scanner(System.in);
int counter = 0;
for(int i = 0; i < 5; i++)
{
int n = variable.nextInt();
if(0 <= n && n <= 9)
{
counter++;
}
}
variable.close();
System.out.println("the number of values enterd from 0-9 is: " + counter);
}
您还应该关闭您的Scanner
。