Reputation: 11
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"
Upvotes: 0
Views: 1331
Reputation: 7824
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.
Upvotes: 1
Reputation: 975
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.
Upvotes: 3
Reputation: 1801
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);
}
}
Upvotes: 2