-4
import java.util.Scanner;
public class simple
 {


 public static void main(String args[]){

 double fnum , snum = 0,sum = 0;

 Scanner ip = new Scanner(System.in);
 System.out.println("enter the number:");
 fnum = ip.nextDouble();
 do{
     System.out.println("enter more numbers:");
     snum = ip.nextDouble();
      }
 while(fnum > 0);
 do{
         System.out.println("total number is:");
         sum = fnum + snum;
         }
 while(fnum ==0);
         }
}

It's not adding the input numbers.Ii want to run this using while(hasnext)?

Thanks for helping.

Balwinder Singh
  • 2,196
  • 5
  • 20
  • 32

2 Answers2

0

Well this is true because you are trying to set a number to a variable multiple times to snum. Also as far as I can see,

 do{
     System.out.println("enter more numbers:");
     snum = ip.nextDouble();
      }
 while(fnum > 0);

Should be an infinite loop. What is stopping the condinitional from running forever? You never alter fnum thereby it will run forever.

Im not sure how you want to handle fnum, however if this is what you are looking for then you can simpily subtract fnum by any amount in the loop which will prevent this infinite loop. Then now to fix changing the value of snum without overwriting it, create another var ans = 0. Now you can do:

 double ans = 0;
 do{
     System.out.println("enter more numbers:");
     snum = ip.nextDouble();
     ans += snum;
      }
 while(fnum > 0);
 System.out.println(ans); //This will produce the sum of all snum numbers
PsyCode
  • 574
  • 4
  • 12
0

I'm confused about what you're trying to do so clarification would help. If you're just trying to add numbers together and then print the total when the user has finished then something like this should work:

double sum;
while((newNum = readDouble())  != 0){ //entering 0 will stop the loop
  sum += newNum;
}
System.out.println("Total sum: " + sum);
private double readDouble(){
  System.out.println("Enter a number");
  return scanner.nextDouble();
}
Hatward
  • 62
  • 7