![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Newbie
|
im very new to JAVA i goot an assignment to write a program that is
take 3 boxes and it has "n" number of eggs after each box done with the counting it have to print the totel of it and after all 3 done max total have to print so far i done as below import java.util.*; class egg3{ public static void main(String args[]){ Scanner input=new Scanner(System.in); int x=1; int total=0; int t1=0; for(int j=0;j<3;j++){ System.out.println("Box 00"+(j+1)+""); while(x!=0){ System.out.print("Input egg wegiht "); x=input.nextInt(); total=total+x; } System.out.println("Total wegiht of the box : "+total); System.out.println(); t1=total+t1; } System.out.println("Grand Total :" +t1); } } this can enter any number of valus as u can see when we give "0" i stopes and print total ,but it wont continu to other 2 as well what shud i do ples explane ![]() |
|
|
|
|
|
#2 |
|
Expert Programmer
Join Date: May 2005
Location: East Lansing, MI
Posts: 663
Rep Power: 4
![]() |
Re: hay
Please use CODE tags next time.
You need to re-initialize x inside the for loop. The last zero read in is preventing the while loop from executing: (also initialize total if it's meant to be for each box) java Syntax (Toggle Plain Text)
|
|
|
|
|
|
#3 | |
|
Newbie
|
Ya it works and thank you very much for that
another thing as i know for loop doing rept what it got inside so i thought by puting while loop inside for loop it will repet until the for loops condition "yes" is that because when we hit "0"and stop the while loop then the compiler takes x value as "0" for the hole program Quote:
|
|
|
|
|
|
|
#4 |
|
Expert Programmer
Join Date: May 2005
Location: East Lansing, MI
Posts: 663
Rep Power: 4
![]() |
Re: hay
You got the right idea. In most high level languages, the value of a variable remain the same until explicitly changed, drops out of scope (when you're out of main()), or when the program exits. If x was zero the last time while() was executed, it will remain zero for the rest of the runtime (unless you re-initialize it like I did)
|
|
|
|
|
|
#5 |
|
Hobbyist Programmer
|
Re: hay
use white space formating like this. Use 4 spaces instead of tabs(set in editor), use tabs for inside methods, classes, if and loops. Place spaces between operands and operators. It makes the code more "human readable".
java Syntax (Toggle Plain Text)
__________________
i dont know much about programming but i try to help |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|