[英]How to write Java program that takes a number from a user and calculate sum and average of the numbers in between?
[英]how to write java program that read 5 numbers and calculate how many numbers has value from 0-9
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.
我应该得到“ 3”,但是我得到“ 0”
您的代码无效,因为您缺少for循环中的方括号。 您只执行五次n=variable.nextInt()
而不对其进行检查,然后对其进行检查。 如果包括方括号,这应该可行。
您需要在内部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);
}
}
您的主要问题是不了解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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.