3rd Jun 2017, 5:17 PM
Captainnn_
Captainnn_ - avatar
5 Réponses
+ 1
Are you ONLY trying to find the sum of all the numbers the user inputs? Cause if not, I can't really tell. Saying "correct my code" can mean a number of things. If you are trying to find the sum It's best to use an array here, otherwise, you are just going to be doing something like this: sum = no1 + no2 + no3 ...etc. Note* Only if you want to keep track of what each input is. What is the variable "no" supposed to do anyway?
3rd Jun 2017, 5:40 PM
Rrestoring faith
Rrestoring faith - avatar
+ 1
I'm not sure how you want to go about doing this, but if you are only getting the sum you can do something like this: final int NUM_INPUTS = 5; int sum = 0; for(int i = 0; i < NUM_INPUTS; i++) { sum = sum + input.nextInt(); } That will get the sum of everything the user inputs. If you want to use an array to keep track of what the user inputs: int array = new int[NUM_INPUTS]; Then in the for loop written above you'd have this instead: array[i] = input.nextInt(); Now you can calculate the sum: for(int i = 0; i < array.length; i++) sum = sum + array[i];
3rd Jun 2017, 5:44 PM
Rrestoring faith
Rrestoring faith - avatar
0
check this import java.util.Scanner; public class Program{ public static void main(String[] args) { Scanner input = new Scanner(System.in); int no1, no2, no3, no4, no5; System.out.println("Put the first number :"); no1 = input.nextInt(); System.out.println("Put the second number :"); no2 = input.nextInt(); System.out.println("Put the third number :"); no3 = input.nextInt(); System.out.println("Put the fourth number :"); no4 = input.nextInt(); System.out.println("Put the fifth number :"); no5 = input.nextInt(); int [] arr = {no1,no2,no3,no4,no5}; int sum = 0; int count = 0; do{ System.out.println("Number " +count+" : "+arr[count]); sum = sum+arr[count]; count = count+1; }while(count<5); System.out.println("The sum of these numbers is : "+sum); } } variable no was not declared so i replaced it with array element then the count should start from 0 to 4
3rd Jun 2017, 5:34 PM
ASHMIL HUSSAIN
ASHMIL HUSSAIN - avatar
0
import java.util.Scanner; public class Program{ public static void main(String[] args) { Scanner input = new Scanner(System.in); int n,s=0; System.out.println("Enter the numbers :"); while(input.hasNextInt()) { n= input.nextInt(); s+=n; } System.out.println("sum :"+s); } } this code will give u some of all integers in input. number of inputs doesn't matter.
3rd Jun 2017, 5:53 PM
ASHMIL HUSSAIN
ASHMIL HUSSAIN - avatar
0
okey
3rd Jun 2017, 5:55 PM
ASHMIL HUSSAIN
ASHMIL HUSSAIN - avatar