Omnimaga

General Discussion => Technology and Development => Computer Programming => Topic started by: Snake X on March 30, 2011, 07:02:25 pm

Title: [solved][java] help!
Post by: Snake X on March 30, 2011, 07:02:25 pm
Ok, I have an assignment for Adv. comp sci. and I need help. I am assigned to make 'A program that will read integer test scores from the keyboard until a negative value is typed in. The program will drop the lowest score from the total and print the average of the remaining scores.' I have to use looping for this.. I know how to make the syntax for this I'll say, because I don't know how I can take any amount of test score, and drop the lowest score if I don't know how many number's I have and I dont know how to do this. My teacher said something about taking it to another variable and comparing test scores like 'if (low > testscore) {' for example. I am still confused how to do this.. Here is the code I have so far:

Code: [Select]

import javax.swing.JOptionPane;

public class while 2 {

    public static void main(String[] args) {

        int scores = 0; //scoretemp parsed as int here.
        int temp = 0; //temp var to compare lowest score
        int low = 0; //not sure about this, lowest score variable anyhow.
        for (int i=1;i>0;i++) {
        String scoretemp = JOptionPane.showInputDialog("Enter your test score (-1 to exit):");
        int score = Integer.parseInt(scoretemp);  //scoretemp is converted to an integer
        if (score = -1) { //if -1 is entered then..
         break;        //exit. [this will quit the whole loop.]
        }
        if (score >= 0){ //if test score is equal to 0 or greater than 0...
//actual code here

        }
    }
}
}
Title: Re: [java] halp!
Post by: DJ Omnimaga on March 30, 2011, 07:21:27 pm
/me edits a spelling mistake in the topic title. :P
Title: Re: [java] help!
Post by: Snake X on March 30, 2011, 07:27:19 pm
no, that was intentional actually
Title: Re: [java] help!
Post by: Deep Toaster on March 30, 2011, 07:29:02 pm
Quote
for (i=1;i>0;i++);

There's no loop there?
Title: Re: [java] help!
Post by: FinaleTI on March 30, 2011, 07:36:11 pm
I'm working on my homework right now, so I can't offer much help right now.
The only thing I can think of for handling all the numbers would be to store them to an ArrayList. You should then be able to loop through it and find the cell with the lowest number, then call remove() to drop the element, and then loop through the list again and sum up all the numbers.
Title: Re: [java] help!
Post by: apcalc on March 30, 2011, 07:36:22 pm
Maybe something like this?

