Java Forum / First Aid / December 2005
read keyboard input and storing in an array?
guitarromantic@gmail.com - 25 Nov 2005 17:10 GMT Hey all, New to this, so apologies for the presumably basic question:
I'm trying to store user input in an array, marks. Here's my [cut down] code:
public class MarksDatabase { private int marks[];
public MarksDatabase(String moduleName) { int[] marks = new int[200]; }
public static void readMarks() { Scanner keyboard = new Scanner(System.in); System.out.println("Enter marks, then put -1 blah blah"); marks[] = keyboard.nextInt(); }
I get an error with the keyboard.nextInt part. I've probably misunderstood my instructions, but can anybody explain to me where I'm going wrong?
Matt
Rhino - 25 Nov 2005 18:04 GMT > Hey all, > New to this, so apologies for the presumably basic question: [quoted text clipped - 19 lines] > misunderstood my instructions, but can anybody explain to me where I'm > going wrong? First of all, it's a lot easier to help with an error situation if you specify the exact error message you are getting; you have only said that you get an error but not which one.
Second, your logic seems to trying to read in 200 integers in a single gulp, 200 integers that the user has typed in a single logical line of input. (Obviously, the input would wrap to new lines as you typed the 200 different values, followed by the -1 to indicate the end of the input, but Java would treat it all as one big chunk of input.) That is _not_ what the average programmer would do.
A common way to process large numbers of input values is in a loop. Each iteration of the loop would prompt for *one* value, read the value from the input stream somehow, and store the value. The loop would usually terminate when it had read all of the data it needed. In your case, you seem to want exactly 200 values, no more, no less so you could simply execute the loop exactly 200 times until you had all of the values. However, it would be better (in my opinion) to make the program more flexible in case you had situations in which the number of grades to be read was not precisely 200. You have the beginnings of that logic already since your prompt tells the user to enter -1 when they have no more data to input. Assuming you want that flexibility, why don't you try to rewrite the code so that it is prompting for data in a loop and stops when the value -1 is supplied?
That causes one complication though: if the user ever wants to input more than 200 values, the program will have an error when it tries to store the 201st value since the array only has room for 200 values. You can get around that in a few ways: - make the array big enough to hold the largest conceivable number of values that you can ever imagine anyone giving your program. Perhaps that is 250 values, perhaps it is 50 million. (I don't recall if there is a maximum size for an array so it is possible that you could pick a size that is too big to compile but if that happens, there should be a clear compile message telling you what happened. If you get that message, just use a smaller size for the array to prevent the error message.) - use a structure that is not fixed in size, like a Vector, instead of an int array. This will force you to store the int values as Integer ('Integer' is a wrapper class. A wrapper class enables you to store primitives like ints in Objects which can then be stored in structures like Vectors or collections.) You will also need to convert the Integer back to int when you get it back out of the Vector. The good news is that converting from int to Integer and back again is very easy. - write the loop so that it stops when the input is -1 _OR_ you are at the maximum size of the array. That way, you can store a very small number of values or any number of values up tol 200 but no more. That is probably the solution I would suggest at your stage with Java; it should make the program sufficiently flexible to impress your teacher slightly.
One other thing you need to consider is the type of data that keyboard.nextInt() returns to your program. I think someone posted a code fragment using the Scanner class before (you? one of your classmates?); as I recall it is not a class from the standard Java API. That is probably okay for teaching purposes, although I frown on showing students non-standard classes, but it means that you need to find the API that your teacher is using and find out what keyboard.nextInt() is returning. From the method name, I assume it is an int but you should make sure of that. If it isn't returning an int, you will need to convert whatever it gives you into an int so that you can store it in the array. (Or change the array so that it contains whatever keyboard.getInt() returns!) Otherwise, you'll get an error if you try to shove a non-int into an int array.
Why don't you try changing the code along the lines I've suggested and see how it goes. If you have problems, post back to the same thread and someone here will probably help you.
The third and final thing I'm going to say is probably too advanced for you to appreciate at this stage and I'm not suggesting you act on it. I'm simply mentioning it to make you think about design issues. That is a good practice to get into for when you are writing "real" programs.
Basically, I don't think you'd ever see a professional program prompt a user for 200 different values from a command line. Not even one value at a time, let alone 200 in one gulp! If I were writing a professional program and wanted to get that much data from someone, I'd probably use a GUI so that I could give them an input form of some kind for the data. That might mean writing a GUI in a Java application or applet or it might mean using an HTML form in a servlet. Other possibilities also exist, like Struts or other "frameworks" that are intended for this purpose.
The other common approach to this situation would be for the marks to be written to a file or database via some process or another; then your program would simply read the file or database without having to prompt the user for anything. Of course, the process that wrote the file in the first place would probably prompt the user for the marks somewhere along the line but that might not be _your_ problem in the real world :-)
As your course proceeds, you may learn something about these professional techniques; if not, maybe a future course or some self-study on your part will show you these approaches. But don't sweat this too much right now; you are still learning basics and you can learn these other techniques when the time comes.
But it's never too early to start thinking like a professional designer, even if you can't build professional quality components yet :-)
Rhino
guitarromantic@gmail.com - 26 Nov 2005 23:37 GMT Thanks for the very informative post, it was worth waiting for (I didn't see this message appear for a couple of days, oddly enough..).
I should have been a little more diligent in my post: I didn't intend to let the user enter 200 values, haha. The spec for our work said allow up to 200 values to be entered, and I fully intend to do this in a loop, where the user can cancel it at any time by entering -1 (as the spec demands). Call my sloppy code above the product of being frustrated..
As for the Scanner class, it probably was me posting it. That's what we're being told to use, so I have to stick with it.
So I return to my original problem. When in a loop, how do I simply tell Java to store the next user-inputted integer in value [x] of an array?
Rhino - 28 Nov 2005 00:49 GMT > Thanks for the very informative post, it was worth waiting for (I > didn't see this message appear for a couple of days, oddly enough..). [quoted text clipped - 12 lines] > tell Java to store the next user-inputted integer in value [x] of an > array? That's not the easiest question to answer since I don't have access to the API for your Scanner class. I *think* Scanner is probably just your instructor's way of avoiding this, which is what I would use in my own programs:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Then, the BufferedReader instance, br, would do this to read in a line of text:
String input = br.readLine();
The data returned by 'br.readLine()' would always be a String so I've stored it in a String called 'input'. Since I want to store an integer, I would simply convert it to an int as follows:
int myInt = Integer.parseInt(input);
Then, you could copy 'myInt' to your array. (Of course, you could combine several steps at once into a single, more complex line of code so that the value obtained by readLine() was immediately converted from String to int and then stored in the array.
But you don't use the standard techniques: instead, you teacher is showing you homemade techniques that you won't see in the real world. He/she is definitely not doing you a favour, at least in my opinon.
For your situation, the code should be pretty much what you already have:
Scanner keyboard = new Scanner(System.in); System.out.println("Enter an integer test score or -1 to quit."); int ix = 4; marks[ix] = keyboard.nextInt();
All I really added was the index within the square brackets on the fourth line so that Java knows which entry of the array to use for your input. Of course, when you write your loop, you will not simply assign '4' to 'ix'; you will set 'ix' equal to the value of your loop counter so that it increments on each time through the loop.
Try coding it along the lines I've suggested and post again if you have problems. But be sure to include the actual error message you are getting, not just the fact that you are getting an error. You still haven't said what error you are getting so I'm going to assume you got a compile error on the 'marks[] = keyboard.nextInt();' line and the message said something about invalid syntax.
Rhino
blmblm@myrealbox.com - 28 Nov 2005 10:45 GMT [ snip ]
>> As for the Scanner class, it probably was me posting it. That's what >> we're being told to use, so I have to stick with it. [ snip ]
>That's not the easiest question to answer since I don't have access to the >API for your Scanner class. Actually, you probably do. Check the 5.0 / 1.5 Java API.
[ snip ]
| B. L. Massingill | ObDisclaimer: I don't speak for my employers; they return the favor. Rhino - 28 Nov 2005 20:05 GMT > [ snip ] > [quoted text clipped - 9 lines] > > [ snip ] I stand corrected!
The last time someone posted a fragment using the Scanner class, a few weeks ago, other people complained that it was not a standard class so I just assumed that was correct. I'd never heard of the Scanner class myself and I hadn't noticed it in the API before you pointed it out. You're absolutely right; it is a standard class and just came into existence with 1.5. My respect for the original poster's teacher just went up several notches ;-)
Rhino
guitarromantic@gmail.com - 29 Nov 2005 22:30 GMT Okay, I modified stuff, but I still get a nasty error when running (but not compiling) this method:
public static void readMarks() {
for (int numOfMarks = 0; numOfMarks < 5; numOfMarks++) { System.out.println("Enter marks, then enter -1 when complete."); Scanner keyboard = new Scanner(System.in); marks[numOfMarks] = keyboard.nextInt(); } }
Error is displayed as soon as I input anything and press enter.
InputMismatchException: at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at MarksDatabase.readMarks(MarksDatabase.java:37) at MarksDatabase.main(MarksDatabase.java:43) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source)
IchBin - 29 Nov 2005 23:34 GMT > Okay, I modified stuff, but I still get a nasty error when running (but > not compiling) this method: [quoted text clipped - 22 lines] > at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) > at java.lang.reflect.Method.invoke(Unknown Source) The important part is not in your sample. How is your marks field defined. If it is not the right type, say String[], then you will get this error message. Scanner wants to write to an int.
 Signature Thanks in Advance... IchBin, Pocono Lake, Pa, USA http://weconsultants.servebeer.com/JHackerAppManager __________________________________________________________________________
'If there is one, Knowledge is the "Fountain of Youth"' -William E. Taylor, Regular Guy (1952-)
IchBin - 29 Nov 2005 23:40 GMT > Okay, I modified stuff, but I still get a nasty error when running (but > not compiling) this method: [quoted text clipped - 22 lines] > at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) > at java.lang.reflect.Method.invoke(Unknown Source) The important part is not in your sample. How is your marks field defined. If it is not the right type you will get tis message. Scanner wants to write to an int else
 Signature Thanks in Advance... IchBin, Pocono Lake, Pa, USA http://weconsultants.servebeer.com/JHackerAppManager __________________________________________________________________________
'If there is one, Knowledge is the "Fountain of Youth"' -William E. Taylor, Regular Guy (1952-)
IchBin - 29 Nov 2005 23:50 GMT > Okay, I modified stuff, but I still get a nasty error when running (but > not compiling) this method: [quoted text clipped - 22 lines] > at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) > at java.lang.reflect.Method.invoke(Unknown Source) Scanner wants to write an int else you see this error. Run the program and input a 1 then input an A.
 Signature Thanks in Advance... IchBin, Pocono Lake, Pa, USA http://weconsultants.servebeer.com/JHackerAppManager __________________________________________________________________________
'If there is one, Knowledge is the "Fountain of Youth"' -William E. Taylor, Regular Guy (1952-)
Roedy Green - 30 Nov 2005 00:07 GMT On 29 Nov 2005 14:30:00 -0800, "guitarromantic@gmail.com" <guitarromantic@gmail.com> wrote, quoted or indirectly quoted someone who said :
> marks[numOfMarks] Please post COMPLETE code. Then we can see the declarations and we can compile and run.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
guitarromantic@gmail.com - 30 Nov 2005 14:10 GMT I think I figured it out, my instructions are causing issues. Here's the first part of the code (originally):
import java.util.*;
public class MarksDatabase { private static String moduleName; private static int size; private static int marks[];
public MarksDatabase(String mod) { int[] marks = new int[200]; }
I was told to define the marks array within MarksDatabase, but if I move it up and make it an instance variable the code posted above works fine. This is odd, it's possible I've misunderstood the instructions. Every post I make here makes me feel 12% more stupid :(
guitarromantic@gmail.com - 30 Nov 2005 23:00 GMT Okay, an update. I've progressed a little, but my main issue now has changed, as ever.
Here's my readMarks method:
public static void readMarks() {
for (int numOfMarks = 0; numOfMarks < 200; numOfMarks++) { String gradeString; gradeString = JOptionPane.showInputDialog ("Enter the exam grades:");
//parse string into integer marksPreTest = Integer.parseInt(gradeString);
if (marksPreTest >= 0 && <= 100) //"illegal start of expression" at the < symbol { size++; }
else { System.out.println("Invalid entry"); } } }
Besides that, the class starts with the code in the above post (with an import of the Swing package - this is defined in my spec as gaining 'excellent', rather than using Scanner).
What's wrong with my code?
Chris Smith - 30 Nov 2005 23:35 GMT > if (marksPreTest >= 0 && <= 100) > //"illegal start of expression" at the < symbol You're using the logical && operator. To do so, you need something of this form:
if (expr && expr)
where each "expr" is replaced by a complete expression that evaluates to either true or false. On the left hand side, you've provided "marksPreTest >= 0", which is indeed complete and evaluates to true or false.
On the right side, though, you have "<= 100". That's not a complete expression! What would you expect from:
if (<= 100) ...
Obviously, this won't compile. Putting the same expression into a logical and operation doesn't fix anything.
So, how to fix this? Easy. Just write this (my added parentheses are unnecessary and ignored by the compiler, but help make things clearer):
if ((marksPreTest >= 0) && (marksPreTest <= 100))
 Signature www.designacourse.com The Easiest Way To Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer MindIQ Corporation
Roedy Green - 30 Nov 2005 23:48 GMT On 30 Nov 2005 15:00:46 -0800, "guitarromantic@gmail.com" <guitarromantic@gmail.com> wrote, quoted or indirectly quoted someone who said :
> //parse string into integer > marksPreTest = Integer.parseInt(gradeString); [quoted text clipped - 4 lines] > size++; > } 1. you have a counted loop. I strongly doubt you know ahead of time how many marks are coming. You should be using a while loop with some sort of end of file Exception.
2. You get marksPreTest but do nothing with it. You should be storing it in an array or ArrayList or at least printing it out.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
guitarromantic@gmail.com - 02 Dec 2005 13:50 GMT Roedy:
1. My specification states to allow for 200 marks maximum. I've rewrote this now to break the loop should the user enter less.
2. Yeah, that was my intention.
I've rewritten the entire method after an elightening lecture this morning. I still get a compile error, though:
"Error: non-static variable marks cannot be referenced from a static context"
Here's the method:
public static void readMarks() { int inputMark; Scanner input = new Scanner(System.in);
//allow 200 possible loops for (int i = 0; i < 200;) {
//if the user finishes before 200, break the loop if (!input.hasNextInt()); break;
int inputMarks = input.nextInt();
//as long as the input is between 0 and 100, store it in the array if ((inputMark >= 0) && (inputMark < 100)) { marks[i] = inputMark; ++i; } }
}
The marks array is defined in the instance variables/constructor, correctly (I'm pretty sure). Why can't I assign my value to it?
Matt
Roedy Green - 02 Dec 2005 18:28 GMT On 2 Dec 2005 05:50:27 -0800, "guitarromantic@gmail.com" <guitarromantic@gmail.com> wrote, quoted or indirectly quoted someone who said :
>The marks array is defined in the instance variables/constructor, >correctly (I'm pretty sure). Why can't I assign my value to it? For the second time, please post complete code. I can't diagnose the problem with marks without seeing how you declared it.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
guitarromantic@gmail.com - 02 Dec 2005 20:14 GMT Sorry. Here's the entire class:
/** * Stores all marks */ import java.util.*; import javax.swing.*;
public class MarksDatabase { //define instance variables private String moduleName; private int size; private int[] marks;
//constructor public MarksDatabase(String name) { moduleName = name; size = 0; marks = new int[200]; }
//display module name public String getModuleName() { return moduleName; }
//display # of marks in array public int getSize() { return size; }
//display mark X public int getMark(int mark) { return marks[mark]; }
public static void readMarks() { int inputMark; Scanner input = new Scanner(System.in);
//allow 200 possible loops for (int i = 0; i < 200;) {
//if the user finishes before 200, break the loop if (!input.hasNextInt()); break;
inputMark = input.nextInt();
//as long as the input is between 0 and 100, store it in the array if ((inputMark >= 0) && (inputMark < 100)) { marks[i] = inputMark; ++i; } } } }
Roedy Green - 02 Dec 2005 20:42 GMT On 2 Dec 2005 12:14:00 -0800, "guitarromantic@gmail.com" <guitarromantic@gmail.com> wrote, quoted or indirectly quoted someone who said :
>Sorry. Here's the entire class: Where is the main method?
Where do you ever construct a MarksDatabase object?
readMarks can't be static since it accesses the instance variable marks[]
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
guitarromantic@gmail.com - 02 Dec 2005 21:41 GMT As per my instructions, I haven't written the main method yet, I've been told to run commands in DrJava's Interactions tab (effectively acting as a main method) to create the objects.
If I make readMarks non static, I get an error for this line:
inputMark = input.nextInt();
"Error: unreachable statement"
Roedy Green - 02 Dec 2005 22:46 GMT On 2 Dec 2005 13:41:24 -0800, "guitarromantic@gmail.com" <guitarromantic@gmail.com> wrote, quoted or indirectly quoted someone who said :
>If I make readMarks non static, I get an error for this line: > > inputMark = input.nextInt(); Since you have no static variables, it is unlikely any of your methods should be static.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
guitarromantic@gmail.com - 03 Dec 2005 01:41 GMT Okay, I understand that, but why is that line causing problems? Do I need to define inputMark as an instance variable?
Roedy Green - 03 Dec 2005 03:16 GMT On 2 Dec 2005 17:41:33 -0800, "guitarromantic@gmail.com" <guitarromantic@gmail.com> wrote, quoted or indirectly quoted someone who said :
>Okay, I understand that, but why is that line causing problems? Do I >need to define inputMark as an instance variable? Your basic problem is you don't understand the difference between instance and static. You are just wildly guessing. See http://mindprod.com/jgloss/instance.html http://mindprod.com/jgloss/static.html http://mindprod.com/jgloss/scope.html
and follow the links.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
guitarromantic@gmail.com - 04 Dec 2005 20:30 GMT Okay, I've gone away and tried to figure out where I've been going wrong, and I think I've gained a little insight.. perhaps. I've progressed on my code, and Roedy; I now have a seperate class with a main method that does all of the testing work on the first class.
My problem is as such: I'm writing a method to calculate averages for two objects being stored in an array. The first average returned is just wrong, the second comes out blank. Knowing me, this is going to be something fundamental..
When I print out the size of the two arrays, one is 11 (should be 10 with my test data) and the other is 0. Here's my code:
/** * Stores all marks */ import java.util.*; import javax.swing.*;
public class MarksDatabase { //define instance variables private String moduleName; private int size; private int[] marks; private int gradeLimit = 200;
//constructor public MarksDatabase(String name) { moduleName = name; size = 0; marks = new int[200]; }
//display module name public String getModuleName() { return moduleName; }
//display # of marks in array public int getSize() { return size; }
//display mark X public int getMark(int mark) { return marks[mark]; }
public void readMarks() { int inputMark; int index = 0;
//create JOptionPane String gradeString; gradeString = JOptionPane.showInputDialog ("Enter the exam grades");
//Scanner to extract marks Scanner scanner = new Scanner(gradeString);
//while the scanner still has numbers and there are below 200 items in the array while (scanner.hasNextInt() && index < gradeLimit) {
//set inputMark to the next integer entered inputMark = scanner.nextInt();
//as long as the input is between 0 and 100, store it in the array if ((inputMark >= 0) && (inputMark <= 100)) { marks[index] = inputMark; index++; size++; } } }
public String toString() { //if there aren't any numbers in the array, display <no data> if (size == 0) return ( getModuleName() + ": <no data>");
//create the stringbuilder and add a colon after the module name StringBuilder builder = new StringBuilder(); builder.append(getModuleName() + ":");
//display the marks with spaces in between for (int i = 0; i < size; ++i) { builder.append(" "); builder.append(marks[i]); } return builder.toString(); }
public double findMean() { System.out.println("Size = " + size); double total = 0; double mean;
//if there's no marks, display 0.0 if (size == 0) { return 0.0; } else { for (int i = 0; i <= size; i++) //for all the marks { total = total + marks[i]; //add them onto total } mean = total / size; //divide total by size of the array return mean; } } }
--------------------------------
import javax.swing.*;
public class MarksTest { public static void main(String[] args) { MarksDatabase db1 = new MarksDatabase("SE15"); db1.readMarks();
MarksDatabase db2 = new MarksDatabase("IS11"); db1.readMarks();
double db1Mean = db1.findMean(); double db2Mean = db2.findMean();
System.out.println(db1Mean); System.out.println(db2Mean); } }
Roedy Green - 04 Dec 2005 21:16 GMT On 4 Dec 2005 12:30:32 -0800, "guitarromantic@gmail.com" <guitarromantic@gmail.com> wrote, quoted or indirectly quoted someone who said :
> MarksDatabase db1 = new MarksDatabase("SE15"); > db1.readMarks(); > > MarksDatabase db2 = new MarksDatabase("IS11"); > db1.readMarks(); I detect a lack of symmetry.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
guitarromantic@gmail.com - 04 Dec 2005 21:34 GMT This is what I get for copy and pasting.. damn!
IchBin - 04 Dec 2005 22:15 GMT > This is what I get for copy and pasting.. damn! Consider putting a for loop around your JOptionPane.showInputDialog and Scanner scanner = new Scanner(gradeString); logic.
 Signature Thanks in Advance... IchBin, Pocono Lake, Pa, USA http://weconsultants.servebeer.com/JHackerAppManager __________________________________________________________________________
'If there is one, Knowledge is the "Fountain of Youth"' -William E. Taylor, Regular Guy (1952-)
guitarromantic@gmail.com - 04 Dec 2005 22:22 GMT The original iteration was like this, but further reading of my spec said that when using JOptionPane, grades would be entered as a single string ("12 34 67 85" etc) and then parsed using Scanner.
IchBin - 04 Dec 2005 22:32 GMT > The original iteration was like this, but further reading of my spec > said that when using JOptionPane, grades would be entered as a single > string ("12 34 67 85" etc) and then parsed using Scanner. Sorry, I should have not butted in..
 Signature Thanks in Advance... IchBin, Pocono Lake, Pa, USA http://weconsultants.servebeer.com/JHackerAppManager __________________________________________________________________________
'If there is one, Knowledge is the "Fountain of Youth"' -William E. Taylor, Regular Guy (1952-)
Roedy Green - 05 Dec 2005 00:22 GMT On 4 Dec 2005 13:34:16 -0800, "guitarromantic@gmail.com" <guitarromantic@gmail.com> wrote, quoted or indirectly quoted someone who said :
>This is what I get for copy and pasting.. damn! you mean for NOT copying and pasting?
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
guitarromantic@gmail.com - 05 Dec 2005 15:05 GMT No..? I just copied these lines:
MarksDatabase db1 = new MarksDatabase("SE15"); db1.readMarks();
And obviously forgot to change the readMarks reference on the second line.
guitarromantic@gmail.com - 05 Dec 2005 18:39 GMT Next problem..
I've written findMinimum (and Maximum) methods to do, well, just that. The Maximum one works fine; the minimum is just returning 0. Here's the code for findMinimum:
private int minValue = Integer.MAX_VALUE;
.... //more code
public int findMinimum() { int min = 0; for (int i = 0; i < size; i++) { if (marks[i] < minValue) min = marks[i]; } return min; }
My test data for the array is just "1, 2, 3, 4", and the size variable is the recorded size of the array so it shouldn't be including null values in the array - where am I going wrong?
Just wanted to add thanks for all the assistance, I'm very grateful and I hope you guys don't think too badly of me for all these problems.
Matt
Roedy Green - 05 Dec 2005 19:18 GMT On 5 Dec 2005 10:39:10 -0800, "guitarromantic@gmail.com" <guitarromantic@gmail.com> wrote, quoted or indirectly quoted someone who said :
> int min = 0; > for (int i = 0; i < size; i++) > { > if (marks[i] < minValue) > min = marks[i]; Put a comment on your declaration for min describing what it is for. Put a comment on your declaration for minValue describing what it is for.
That will lead you inevitably to the solution to you problem.
So many bugs are caused by programmers either forgetting or never getting clear on what they plan to do with a given variable.
For newbies, it would say it is an error to fail to document any variable except i in a for loop.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
guitarromantic@gmail.com - 05 Dec 2005 19:39 GMT This must be me being stupid but I honestly can't figure it out. In psuedocode I am (I hope) doing this:
loop through all values in the array if a value is less than <minValue (which is set to a really high number, so inevitably this condition will be true): set min to the value of the array.
Roedy Green - 05 Dec 2005 20:38 GMT On 5 Dec 2005 11:39:15 -0800, "guitarromantic@gmail.com" <guitarromantic@gmail.com> wrote, quoted or indirectly quoted someone who said :
>if a value is less than <minValue (which is set to a really high >number, so inevitably this condition will be true): >set min to the value of the array. no it won't unless you change the value of minValue.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
guitarromantic@gmail.com - 05 Dec 2005 20:48 GMT Arghhh, I'm stupid. I hereby renounce my membership card to the human race; I'm too dumb to take part.. damn.
Roedy Green - 05 Dec 2005 21:55 GMT On 5 Dec 2005 12:48:43 -0800, "guitarromantic@gmail.com" <guitarromantic@gmail.com> wrote, quoted or indirectly quoted someone who said :
>Arghhh, I'm stupid. I hereby renounce my membership card to the human >race; I'm too dumb to take part.. damn. Does this mean you now see the problem, and you feel silly for taking so long, or that you still can't see it?
Hint: you have two variables: min and minValue. You only want one.
You could discover this by either
1. playing computer. Just draw on a piece of paper the values of your various variable.
2. tracing see http://mindprod.com/jgloss/trace.html
3. pepper your code with System.out.println and analyse the printout comparing what you expected to happen with what did.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
guitarromantic@gmail.com - 05 Dec 2005 22:26 GMT Sorry, it meant I figured out what was wrong and felt utterly stupid for not being able to see what was wrong. Haha, I can't even get a sarcastic dig at myself right...
guitarromantic@gmail.com - 08 Dec 2005 14:05 GMT Hey again Roedy/everyone else;
Just an update: I handed my project in today and got full marks for it! I hope you guys aren't reading that and thinking "He doesn't deserve that, with all the dumb mistakes he made", but I really think after this task I've learned a lot of stuff that wasn't immediately obvious from my lectures.. which I guess is the point of the course. Thanks a lot for all the help, it's really done a lot for me and I'm very grateful.
Matt
Oliver Wong - 08 Dec 2005 17:01 GMT > Hey again Roedy/everyone else; > [quoted text clipped - 5 lines] > lot for all the help, it's really done a lot for me and I'm very > grateful. The point of going to school is to learn (as opposed to getting as many marks as possible).
The points of having marks at all is so that employers can know whether someone is qualified for the job they are applying for.
Your responsibility is to make sure you're learning. Don't cheat, give it your best effort, etc.
What mark you get is not really your responsibility. Maybe you have a nice teacher, maybe you have a mean one. Don't worry about that part too much.
- Oliver
Roedy Green - 09 Dec 2005 00:26 GMT On 8 Dec 2005 06:05:07 -0800, "guitarromantic@gmail.com" <guitarromantic@gmail.com> wrote, quoted or indirectly quoted someone who said :
>Just an update: I handed my project in today and got full marks for it! Great! One nice thing about computing is if you stick with it, no matter how many attempts it takes, the final result shows no signs of all your previous goofs. It looks seamless as if you created it effortlessly first time out.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
Roedy Green - 03 Dec 2005 00:02 GMT On 2 Dec 2005 13:41:24 -0800, "guitarromantic@gmail.com" <guitarromantic@gmail.com> wrote, quoted or indirectly quoted someone who said :
>As per my instructions, I haven't written the main method yet, I've >been told to run commands in DrJava's Interactions tab (effectively >acting as a main method) to create the objects. You have to TEST your code. You can't do that without composing a main method even if your prof is not interested in seeing it.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
Roedy Green - 28 Nov 2005 16:05 GMT On Sun, 27 Nov 2005 19:49:20 -0500, "Rhino" <no.offline.contact.please@nospam.com> wrote, quoted or indirectly quoted someone who said :
>Scanner class It is probably just the java.util.Scanner class in JDK 1.5 see http://mindprod.com/jgloss/scanner.html
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
Roedy Green - 25 Nov 2005 19:29 GMT On 25 Nov 2005 09:10:54 -0800, "guitarromantic@gmail.com" <guitarromantic@gmail.com> wrote, quoted or indirectly quoted someone who said :
> public static void readMarks() { > Scanner keyboard = new Scanner(System.in); > System.out.println("Enter marks, then put -1 blah blah"); > marks[] = keyboard.nextInt(); > } I think the intended way to stop this would be with NoSuchElementException triggered by typing a ^Z eof char.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
Free MagazinesGet these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...
|
|
|