For-lups problem
I've made a program which calculates studensts' math and science scores.
In the program, I put name, scores of math and science, and then the code calculates sum, average of the scores, and their standings.
But I had a problem of standings.
import java.io.*;
class Scores
public static void main(String[] args) throws Exception
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int[] math = new int[3]; //an array of math score
int[] science = new int[3]; // an array of science score
int[] sum = new int[3]; //an array of sum
double[] avg = new double[3]; //an array of average
String[] name = new String[3]; //an array of students name
int[][] student = new int[3][3]; // an array of students
int[] num = new int[3]; // an array of number
int[] standing = new int[3]; //an array of students' standing
for (int i=0; i<student.length; i++)
System.out.print("Your name: ");
name=in.readLine(); // put your name here
System.out.print("Your Math grade: ");
math[i]=Integer.parseInt(in.readLine()); //put your math score here
System.out.print("Your Science grade: ");
science[i]=Integer.parseInt(in.readLine()); //put your science score here
sum[i]=math[i]+science[i];
avg[i]=sum[i]/2.0;
num[i]=i+1; // in order to put number from 1 to 3 to each student
for (int i=0; i<student.length; i++) // calculating students' standing
int rank=student.length; //rank starting with 3
for (int j=0; j<student[i].length; j++)
if(avg[i]>avg[j])
standing[i]=rank-1;
else if(avg[i]<=avg[j])
standing[i]=rank;
System.out.println();
for (int i=0; i<student.length; i++)
System.out.println("Number\tName\tMath\tScience\tSum\tAvg\tStanding");
System.out.println(num[i]+"\t"+name[i]+"\t"+math[i]+"\t"+science[i]+"\t"+sum[i]+"\t"+avg[i]+"\t"+standing[i]);
System.out.println();
The style of your code gives me the feeling that you are somewhat new to programming in general, so I'm going to give you some general debugging tips before actually answering your question.
The best way to find an error is to take some test data and go through the code yourself as if you were the computer and look at what it's actually doing (which may or may not be what you intended for it to do) at each step. I usually make a table of all the relevant variables, and fill in a new line each time any of them changes.
Here's the relevant portion of your code, cleaned up a bit (the missing [ i ]'s replaced, and tabs inserted in appropriate places) and line numbers added for reference.
1 for (int i=0; i<student.length; i++) // calculating students' standing
2 {
3 int rank=student.length; //rank starting with 3
4 for (int j=0; j<student.length; j++)
5 {
6 if(avg>avg[j])
7 {
8 standing[i]=rank-1;
9 }
10 else if(avg[i]<=avg[j])
11 {
12 standing[i]=rank;
13 }
14 }
15 }
at each step in the code, the variables I'll want to keep track of are:
i, name[ i ], avg[ i ], standing[ i ], rank, j, name[j], avg[j] (I included name[ i ] and name[j] just to make it easier to see which students we are talking about in each case. Technically, i and j would be sufficient.)
Let's say our three students' averages are as follows:
[0] John = 75
[1] Jane = 70
[2] Jim = 65
Let's skip straight to line 4 on our first iteration through the outer loop, our values are:
i = 0
name[i] = John
avg[i] = 75
standing[i] = 0
rank = 3
j = 0
name[j] = John
avg[j] = 75Since 75 <= 75, we skip straight to line 12:
i = 0
name[i] = John
avg[i] = 75
standing[i] = 3
rank = 3
j = 0
name[j] = John
avg[j] = 75Then go back to line 4:
i = 0
name[i] = John
avg[i] = 75
standing[i] = 3
rank = 3
j = 1
name[j] = Jane
avg[j] = 70Since 75 > 70, we go to line 8:
i = 0
name[i] = John
avg[i] = 75
standing[i] = 2
rank = 3
j = 1
name[j] = Jane
avg[j] = 70Back to line 4:
i = 0
name[i] = John
avg[i] = 75
standing[i] = 2
rank = 3 // note, rank has not been altered
// this is the root of the problem
j = 2
name[j] = Jim
avg[j] = 6575 > 65 so to line 8:
i = 0
name[i] = John
avg[i] = 75
standing[i] = 2 // since rank was never changed to reflect
// the comparison to Jane, the comparison
// to Jim is using the original value of 3,
// not 2 as you probably intended
rank = 3
j = 2
name[j] = Jim
avg[j] = 65Better would be:
1 for (int i=0; i<student.length; i++) // calculating students' standing
2 {
3 int rank=student.length; //rank starting with 3
4 for (int j=0; j<student.length; j++)
5 {
6 if(avg>avg[j])
7 {
8 rank--; // decrement rank here
9 }
10 }
11 standing[i]=rank; // once your final rank is established, assign it to standing
12 }
Other comments that might clean up your code a bit:
* I wouldn't use a separate variable where you have num -- just use i+1 directly wherever you would use it. (I only see one place it's even used.)
* A better overall design might be to create a Student class, with instance variables such as name, math, science, etc. and then create and use an array of Student objects, rather than keeping several parallel arrays. This has the added advantage that if your number of students changes, you only have to change the size of one array. (Keeping track of parallel arrays can be a royal pain in larger applications. You're better off getting out of the habit of using them early, IMO.)
* Do you really need to store both the sum and the average of the two scores? That seems a bit redundant to me. Storing the average might make it easier when you go to calculate ranks so you don't have to calculate it each time, but what is the advantage of keeping the sum around? When you print the report, you can just put (math + science) there. The only reason I could see to actually store sum would be for readability & efficiency if it's used in several different calculations, but here it's used exactly twice -- to calculate the average and to display it. If you were to create a separate student object, you could simply store the individual scores, and write methods to return the sum and average, then it could be transparent to the program whether you are actually storing the numbers or calculating them each time.
* In your final report, do you really want to put your column headers [i]inside your for loop? It makes more sense to me to print them once, before you enter the loop, rather than printing them for each student.
Lisa
Similar Messages
-
I've only had my iphone 5s for a week. I keep getting an error message of "Server has stopped responding." I need the server to work. Does anyone know if there is a "fix" for the problem? Other wise, I probably best return for a refund and get a Samsung. Thanks
sandyzotz wrote:
Other wise, I probably best return for a refund and get a Samsung.
Unlikely. Based on the complete lack of detail of the issue provided it is entirely possible the same issue would occur.
Unless and until the user provides some actual details of the problem, there is nothing the indicate that the issue is with the iPhone. -
My iPad (version 1, IOS 5.1) has quit connecting with the store. I am unable to update or buy any app. I did a reboot and a reset with deleting the data. I can not find anything in support for this problem. Any help will be appreciated.
My iPad (version 1, IOS 5.1) has quit connecting with the store. I am unable to update or buy any app. I did a reboot and a reset with deleting the data. I can not find anything in support for this problem. Any help will be appreciated.
-
I've searched to no avail for this problem. Similar posts but none that tell me what to do. I can't add or delete any bookmarks on my iPad 2 running the newest iOS. I know how it's suppose to work, it just isn't working!
It started after the major update to iOS 7.
I can't believe that this is so hard to do. It's just not letting me. I can add a bookmark to the home screen just fine, just not in a bookmarks folder anywhere I try.
I've used Apple products since 2001 and have always loved how intuitive they are. But the Safari browser since iOS 7 has been the worst I've experienced. At least right in the beginning after that update.
I'd really appreciate any help that doesn't just tell me how it's suppose to work...I know that.
My iPad 4 is not affected with the problem and works as it should.To delete, tap "Edit" (tap to enlarge image)
-
Can someonee please assist me in my Adobe Photoshop CS6 Extended. I keep getting a 'Couldn't Complete Your Request because Dynamic Link is not Available?" Is there a way of getting a software patch for this problem? I thought you didn't need extra software. My software other than that problem works fine.
Couldn't complete what request? Way more information please.
What operating system? -
My 500 GB can't verify nor repair. I have photoshop work that I need to recover. I would like to know what option would be the best solution for this problem?
You appear to have two issues: 1) a hard drive that is not working properly and 2) files you wish to recover.
Re 1) you need to answer Kappy's questions.
Re 2) does the drive load and can you see your photo files? If so can you copy them to another drive?
Do you not have a backup of the photo files? -
I have no service on my iphone 3gs. Is there a fix for this problem.
I have no service or no 3G Network on my iphone 3GS. Is there a fix from Apple for this problem.
Sometimes this happens to me, I know I am old school as well with an iPhone 3g hey what can I say I got a great deal on it. If I do a reboot, hold the power button and home button down for 10 seconds, and then hold the power button down until the apple logo appears it usually fixes this issue.
-
Help Me.
What is the best solution for this problem ?Encore is activated when you activate Premiere Pro... so, as Stan asked, how did you install P-Pro?
Ask for serial number http://forums.adobe.com/thread/1234635 has a FAQ link
-and a fix for Encore http://forums.adobe.com/thread/1421765?tstart=0 in reply #7
-plus more Encore http://helpx.adobe.com/encore/kb/cant-write-image-fie-larger1.html -
I can't get any contact info for installation problem- I just bought a Mac Air and my CS5 is asking for a reinstall. Mac Air has no DVD slots. HELP I al VERY FRUSTRATED THAT ADOBE HAS NO WAY TO GET HELP
You are right, Adobe does not support CS5 because it is no longer sold.
Simply download the trial version of CS5 from this Adobe web site and input your serial number.
Adobe - Photoshop : For Macintosh -
I bought my iphone 5 in Houston on May 15 2013.
IMEI 013428009645399.The problem I have is that in the country
which I live GREECE the 4G is
not working.Please if you have any solution for this
problem let me know.My email is [email protected]
Thanking you in advance
Philip CouridisiPhones purchased in the US are NOT guaranteed to work with 4G bands outside of North America.
For what crazy reason did you purchase an iPhone in the US if you live in Greece? If your phone needs servicing, it will have to be brought back to the US. You cannot get that phone serviced in Greece. -
Auto creation of notification for vendor problems
Hi, pls advise how to generate notificatin for vendor problems during goods receipt. can it be possible to generate automatically when there is problem for the vendor for the goods which are subjected to GR. Pls advise.
Hi Yadav,
pls advise how to generate notificatin for vendor problems during goods receipt.
While doing GR( which is stores activity) why you want to generate Notification, once GR is made the inspection lot is generated, then while doing RR if some thing is not as per specs then you can raise notification automatically.
can it be possible to generate automatically when there is problem for the vendor for the goods which are subjected to GR. Pls advise.
You will be able to generate auto notification only after you do GR, while doing RR. This authorization you can given to stores but again unless you inspect the material how you will know that there is problem in material and you need to raise notification.
for auto notification while RR, you have to assign notification type Q2/ N2 at that inspection type at customizing.
Also you should tick 'Defect recording' tab in control indicator of MIC's, this will automatically pop up the Window for defect recording and thereby notification.
Best Regards,
Shekhar -
I'm using Photoshop cc 2014.21 I you save for Web and dialog box comes up that says that Photoshop is using Latin characters and that servers cannot recognize Latin characters in webpages and you may have trouble viewing these pages does anyone have an answer for this problem?
What Firefox version is currently installed on the computer?
You can find the full version of the current current Firefox release (37.0.2) in all languages and all operating systems here:
*https://www.mozilla.org/en-US/firefox/all/
If you have a very old Firefox version then you could consider to uninstall that version to clean up existing registry keys (especial the uninstall key).
Make sure NOT to remove "personal data" when you uninstall Firefox, because that will remove all profile folders and you lose personal data like bookmarks and passwords including data in profiles created by other Firefox versions.
Check the Firefox program folder and remove the Firefox program folder if there are still files left in it.
*(32 bit Windows) "C:\Program Files\Mozilla Firefox\"
*(64 bit Windows) "C:\Program Files (x86)\Mozilla Firefox\"
It is important to delete the Firefox program folder to remove all the files and make sure that there are no problems with files that were leftover after uninstalling.
*http://kb.mozillazine.org/Uninstalling_Firefox
Your bookmarks and other personal data are stored in the Firefox profile folder and won't be affected by an uninstall and (re)install, but make sure NOT to remove personal data when you uninstall Firefox as that will remove all Firefox profile folders and you lose your personal data.
*http://kb.mozillazine.org/Profile_folder_-_Firefox
*http://kb.mozillazine.org/Profile_backup
*http://kb.mozillazine.org/Standard_diagnostic_-_Firefox#Clean_reinstall -
What is the best design pattern for this problem?
No code to go with the question. I am trying to settle on the best design pattern for the problem before I code. I want to use an Object Oriented approach.
I have included a basic UML diagram of what I was thinking so far.
Stated simply, I have three devices; Module, Wired Modem, and Wireless Modem.
In the Device Under Test parent class, I have put the attributes that are variable from device to device, but common to all of them.
In the child classes, I have put the attributes that are not variable to each copy of that device. The attributes are common across device types. I was planning to use controls in the class definition that have the data set to a default value, since it doesn't change for each serial number of that device. For example, a Module will always have a Device Type ID of 1. These values are used to query the database.
An example query would be [DHR].[GetDeviceActiveVersions] '39288', 1, '4/26/2012 12:18:52 PM'
The '1' is the device type ID, the 39288 is the serial number, and the return would be "A000" or "S002", for example.
So, I would be pulling the Serial Number and Device Type ID from the Device Under Test parent and child, and passing them to the Database using a SQL string stored in the control of the Active Versions child class of Database.
The overall idea is that the same data is used to send multiple queries to the database and receiving back various data that I then evaluate for pass of fail, and for date order.
What I can't settle on is the approach. Should it be a Strategy pattern, A Chain of Command pattern, a Decorator pattern or something else.
Ideas?elrathia wrote:
Hi Ben,
I haven't much idea of how override works and when you would use it and why. I'm the newest of the new here.
Good. At least you will not be smaking with a OPPer dOOPer hammer if I make some gramatical mistake.
You may want to look at this thread in the BreakPoint where i trie to help Cory get a handle on Dynamic Dispatching with an example of two classes that inherit from a common parent and invoke Over-ride VIs to do the same thing but with wildly varying results.
The example uses a Class of "Numeric" and a sibling class "Text" and the both implement an Add method.
It is dirt simple and Cory did a decent job of explaining it.
It just be the motivation you are looking for.
have fun!
Ben
Ben Rayner
I am currently active on.. MainStream Preppers
Rayner's Ridge is under construction -
I use dial-up, FireFox 5.0, Yahoo addition 1.8. My screen load times have slowed down to a crawl. I have to wait and wait for a page to load. (I know --dial -up) It used to be much faster a month ago before 5.0. Is it FireFox or do I look to Yahoo for the problem? I don't know how to sort it out. Using Vista
I'm having the same problem. Dreamweaver is supper slow. Uploading and downloads from the server... any server I use two different servers. It times out all the time. Menus are slow too.
I'm on a MAC Pro, 6 gigs of ram no issues with anything else. I have talked to Apple they have checked everything for me. They say it's Dreamweaver. I've noticed the Dreamweaver is talking to the FTP even when I'm not doing anything.
I've tried cleaning out my MAC caches, turning off file check and check out. Still really slow. I've worked with Dreamweaver for 6 years never any issues like this before. 18 seconds to upload a 4 kb file. 11 seconds to download the same file. -
When I open ITunes, I get a message that "iTunes has stopped working". I have tried reinstalling iTunes, creating a new user file, changing the startup programs in accordance with articles in iTunes troubleshooting, but am having no success in getting iTunes to stay open. Any fixes for this problem?
Maybe you are looking for
-
Error in RFC Receiver Adapter: functiontemplate from repository was null
Hi Friends, i am working on JDBC -> RFC Scenario, JDBC Sender Adapter is working fine, but RFC Receiver Adapter is throwing this error message... can some one help me to solve this issue... Message processing failed. Cause: com.sap.aii.af.ra.ms.api.R
-
Pivot chart vertical axis label show percentage
Hi All, I have a pivot chart showing percentage of the row. the vertical axis label can only show 0, 1, 2; I change it to specify value with 'Minimum' 0 and 'Maximum' 1. Wondering how to show vertical axis label with minimum 0% and maximum 100%, inst
-
From U.S. to Sweden Power Box Question
Hello! My wife and I will soon be moving to Sweden. I currently have the 2.4 GHz late 2008 Unibody MacBook Pro and my wife will be buying one of her own pretty soon. So, naturally, we'd like to take them with us and purchase the correct adapters for
-
I just installed the Palm Desktop 6.2. When working at my computer in the software, if I click on DAY, WEEK, or YEAR view it's fine. But if I click on MONTH it craps out and the software closes up. This is error detail: AppName: palm.exe AppVer: 6.2.
-
Can anyone help me with a bit of script modifying?
Hey guys, can anyone help me? Here is some script that makes my character obviously move and detects walls. I would like to modify the script so that when my character hits the right keydown, the sprite changes to cast member "right". I have tried an