EDIT:  fixed major error in for( loop...

Code: [Select]

public class average {

public static void main(String []args) {

public Arraylist<Integer> grades;
double total=0.0;
int minGrade=Integer.MAX_VALUE;
int minIndex=-5;

//Read input, adding each grade to the list with grades.add(new Integer(grade_value));

for(int x=0;x<grades.size();x++) {
if(grades.get(x).intValue()<minGrade) {
minIndex=x;
minGrade=grades.get(x).intValue();
}
}

grades.remove(minIndex);

for(int x=0;x<grades.size();x++)
total+=grades.get(x).intValue();

System.out.println(total/grades.size());

}
}
Title: Re: [java] help!
Post by: Snake X on March 30, 2011, 07:56:10 pm
no arrays.

fixed:

Code: [Select]
import javax.swing.JOptionPane;

public class while2 {

    public static void main(String[] args) {

        int temp = 0; //temp var to compare lowest score
        int low = 0; //not sure about this, lowest score variable anyhow. initialization.
        int acc = 0;
        int total = 0; //total.
        boolean fail = false;
        int score = 0;

        if (score < 0) { //if -1 is entered then..
                fail = true;  //Some kind of failure code goes here.
        }
        else{
             String scoretemp = JOptionPane.showInputDialog("Enter your test score (-1 to exit):");
             score = Integer.parseInt(scoretemp);
             low = score; //assignment takes place <--
        }
        while (!fail) {
        String scoretemp = JOptionPane.showInputDialog("Enter your test score (-1 to exit):");
        score = Integer.parseInt(scoretemp);  //scoretemp is converted to an integer
        if (score < 0) { //if -1 is entered then..
                break;
        }
        else{
                        if (score < low) {  //compares 0 to the score :S
                                total += low;
                                low = score;
                        }
                        else{
                               total += score;
                        }
        }
        acc += 1;
    }
    System.out.print(low); //tests low to make sure of correct output
}
}
Title: Re: [java] help!
Post by: Madskillz on March 30, 2011, 08:41:23 pm
Did you get this working then snake.

I was going to say you wouldn't need an array.
A variable that keeps the lowest score.
A variable that keeps a running total of scores.
A variable that keeps the number of entries submitted.

You can get all your information from those three things. You shouldn't need any loops for this.
Title: Re: [java] help!
Post by: nemo on March 30, 2011, 09:10:55 pm
Code: [Select]
int sum = 0;
int numScores = 0;
int lowest = 101; //assuming 100 is the highest score possible
while(true){
    String temp = JOptionPane.showInputDialog("Enter test score (negative to exit): ");
    int score = Integer.parseInt(temp);
    if(score < 0)
        break;
    numScores++;
    if(score < lowest)
        lowest = score;
    sum += score;
}
System.out.println("Average: " + ((sum - lowest) / (numScores - 1)));

should work, unless you don't enter any scores, in which case you'll get -101 (if i went through that right).
You can get all your information from those three things. You shouldn't need any loops for this.

you do need one loop... unless you want to write it recursively? just for the challenge:

Code: [Select]
public static void main(String[] args){
    int[] answers = recursion(0, 101, 0);
    System.out.println("Average: " + ((answers[2] - answers[1]) / (answers[0] - 1)));
}
public static int[] recursion(int numScores, int lowest, int sum){
    String temp = JOptionPane.showInputDialog("Enter test score (negative to exit): ");
    int score = Integer.parseInt(temp);
    if(score < 0)
        return new int[] {numScores, lowest, sum};
    return recursion(numScores + 1, score < lowest ? score : lowest, sum + score);
}

pretty sure the first one works, not sure about the second.

       
Title: Re: [java] help!
Post by: Madskillz on March 31, 2011, 03:24:35 am
My bad I didn't read all of his description, especially about the looping being necessary. :P

The first part looks right just walking through it systematically.
Well thought out on the checking of lower scores, you actually save a step doing it that way versus setting lowest score to 0.

Your recursion looks right but I didn't test it. Good way to test yourself ha.
Title: Re: [java] help!
Post by: ZippyDee on March 31, 2011, 03:47:39 am
Code: [Select]
int sum = 0;
int numScores = 0;
int lowest = 101; //assuming 100 is the highest score possible
while(true){
    String temp = JOptionPane.showInputDialog("Enter test score (negative to exit): ");
    int score = Integer.parseInt(temp);
    if(score < 0)
        break;
    numScores++;
    if(score < lowest)
        lowest = score;
    sum += score;
}
System.out.println("Average: " + ((sum - lowest) / (numScores - 1)));
You may want to try/catch that parseInt, otherwise it could throw a NumberFormatException.
Title: Re: [java] help!
Post by: Munchor on March 31, 2011, 05:46:49 pm
I know this is not supposed to be here, but for the fun of it, I made a Python code for this challenge:

Quote
A program that will read integer test scores from the keyboard until a negative value is typed in. The program will drop the lowest score from the total and print the average of the remaining scores.

Code: [Select]
inputs = []
while True:
n = input()
if n<0:
break
inputs.append(n)

lowest = inputs[0]
for i in range(0,len(inputs)):
if inputs[i]<=lowest:
lowest=inputs[i]

numberOfValues = len(inputs)
sumOfValues = 0
for i in range(0,len(inputs)):
sumOfValues+=inputs[i]

print "Average: " + str(sumOfValues/numberOfValues)
print "Lowest: " + str(lowest)

It could be shorter, but I made it simplified.

Sorry, I couldn't resist:

Code: [Select]
inputs = []
while True:
n = input()
if n<0:
break
inputs.append(n)

lowest = inputs[0]
sumOfValues = 0
for i in range(0,len(inputs)):
if inputs[i]<=lowest:
lowest=inputs[i]
sumOfValues+=inputs[i]

print "Average: %d\nLowest: %d" % (sumOfValues/len(inputs),lowest)
15 lines :)
Title: Re: [java] help!
Post by: Michael_Lee on March 31, 2011, 06:38:03 pm
This is even more off-topic, but here's my version.

