Hey, everyone. I am writing a program that I need to use the while loop for. I need to ask for the speed and number of hours traveled. It has to use a loop to display the distance the vehicle has traveled for each hour.
I need to show a chart after, like:
Hour Distance Traveled
I have gotten some of it so far, I just have no clue how to get the values appear with the chart. Thanks a ton!
Start by moving all that code out of the main method. A main method should contain 1 statement, ideally. Everything else should be written elsewhere.
I think it is possible to confuse yourself by trying too much. And I think you have managed that. I think you need to start small. Do one thing and one only. Try running at 40mph for 1hour and see whether you can get it to print 40miles. Then try going for 2 hours and getting it to print 40miles … 80miles. That will of course be in a loop which runs twice.
Don't use doubles if you can possibly avoid them. Use ints. That way you won't have to bother about whether you have driven for 2½hours and why it won't show 100miles. Also you can get horrible errors if you use floating‑point arithmetic to control loops. Example: Guess how often the following loop will run:-I shall give you a hint. If you look in the BigDecimal(double) constructor documentation, you find that the nearest double to 0.1 is very slightly higher than 0.1.
From your posted code, it looks like you want to print the table after the input is over. If that is true, you must collect the data.
You are using data pairs: speed and time. In doing so you have many options to follow as to how to declare your data collection base object, but you have a flagged exit in your collection, so you do not know how many times through the loops you will go, so you don't know how many of the data pairs you will need.
You can declare a data type that consists of 2 of your chosen data types, but I prefer to keep things as simple as possible, so I would think of an array--let's say you are using int as your base type. so
will give you a data pair of int--m and m. Since you do not know how many iterations through the loop you will do, you need to be able to save these off in a collection; I prefer to use an ArrayList to do so.
so after you collect your data in the loop in your array m and determine that you need to save it, then put it in your ArrayList before you loop again.
to print it out you will need to do something along this line, but format it as you need to do so:
Out on HF and heard nobody, but didn't call CQ? Nobody heard you either. 73 de N7GH
Why do you "need to use a while loop"? Generally, if you know exactly how many times you are going to loop, a for loop is preferred. Granted you can pretty much always use any of looping constructs...I just find it odd when anyone says "I have to do THIS using THIS".
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors