Introducing an array to store scores in Java - java

The question I am working on is:
Write a program that:
asks the user how many exam scores there are (and verifies that the user entered a positive integer), prompt the user for each real-valued score, one by one (as shown below in Sample program behavior / output: box), Calculate and output the average of the scores and count and output how many scores are greater than the average (as shown below in Sample program behavior / output: box).
Sample program behavior / output:
How many exams scores do you have to enter? 5
Enter score #1: 95.0
Enter score #2: 92.0
Enter score #3: 68.0
Enter score #4: 72.0
Enter score #5: 70.0
The average score is: 79.4
There are 2 scores larger than the average.
This is my code:
import java.util.Scanner;
public class testee {
public static void main(String[] args) {
int examnum = -1;
Scanner scan = new Scanner (System.in);
while (examnum<0) {
System.out.println("How many exam scores do you have to enter?");
examnum = scan.nextInt( );
}
for (int i=1; i<=examnum; i++) {
System.out.println("Enter score #" + i + ": ");
for (int a=1; a<=i; a++) {
a = scan.nextInt();
}
}
}
}
What I did produces the following output however my problem is that I need to store the scores that are input to later compute an average so inside my for loop I would need to store the scores as an array but I do not know how to approach that.

First prompt looks good however there is one small problem.
Hint: What condition would you use for your while loop if you wanted to ensure that the value entered was not less than 1 since zero would be rather non-productive?
It's always nice to inform the User of any invalid entry.
To place items into an Array you need to declare that array and initialize it to the proper size:
int[] scoresArray = new int[examnum];
Think about this, where do you think this line of code should be placed?
Hint: You need to ensure that the required array size is already properly established.
Why use two for loops when you can use only one? What can the second (inner nested) for loop do that the outer for loop just simply can't do?
Hint: Nothing! "Enter score #" + (i+1) + ": ". Of course in this case i (within the initialization section) would need to start from 0 and always be less than examnum (within the termination section).
If you want to add an element to your array, where do you think would be a great place in your code to do that?
Hint: int score = scan.nextInt(); scoresArray[i] = score;.
Things to consider:
When scores are being entered, do you think the User entries should be validated? What if the User enters one or more (or all) alpha characters instead of digits in any of your prompts that require an Integer value? Do you end up getting an InputMismatchException? How would you handle such a thing?
Yes, you can nest while loops within a for loop and visa-versa.

Related

I need the input of the user to not skip the value 100