Code: [Select]
grades = []
n = lowest = float("inf")   # 'inf' stands for infinity - this actually works.

while n > 0:
    n = float(input("Grade: "))
    if n > 0:
        if n < lowest:
            lowest = n
        grades.append(n)

for i in range(grades.count(lowest)):
    grades.remove(lowest)
   
print("Average = {0}\nLowest =  {1}".format(sum(grades)/len(grades), lowest))

Scout's version was 13 lines long (without empty lines), mine is 11 lines long (without empty lines)  ;D.

Mine also removes any repeated low scores.  If that isn't desired behavior, then you could just remove the 'for' statement and execute 'grades.remove(lowest)' only once.
Title: Re: [java] help!
Post by: Munchor on April 01, 2011, 09:49:47 am
Nice job Michael, I like what you did there.
Title: Re: [java] help!
Post by: calcdude84se on April 01, 2011, 10:08:39 am
Hm. Are you allowed to use implementers of List<T> such as ArrayList<T>?
The List<T> interface specifies an add(T) function.
Edit: That's a no. * calcdude needs to read the topic more thoroughly :-[
Title: Re: [java] help!
Post by: Munchor on April 02, 2011, 06:30:42 am
This is even more off-topic, but here's my version.

Code: [Select]
grades = []
n = lowest = float("inf")   # 'inf' stands for infinity - this actually works.

while n > 0:
    n = float(input("Grade: "))
    if n > 0:
        if n < lowest:
            lowest = n
        grades.append(n)

for i in range(grades.count(lowest)):
    grades.remove(lowest)
   
print("Average = {0}\nLowest =  {1}".format(sum(grades)/len(grades), lowest))

Scout's version was 13 lines long (without empty lines), mine is 11 lines long (without empty lines)  ;D.

Mine also removes any repeated low scores.  If that isn't desired behavior, then you could just remove the 'for' statement and execute 'grades.remove(lowest)' only once.

For the fun of it, 7 lines!

Code: [Select]
inputs = []
while True:
n = input()
if n<0:
break
inputs.append(n)
print "Average: %d\nLowest: %d" % (sum(inputs)/len(inputs),min(inputs))
/me wins.

:P
Title: Re: [java] help!
Post by: Michael_Lee on April 02, 2011, 03:28:59 pm
This is even more off-topic, but here's my version.

Code: [Select]
grades = []
n = lowest = float("inf")   # 'inf' stands for infinity - this actually works.

while n > 0:
    n = float(input("Grade: "))
    if n > 0:
        if n < lowest:
            lowest = n
        grades.append(n)

for i in range(grades.count(lowest)):
    grades.remove(lowest)
   
print("Average = {0}\nLowest =  {1}".format(sum(grades)/len(grades), lowest))

Scout's version was 13 lines long (without empty lines), mine is 11 lines long (without empty lines)  ;D.

Mine also removes any repeated low scores.  If that isn't desired behavior, then you could just remove the 'for' statement and execute 'grades.remove(lowest)' only once.

For the fun of it, 7 lines!

Code: [Select]
inputs = []
while True:
n = input()
if n<0:
break
inputs.append(n)
print "Average: %d\nLowest: %d" % (sum(inputs)/len(inputs),min(inputs))
/me wins.

:P

