Author Topic: [solved][java] help!  (Read 14004 times)

0 Members and 1 Guest are viewing this topic.

Offline Snake X

  • Ancient Veteran
  • LV8 Addict (Next: 1000)
  • ********
  • Posts: 810
  • Rating: +33/-8
    • View Profile
[solved][java] help!
« 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

        }
    }
}
}
« Last Edit: April 11, 2011, 06:57:55 am by Snake X »
Loved this place, still the best producers of power metal, and sparked my dreams of coding.

Offline DJ Omnimaga

  • Clacualters are teh gr33t
  • CoT Emeritus
  • LV15 Omnimagician (Next: --)
  • *
  • Posts: 55942
  • Rating: +3154/-232
  • CodeWalrus founder & retired Omnimaga founder
    • View Profile
    • Dream of Omnimaga Music
Re: [java] halp!
« Reply #1 on: March 30, 2011, 07:21:27 pm »
* DJ_O edits a spelling mistake in the topic title. :P
Now active at https://discord.gg/cuZcfcF (CodeWalrus server)

Offline Snake X

  • Ancient Veteran
  • LV8 Addict (Next: 1000)
  • ********
  • Posts: 810
  • Rating: +33/-8
    • View Profile
Re: [java] help!
« Reply #2 on: March 30, 2011, 07:27:19 pm »
no, that was intentional actually
Loved this place, still the best producers of power metal, and sparked my dreams of coding.

Offline Deep Toaster

  • So much to do, so much time, so little motivation
  • Administrator
  • LV13 Extreme Addict (Next: 9001)
  • *************
  • Posts: 8217
  • Rating: +758/-15
    • View Profile
    • ClrHome
Re: [java] help!
« Reply #3 on: March 30, 2011, 07:29:02 pm »
Quote
for (i=1;i>0;i++);

There's no loop there?




Offline FinaleTI

  • Believe in the pony that believes in you!
  • CoT Emeritus
  • LV10 31337 u53r (Next: 2000)
  • *
  • Posts: 1830
  • Rating: +121/-2
  • Believe in the pony that believes in you!
    • View Profile
    • dmuckerman.tumblr.com
Re: [java] help!
« Reply #4 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.


Spoiler For Projects:

My projects haven't been worked on in a while, so they're all on hiatus for the time being. I do hope to eventually return to them in some form or another...

Spoiler For Pokemon TI:
Axe port of Pokemon Red/Blue to the 83+/84+ family. On hold.

Spoiler For Nostalgia:
My big personal project, an original RPG about dimensional travel and a few heroes tasked with saving the world.
Coding-wise, on hold, but I am re-working the story.

Spoiler For Finale's Super Insane Tunnel Pack of Doom:
I will be combining Blur and Collision Course into a single gamepack. On hold.

Spoiler For Nostalgia Origins: Sky's Story:
Prequel to Nostalgia. On hold, especially while the story is re-worked.

Offline apcalc

  • The Game
  • CoT Emeritus
  • LV10 31337 u53r (Next: 2000)
  • *
  • Posts: 1393
  • Rating: +120/-2
  • VGhlIEdhbWUh (Base 64 :))
    • View Profile
Re: [java] help!
« Reply #5 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());

}
}
« Last Edit: March 30, 2011, 07:38:46 pm by apcalc »


Offline Snake X

  • Ancient Veteran
  • LV8 Addict (Next: 1000)
  • ********
  • Posts: 810
  • Rating: +33/-8
    • View Profile
Re: [java] help!
« Reply #6 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
}
}
Loved this place, still the best producers of power metal, and sparked my dreams of coding.

Offline Madskillz

  • LV6 Super Member (Next: 500)
  • ******
  • Posts: 488
  • Rating: +32/-2
    • View Profile
Re: [java] help!
« Reply #7 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.

Offline nemo

  • LV9 Veteran (Next: 1337)
  • *********
  • Posts: 1203
  • Rating: +95/-11
    • View Profile
Re: [java] help!
« Reply #8 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.

       
« Last Edit: March 30, 2011, 09:20:36 pm by nemo »


Offline Madskillz

  • LV6 Super Member (Next: 500)
  • ******
  • Posts: 488
  • Rating: +32/-2
    • View Profile
Re: [java] help!
« Reply #9 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.

Offline ZippyDee

  • LV8 Addict (Next: 1000)
  • ********
  • Posts: 729
  • Rating: +83/-8
  • Why not zoidberg?
    • View Profile
Re: [java] help!
« Reply #10 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.
« Last Edit: March 31, 2011, 03:50:31 am by ZippyDee »
There's something about Tuesday...


Pushpins 'n' stuff...


Offline Munchor

  • LV13 Extreme Addict (Next: 9001)
  • *************
  • Posts: 6199
  • Rating: +295/-121
  • Code Recycler
    • View Profile
Re: [java] help!
« Reply #11 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 :)
« Last Edit: March 31, 2011, 05:49:51 pm by Scout »

Offline Michael_Lee

  • LV9 Veteran (Next: 1337)
  • *********
  • Posts: 1019
  • Rating: +124/-9
    • View Profile
Re: [java] help!
« Reply #12 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.
« Last Edit: March 31, 2011, 06:42:45 pm by Michael_Lee »
My website: Currently boring.

Projects:
Axe Interpreter
   > Core: Done
   > Memory: Need write code to add constants.
   > Graphics: Rewritten.  Needs to integrate sprites with constants.
   > IO: GetKey done.  Need to add mostly homescreen IO stuff.
Croquette:
   > Stomping bugs
   > Internet version: On hold until I can make my website less boring/broken.

Offline Munchor

  • LV13 Extreme Addict (Next: 9001)
  • *************
  • Posts: 6199
  • Rating: +295/-121
  • Code Recycler
    • View Profile
Re: [java] help!
« Reply #13 on: April 01, 2011, 09:49:47 am »
Nice job Michael, I like what you did there.

Offline calcdude84se

  • Needs Motivation
  • LV11 Super Veteran (Next: 3000)
  • ***********
  • Posts: 2272
  • Rating: +78/-13
  • Wondering where their free time went...
    • View Profile
Re: [java] help!
« Reply #14 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 :-[
« Last Edit: April 01, 2011, 10:10:39 am by calcdude84se »
"People think computers will keep them from making mistakes. They're wrong. With computers you make mistakes faster."
-Adam Osborne
Spoiler For "PartesOS links":
I'll put it online when it does something.