I'm currently working on a program for an O Level project where I have chosen to make a class management system. In my method class, I have various methods which control different functions of my program, such as one which collects the name of the students or one which displays a histogram of the student's grades. However, I have discovered a flaw in one of my methods. This is the method that lists the names of the students, one by one (which are saved in an array from a method that is executed before this method) and asks for the students marks. Here, the user is able to enter any number, which is inconvenient, considering that numerical grades normally range from 0-100. I have tried the following code but I have reached a predicament. The code does in fact stop the user from entering a mark over 100, but instead of allowing the user to re-enter a correct mark, it skips over to the next student, leaving the previous student without a mark. The following is said code:
//mark input
public void markin() {
System.out.println("=====================================");
System.out.println("Please enter the mark of the students");
System.out.println("=====================================");
for (int g = 0; g != marks.length; g++) {
System.out.println(names[g]);
marks[g] = Keyboard.readInt();
while(marks[g]<0||marks[g]>100){
System.out.println("Kindly enter a number that is less than 100");
break;
}
}
}
Help would be very much appreciated and thank you in advance :)
Apologies if my English is not very good.
You almost got it - you need to read in your while-loop instead of breaking without reading. Also a do-loop would be more appropriate for not having to set an initial invalid value.
//mark input
public void markin() {
System.out.println("=====================================");
System.out.println("Please enter the mark of the students");
System.out.println("=====================================");
for (int g = 0; g != marks.length; g++) {
System.out.println(names[g]);
do {
System.out.println("Kindly enter a number that is less than 100");
marks[g] = Keyboard.readInt();
} while(marks[g]<0||marks[g]>100);
}
}
Set marks[ g ] to a number that isn't allowed before the loop, like - 1 then check the keyboard input inside of the while loop,
(and set It there every time as long as the while loop isn't stopped,
marks[g] = Keyboard.readInt();
and don't break the loop, as the loop would end anyways when the input is valid
The valid answers has to get into the array sequentially.
Use this simple trick to reset index [g] to the previous value
then you will overwrite the marks[g] value until you get a valid one:
while(marks[g]<0||marks[g]>100){
System.out.println("Kindly enter a number that is less than 100");
g--; // Resetting index to previous value
break;
}

Can someone help analyse my java code on an averaging program?

Hi so I've started learning java online for two weeks now, but as I watched those tutorials, I felt the only way I'd actually grasp that information was to practice it. My other programs worked great, but just when I decided to do something spectacular (for me only of course; a java expert would find creating this program mind-numbing), something went terribly wrong. I'd really appreciate if you could take a look at my code below of an averaging program that could average any amount of numbers you want, and tell me what in the world I did wrong.
UPDATE: Eclipse just outputs a random number after typing in just one number and then shuts down the program.
Here is a snapshot where I type in the console to average 6 numbers and then start with the number 7, but for some reason, when I hit enter again, it outputs 8.
package justpracticing;
import java.util.*;
public class average{
int grade = 0;
int average;
Scanner notoaverage = new Scanner(System.in);
System.out.println("Please enter the amount of numbers you'd like the average of! ");
final int totalaverage = notoaverage.nextInt();
Scanner averagingno = new Scanner(System.in);
System.out.println("Start typing in the " + totalaverage + " numbers");
int numbers = averagingno.nextInt();
int counter = 0;
public void averagingnumbers(){
while(counter<=totalaverage){
grade+=numbers;
++counter;
}
}
public void printStatement(){
average = grade/totalaverage;
System.out.println(average);
}
}
It seems that you have created an average Object in another class, and are calling the methods given from a main class.
I don't know what exactly you're having trouble with, but one problem is here:
average = grade/totalaverage;
These 2 variables that you are dividing are both integers. That means that the result will also be an integer. This is called truncation. What you want to do is first convert at least one of the integers to a double:
... = (grade * 1.0) / totalaverage;
You also want your average variable to be a double instead of an integer so that it can be a lot more accurate.

Using a loop, and conditionals to change score in a game

I used a loop to generate 1 numbers onto the text file. I start to have problems on when the user starts to play the game.
I'm going to go right ahead and give my pseudo code so you can understand what I want to do...
Randomly generate 10 numbers between 0 and 10
Store these numbers into a file called mysteryNumbers.txt, a number per line
Prompt the user to enter a number between 0 and 10
Check this number against the first number in the file
If the user guesses right, subtract 10 from the score (at the start, the score is 0)
If the user guesses wrong, add the correct amount of score to the current score of the user (at the start, the score is 0)
Prompt the user to enter a number between 0 and 10
Check this number against the second number in the file
If the user guesses right, subtract 10 from the score
If the user guesses wrong, add the correct amount of score to the current score of the user
Prompt the user to enter a number between 0 and 10
Check this number against the third number in the file
If the user guesses right, subtract 10 from the score
If the user guesses wrong, add the correct amount of score to the current score of the user
… etc. …
Display the score of the user: of course, the lower the better!
-I also organized the code below following the pseudocode outline.
/************************************************************************************
PrintWriter mywriter = new PrintWriter("mysteryNumber.txt");
int randomNumber;
int i = 0;
i=1;
while (i<=10) {
Random randomGen = new Random();
randomNumber= randomGen.nextInt(11);
// then store (write) it in the file
mywriter.println(randomNumber);
i = i + 1;
}
//numbers are now generated onto text file...
/************************************************************************************
* 3. Prompt the user to enter a number between 0 and 10 */
Scanner myscnr= new Scanner (System.in);
System.out.print ("Please enter a number between 0 and 10: ");
int userNumber= myscnr.nextInt();
/************************************************************************************
* 4. Check this number against the first number in the file */
// to check the user's number against the file's, you need to be able to read
// the file.
FileReader fr = new FileReader("./mysteryNumber.txt");
BufferedReader textReader = new BufferedReader(fr);
int numberInFile;
// the number in your file is as follows:
numberInFile = Integer.valueOf(textReader.readLine());
/************************************************************************************
* 5. If the user guesses right, subtract 10 from the score */
/************************************************************************************
* 6. If the user guesses wrong, add the correct amount of score to the current *
* score of the user (at the start, the score is 0 */
/************************************************************************************
* 7. Prompt the user to enter a number between 0 and 10 */
//Sytem.out.println ("Enter a number between 0");
/************************************************************************************
* 8. Check this number against the second number in the file */
etc etc...
I'm confused starting on comment section 5. I know I have to create a new integer for score, but after that I'm lost!
I tried working in an if else statemnent but I couldn't get it going..
I guess you created the 10 random numbers and stored in the file without problem.
It would be easier for the rest your code to have the numbers in an array. You could store them in sequence obviously. Next create a for loop to get input number and check against the corresponding number in the array .
Ex:
Considering you have the array numbers[] containing your numbers.
for(int i=0;i<10,i++){
System.out.print ("Please enter a number between 0 and 10: ");
int userNumber= myscnr.nextInt();
if(userNumber==numbers[i])
score-=10;
else
score++; //the addition you wanna make
}

Population change over time

I'm having some problems with my program, i ask the user to enter the start population,daily growth in percent, and how many days they will multiply. Then calculate the end population for each day, while making sure they are constraints to the user entered data. I keep getting back the same results for each day and the constraints aren't doing their job either.
input=JOptionPane.showInputDialog("Please enter the starting number of organisms");
startPopulation=Double.parseDouble(input);
input=JOptionPane.showInputDialog("Please enter their daily population increase as a percentage");
increase=Float.parseFloat(input);
input=JOptionPane.showInputDialog("Please enter how many days they will multiply in");
daysofIncrease=Double.parseDouble(input);
for (int days=0;days<=daysofIncrease+1;days++)
{
if (startPopulation>=2 || increase >0 || daysofIncrease>=1)
{
endPopulation=(startPopulation*increase)+startPopulation;
JOptionPane.showMessageDialog(null,"This is the organisms end population: "+endPopulation+" for day: "+days);
}
else
{
input=JOptionPane.showInputDialog("Please enter the starting number of organisms");
startPopulation=Double.parseDouble(input);
input=JOptionPane.showInputDialog("Please enter their daily population increase as a percentage");
increase=Float.parseFloat(input);
input=JOptionPane.showInputDialog("Please enter how many days they will multiply in");
daysofIncrease=Double.parseDouble(input);
}
}
}
}
Your line
endPopulation=(startPopulation*increase)+startPopulation;
Will not calculate the end population correctly. You haven't used daysofIncrease at all.
I think you'll need to loop through the days. Note that I have not tested this, may need tweaking, but it should give you the idea:
double interimPopulation = startPopulation;
for (int days=1; days<=daysofIncrease; days++) {
interimPopulation *= (1.0 + (increase/100.0)); //get next day's population
}
endPopulation = interimPopulation;
I think you need to set somewhere in your loop this:
startPopulation = endPopulation;
And then you make another iteration of the loop.
Try this for example
endPopulation=(startPopulation*increase)+startPopulation;
startPopulation = endPopulation;
And if you don't want to lose the initial value of startPopulation,
just store it somewhere, before you change it (the way I suggest).