Wait, how does that drop the lowest score?
Title: Re: [java] help!
Post by: Munchor on April 02, 2011, 03:35:51 pm
min(array) returns the minimum value of an array.
Title: Re: [java] help!
Post by: Deep Toaster on April 02, 2011, 04:10:41 pm
It includes the lowest score in your average calculation, though, which is not what you want. Try this:

Code: (Python) [Select]
inputs = []
while True:
n = input()
if n<0:
break
inputs.append(n)
print "Average: %d\nLowest: %d" % ((sum(inputs) - min(inputs) * inputs.count(min(inputs))) / len(inputs), min(inputs))

And eventually we need to get back on topic :P

Pretty much nemo's, but edited:

Code: (Java) [Select]
int sum;
int numScores;
int lowest = 100;
while (true)
{
try
{
int score = Integer.parseInt(JOptionPane.showInputDialog("Enter test score (negative to exit): "));
}
catch (NumberFormatException exc)
{
break;
}

if (score < 0)
break;

numScores++;

if (score < lowest)
lowest = score;

sum += score;
}
System.out.println("Average: " + ((sum - lowest) / (numScores - 1)), "Lowest: " + lowest);
Title: Re: [java] help!
Post by: Michael_Lee on April 03, 2011, 12:31:02 am
Question:
What is supposed to happen if you enter multiple low scores?

Like, if the grades entered were
10, 90, 6, 5, 5, 12, -5

Would it calculate the average after dropping the negative and both lowest values
10, 90, 6, 12

Or would it calculate the average after dropping the negative and only one of the lowest values?
10, 90, 6, 12, 5

?
Title: Re: [java] help!
Post by: jnesselr on April 03, 2011, 09:27:54 am
well deep thought's code breaks after it reaches a negative number, so if you did 10,90,6,-5,12,5 it would calculate 10, 90, and 6 to get 10+90+6=106/3=35.333....
Title: Re: [java] help!
Post by: Deep Toaster on April 03, 2011, 10:49:44 am
well deep thought's code breaks after it reaches a negative number, so if you did 10,90,6,-5,12,5 it would calculate 10, 90, and 6 to get 10+90+6=106/3=35.333....

Well, it wouldn't even ask you for 12 and 5.
Title: Re: [java] help!
Post by: jnesselr on April 03, 2011, 06:22:41 pm
well deep thought's code breaks after it reaches a negative number, so if you did 10,90,6,-5,12,5 it would calculate 10, 90, and 6 to get 10+90+6=106/3=35.333....

Well, it wouldn't even ask you for 12 and 5.
Well, I mean if you attempted to input that.  Details.... details....
Title: Re: [java] help!
Post by: nemo on April 03, 2011, 08:29:50 pm
well deep thought's code breaks after it reaches a negative number, so if you did 10,90,6,-5,12,5 it would calculate 10, 90, and 6 to get 10+90+6=106/3=35.333....


if you did 10,90,6,-5 shouldn't 6 be dropped, and you end up with 100/2 = 50?
Title: Re: [java] help!
Post by: jnesselr on April 03, 2011, 10:21:35 pm
well deep thought's code breaks after it reaches a negative number, so if you did 10,90,6,-5,12,5 it would calculate 10, 90, and 6 to get 10+90+6=106/3=35.333....


if you did 10,90,6,-5 shouldn't 6 be dropped, and you end up with 100/2 = 50?
Nope.
Title: Re: [java] help!
Post by: Michael_Lee on April 03, 2011, 10:32:25 pm
I am assigned to make 'A program that will read integer test scores from the keyboard until a negative value is typed in. The program will drop the lowest score from the total and print the average of the remaining scores.'

I agree with nemo.
Title: Re: [java] help!
Post by: jnesselr on April 03, 2011, 10:53:58 pm
I am assigned to make 'A program that will read integer test scores from the keyboard until a negative value is typed in. The program will drop the lowest score from the total and print the average of the remaining scores.'

I agree with nemo.
Ah, I totally missed where Deep Thought did that in his code. (sum-lowest) does that.
/me  goes and sits in a corner
Title: Re: [java] help!
Post by: apcalc on April 03, 2011, 10:59:41 pm
/me hits himself for not reading no arrays!

