+ 1
how to count lower integers java
Hi, this is my code that allows user to input number continously if the inputted value is lower than 5 and if number exceeds 5, it will print out "Program Terminated", However i want to edit this and count how many numbers that are lower than 5 were inputted. Can someone help me? import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner myInput=new Scanner(System.in); int num, a; for(a=0;a<=1;a++){ System.out.println("Enter a number:"); num=myInput.nextInt(); if(num > 5){ System.out.println("Program Terminated"); a+=1; } else{ a=0; } } } }
8 Respostas
0
Your program accept only 2 numbers less than 5 because for loop runs only for a =0,1 next a=2, then a<=1 false then loop exits..
only 1 number greater than 5, because a++ makes to a=1, and in next in loop increment a++ cause a=2 so then loop stop.
you can enter any number of 5's.because input 5,last else part get executed, and set a=0, so a++ cause a=1 a<=1 is true, so this way if you put 5, it will reset a=0.
If you want any number of inputs, remove loop condition a<=1. Put a break condition for loop when
if(input>5)
break;
If input <=5, then increment a counter
Try these n reply Clarrise
+ 3
.
.
.
.
int sum=0;
.
if(num<5)
++sum;
.
.
//now print sum.it will contains the sum of all nos inputted less than 5.
+ 3
U have to initialise sum to 0.
That is, int sum=0;
Otherwise it gives error.
+ 1
import java.util.Scanner;
public class Program
{
public static void main(String[] args) {
Scanner myInput=new Scanner(System.in);
int num, sum, a;
for(a=0;a<=1;a++){
System.out.println("Enter a number:");
num=myInput.nextInt();
if(num > 5){
System.out.println("Program Terminated");
a+=1;
}
else if( num < 5){
++sum;
System.out.println("Numbers inputted lower than 5:" + sum);
}
else{
a=0;
}
}
}
}
it says ++sum is not initialized
+ 1
is my code wrong?
+ 1
oh okay thank you!
+ 1
so this is the updated code, it works but it only accept two lower integers, for example if i put 4 and 3 it doesnt accept any numbers anymore and the process is terminated. What maybe is the problem?
import java.util.Scanner;
public class Program
{
public static void main(String[] args) {
Scanner myInput=new Scanner(System.in);
int num, a, sum = 0;
for(a=0;a<=1;a++){
System.out.println("Enter a number:");
num=myInput.nextInt();
if( num < 5){
++sum;
System.out.println("Numbers inputted lower than 5:" + sum);
}
else if(num > 5){
System.out.println("Program Terminated");
a+=1;
}
else{
a=0;
}
}
}
}
+ 1
it works now, thank you! ❤️