Average of n numbers in java

Using loop I want to calculate the average of n numbers in Java and when user enters 0 the loop ends.
Here is the code that I have written:
public class start {
public static void main(String[] args) {
System.out.println("Enter an int value, the program exits if the input is 0");
Scanner input = new Scanner (System.in);
int h = 0;
while (input.nextInt() == 0){
int inp = input.nextInt();
int j = inp;
int i = 0;
h = j + i;
break;
}
System.out.println("The total is: "+ h);
}
}
Am I making any logical error?
Don't name the sum h, but sum.
The while-condition is wrong
Why do you use inp and j and i?
There is an unconditional break - why?
You talk about the average. Do you know what the average is?
Your output message is not about average - it is about the sum.
"Am I making any logical error?"
Yes. This looks like a homework problem so I won't spell it out for you, but think about what the value of i is, and what h = j + i means in this case.
You also need to be careful about calling input.nextInt(). What will happen when you call it twice each time through the loop (which is what you are doing)?
Homework, right?
Calling input.nextInt() in the while loop condition and also to fill in int inp means that each trip through the loop is reading two numbers (one of which is ignored). You need to figure out a way to only read one number per loop iteration and use it for both the == 0 comparison as well as for inp.
Additionally, you've done the right thing having h outside the while loop, but I think you're confusing yourself with j and i inside the loop. You might consider slightly more descriptive names--which will make your code much easier to reason about.
You need to keep a counter of how many numbers you read so you can divide the total by this number to get the average.
Edited the while loop:
while(true){
int e=input.nextInt();
if(e==0) break;
h+=e;
numberOfItems++;
}
Your original implementation called nextInt() twice, which has the effect of discarding every other number (which is definitely not what you intended to do).
Assuming that you asking the user only once, to enter and if the number if zero you simply want to display the average. you need a variable declared outside the while loop that will keep adding different numbers entered by the user, along with a second variable which track the number of cases entered by the user and keep incrementing itself by one till number is not zero as entered by the user. And as the user Enters 0, the loop will break and here our Average will be displayed.
import java.util.Scanner;
public class LoopAverage
{
public static void main(String[] args0)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter any Integer value : ");
int value = -1, sum = 0, count = 0;
while((value = scan.nextInt()) != 0)
{
count++;
sum = sum + value;
}
System.out.println("Average : " + (sum / count));
}
}
Hope that might help,
Regards
yes, oodles of logical errors.
your while loop condition is wrong, you're consuming the first value
you enter and unless that number is 0 you never enter the loop at all
i var has no purpose
you're breaking after one iteration
you're not calculating a running total
you're not incrementing a count for the average dividend
you're not calculating an average
This looks like you threw some code together and posted it. The most
glaring errors would have been found just by attempting to run it.
Some other things to consider:
Make sure to check for divide by 0
If you do an integer division, you might end up with an incorrect
average, as it will be rounded. Best to cast either the divisor or
dividend to a float
variable names should be helpful, get into the habit of using them
I recommend you to refer to the condition of "while" loop: if condition meets, what would the program do?
(If you know a little bit VB, what is the difference between do...until... and do...while...?)
Also, when you call scanner.nextInt(), what does the program do? For each input, how should you call it?
Last but not least, when should you use "break" or "continue"?
For the fundamentals, if you are in a course, recommend you to understand the notes. Or you can find some good books explaining details of Java. e.g. Thinking in Java
Enjoy learning Java.

Categories