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);
}
}
I have no errors in my program but I'm not getting a right answer. For example :
----jGRASP exec: java good
5
6
4
the number of values enterd from 0-9 is 0
----jGRASP: operation complete.
I shoud get "3" but I get "0"
Your code doesn't work because you are missing brackets on your for loop. You just execute n=variable.nextInt()
five times without checking it, and then check it. If you include brackets this should work.
You need to use braces around your the inner for loop
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);
}
}
Your main problem is not understanding when your for
loop ends. You should add brackets { }
around loops and if
statements, so that only the code inside those brackets executes when the conditions are met.
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);
}
You should also close your Scanner
.
Short tutorial on loops .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.