Well, anyways, here is a second shot at this, as I had to go back and do it!  (Yes, I cheated and used a pre-written console input class :P).

Code: [Select]
public class Main {
    public static void main(String[] args) {
       int lowScore=Integer.MAX_VALUE;
       int sum=0;
       int numValues=0;
       int currGrade;
       while(true) {
           System.out.print("Enter Grade:  ");
           currGrade=TextIO.getInt();
           if (currGrade<0) break;
           if(currGrade<lowScore) {
               if(lowScore!=Integer.MAX_VALUE) sum+=lowScore;
               lowScore=currGrade;
               numValues++;
           }
           else {sum+=currGrade;numValues++;}
       }
       System.out.println("Average:  "+(double)sum/(numValues-1));
    }
}
Title: Re: [java] help!
Post by: Munchor on April 04, 2011, 09:45:27 am
apcalc, I like how you use TextIO Class, I love it too, much better than the scanner.
Title: Re: [java] help!
Post by: Snake X on April 10, 2011, 03:37:44 pm
ok, well Thanks for your help so far. I appreciate it. I have one question though.. Why doesnt this work:

Code: [Select]
import javax.swing.JOptionPane;

public class while2 {

    public static void main(String[] args) {

        int temp = 0;
        int low = 0;
        int acc = 0;
        double total = 0;
        int score = 0;
        int lowest = 0;

             String scoretemp = JOptionPane.showInputDialog("Enter your test score (enter a negative number to exit):");
             score = Integer.parseInt(scoretemp);  //5
             low = score;  //low is 5
             total += score;  //total is 5
             acc += 1; //1

        while (true) {
        scoretemp = JOptionPane.showInputDialog("Enter your test score (enter a negative number to exit):");
        score = Integer.parseInt(scoretemp);  //score is now a negative number
        if (score < 0) {  //nope
                break;
        }
        else{
                        if (score < low) {  //if 1 < 2
                               total += low;  // total is total + low (5+4+3+2+1) = 15
                                low = lowest;  //lowest is now 2
                        }
                        else{
                               total += score;
                        }
        }
        acc += 1; //6
        low = score; //low is now 1
    }
     System.out.println(lowest); //lowest is 2
     System.out.println(total);  //total is 15
     total = total - lowest; //total is now 13
     System.out.println(total);
     acc = acc - 1; //5
   System.out.println(acc);
total =(double) total / acc;  //13 / 5 = 2.6
System.out.println(total);


// System.out.println("your average of the test scores minus the lowest score is: " + total);
}
}

I ran this in my head and commented it so that i can keep track of everything that goes on in the program. I did this based on these numbers *in order*: 5,4,3,2,1,<negative number to exit>
here are my results:

0
19.0
19.0
4
4.75

edit: the problem is is that the lowest score for some reason isn't being set in the if block. Thus it's at its default value EVEN THOUGH it Should work
edit 2: for some reason the order on the scores actually makes a difference on what the outcome is  :-\
edit 3: Sorry but im not actually able to use your programs because they are more advanced then what I have learned. I have only learned JOptionPane, while loops, for loops, scanner class, string manipulation, and math functions. D:
Title: Re: [java] help!
Post by: Madskillz on April 10, 2011, 05:11:34 pm
For one thing I would simplify all the variables you really only need 3 for this project. This should simplify your code and help you follow whats going on easier. I think you are getting some variables confused.
Sum, lowest and number of entries.

In your code, it looks like lowest is never actually given a value, except for when you initialize it. That's your 0 as your first println. You have low = lowest, switch it to lowest = score;

Nemo really had it spot on in his thinking. By setting the lowest value to one greater than the highest possible answer, this automatically makes the first entry entered the first lowest number. Then you simply have to check the incoming score against the lowest and if it is lower than the lowest value set the lowest value to this new value. Which is along the same lines as I think you were thinking, but his saves you some code.  I would just keep adding the scores to the total and then subtract the lowest when it comes to printing the results. But we all do stuff differently.

