+ 1

Pls help me to solve this :( plssss

write a program that reads integers until a non-positive integer is entered . for each integer x. the program read x real valued numbers and find their sum. sample run: enter 4 integers and terminate by non-positive:4 enter 4 real numbers: 4.5 5.25. -1 2 sum =10.75 2) enter 2 real numbers : -3 9.5 sum = 6.5

25th Oct 2017, 5:11 PM
Tudes Mubarak
Tudes Mubarak - avatar
2 Réponses
+ 2
while(true) will create an inf loop for us, that way we can continue to get input until we receive the negative value to exit. After you receive input, but before you print/do calculations, have it check if the input was negative and if it was, break the loop. Example / code below: https://code.sololearn.com/czE0p9L1VRys/#java import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); int sum = 0; int num = 0; while(true) { System.out.println("Please enter number (negative to exit): "); num = scnr.nextInt(); if(num < 0){ System.out.println("Negative entered. Exiting..."); break; } System.out.print("" + sum + " + " + num + " = "); sum += num; System.out.println(sum); } } }
25th Oct 2017, 5:46 PM
AgentSmith
0
using loops
25th Oct 2017, 5:24 PM
Tudes Mubarak
Tudes Mubarak - avatar