
If someone could look over this code i wrote and see if its done correctly i would greatly appreciate it.. i use netbeans and when i click "run" the ms dos window doesn't come up and run the program like dev c does for c++
its supposed to ask for integers and add'em up and give a sum at the end, it shouldn't accept negative integers.
import java.util.Scanner;
public class Main
{
/** Creates a new instance of Main */
public Main()
{
}
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
// TODO code application logic here
Scanner input = new Scanner( System.in );
int hold, sum,option,count;
sum = 0;
do
{
count = 0;
hold = 0;
System.out.print("Please enter non-negative integer to be added: ");
hold = input.nextInt();
while(hold<0)
{
System.out.print("That number is negative, please enter another one");
hold = input.nextInt();
}
sum = hold + sum;
System.out.print("Do you wish to add another integer?(1 - yes 2 - no: ");
option = input.nextInt();
count = count +1;
}while(option == 1);
System.out.printf("The sum of the ", count,"integer(s) is ", sum);
}
}Offline
xreddawg909x wrote:
If someone could look over this code i wrote and see if its done correctly i would greatly appreciate it.. i use netbeans and when i click "run" the ms dos window doesn't come up and run the program like dev c does for c++
its supposed to ask for integers and add'em up and give a sum at the end, it shouldn't accept negative integers.Code::
import java.util.Scanner; public class Main { /** Creates a new instance of Main */ public Main() { } /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner input = new Scanner( System.in ); int hold, sum,option,count; sum = 0; do { count = 0; hold = 0; System.out.print("Please enter non-negative integer to be added: "); hold = input.nextInt(); while(hold<0) { System.out.print("That number is negative, please enter another one"); hold = input.nextInt(); } sum = hold + sum; System.out.print("Do you wish to add another integer?(1 - yes 2 - no: "); option = input.nextInt(); count = count +1; }while(option == 1); [b]System.out.printf("The sum of the ", count,"integer(s) is ", sum);[/b] } }
Please try replacing bold line with below.
System.out.println("The sum of the "+ count+" integer(s) is " + sum);
Do let me know if this works.
Thanks
Sachin
Offline