Edit: I modified your code, it's quick and dirty but it should fix your problems. Your score variable could be kept, I just took it out.
Code: [Select]
public class count {
   public static void main(String[] args) {

       int lowest = 0;
       int total = 0;
       int numEntries = 0;

       String tempScore = JOptionPane.showInputDialog("Enter your test score (negative to exit):");
       lowest = Integer.parseInt(tempScore);
       total += Integer.parseInt(tempScore);
       numEntries++;

       while (true) {
       tempScore = JOptionPane.showInputDialog("Enter your test score (enter a negative number to exit):");
       if (Integer.parseInt(tempScore) < 0) {  
               break;
       }
       else{
                       if (Integer.parseInt(tempScore) < lowest) {
                               lowest = Integer.parseInt(tempScore);
                       total  += Integer.parseInt(tempScore);
                       }
                       else {
                       total  += Integer.parseInt(tempScore);
                       }
       }
       numEntries++;
   }
       total = total-lowest;
    System.out.println("Lowest Score:" + lowest);
    System.out.println("Number of Total Entries: " + numEntries);
    System.out.println("Total:" + total);  
    System.out.println("Average:" + (double)total/(numEntries-1));


// System.out.println("your average of the test scores minus the lowest score is: " + total);
}
}
Title: Re: [java] help!
Post by: Snake X on April 10, 2011, 06:18:20 pm
wtf that's how my code was structured! Literally.

pseudo code:

Code: [Select]
enter test number
lowest = test number
total += test number

loop {
if score is negative {
  break
}
else
{
if score < low {
  lowest = score
  total += score
}
else
{
  total += score
}

number of entries ++

//all math here and rest of program blah blah blah

edit: how come mine didnt work but your's did. Also more importantly.. how did the lowest score never get set to? That's what I want to know because it should have
Title: Re: [java] help!
Post by: Madskillz on April 10, 2011, 08:16:03 pm
You had low = lowest in the second if statement in the while loop. You actually wanted lowest = score. I think with having both a low and lowest variable you were confusing yourself.  ;) That's why I suggested keeping things simple and minimalistic. But yeah, I didn't right my own code, all that was you. I just modified it to fix your issues.
Title: Re: [java] help!
Post by: Snake X on April 10, 2011, 09:55:47 pm
:D thanks! yeah what I was doing is comparing the current score with the last score (low) and if it was lower than the last one then its the lowest... although now that im typing this lol im not sure what good that would do me since i still have to compare (lowest) to something.. if thats even how i did it! lol your right i did confuse myself

edit: why did you parseInt so many times, why not just once?
Title: Re: [java] help!
Post by: Madskillz on April 10, 2011, 10:10:21 pm
I was just freeing up variables, no reason in particular. That's why I said you could keep the score variable that you had.
Title: Re: [java] help!
Post by: Munchor on April 11, 2011, 05:25:12 am
:D thanks! yeah what I was doing is comparing the current score with the last score (low) and if it was lower than the last one then its the lowest... although now that im typing this lol im not sure what good that would do me since i still have to compare (lowest) to something.. if thats even how i did it! lol your right i did confuse myself

edit: why did you parseInt so many times, why not just once?

Did you teacher accept any of those? :)
Title: Re: [java] help!
Post by: Snake X on April 11, 2011, 06:57:20 am
well, im just gonna use madskills since it looks more along the lines of my work because any of the others are actually too advanced and my teacher will know something is up.. so yeah :(

I would but I might get in trouble for doing so. I hope you can understand
Title: Re: [solved][java] help!
Post by: Munchor on April 11, 2011, 07:02:27 am
well, im just gonna use madskills since it looks more along the lines of my work because any of the others are actually too advanced and my teacher will know something is up.. so yeah :(

I would but I might get in trouble for doing so. I hope you can understand

Oh good luck then :)