Hey, so i have this hw assignment and i have to write a program that allows the user to input students names and grades and give back the higest lowest and average. The only problem is there is a max 50 students in the class(or so the sheet says) and there are only 10 students names and grades on it. How do i get the array to end after the last student?
static final int MAX = 50;
public static void main(String[] args)
{
int index, average;
int highest = 0, student = 1;
Scanner keyboard = new Scanner(System.in);
String [] students = new String[MAX];
int[] grades = new int[MAX];
System.out.println("Please enter the name of the student and their test grade");
System.out.print("Students: ");
for(index=0; index<MAX; index++)
{
students[index] = keyboard.nextLine();
student = student + index;
if(students[index]=="Done"))
{
student = student - 1;
continue;
}
}
System.out.print("Grades: ");
for(index=0; index<student; index++)
grades[index] = keyboard.nextInt();
averageMan(grades, student);
for(index=0; index<student; index++)
if(grades[index] < averageMan(grades, student))
System.out.println(students[index] + " Your test grade was " +
"below the class average. Step it up.");
for(index=0; index<student; index++)
if(grades[index] > highest)
highest = grades[index];
System.out.println("The highest test grade in the class goes to " +
students[highest] + " with a grade of " + grades[highest]);
}
public static int averageMan(int[] g, int s)
{
int index, sum = 0;
int averages;
for(index=0; index<s; index++)
sum = sum + g[index];
averages = sum / s;
return averages;
}
}
Use Collections, not arrays. Their api is a lot more usable.
Read the Collections Trail to get started.
If you want a drop-in replacement for an array, use a List, if you want uniqueness, use a Set.
You could loop round collecting student details until the user enters a specific token that indicates that they have finished entering details.
EDIT Which looks like what you're trying to do..... but continue goes to the next item in the loop. You want to break out don't you?
Initialize the students array with empty strings. Also Initialize the grades array with -1. In your loop for calculating average/highest/lowest, check for empty string and -1.
Try changing
student = student + index;
if(students[index]=="Done"))
{
student = student - 1;
continue;
}
to:
if(students[index]=="Done"))
{
break;
}
student = student + 1;
Then you will quit the entry loop when a student's name is input as "Done" and the variable student will contain the number of students that were input.
1) Hey, why are you doing this?
if(students[index]=="Done"))
{
student = student - 1;
continue;
}
2) you can divide code into smaller methods
3) you can use Collections API as someone suggested.
The easiest solution would be to use a collection class, like java.util.ArrayList instead of an array. If you have to use arrays, maybe you could reallocate the array each time you add a new Student? This page has an example of how to do that - How to resize an array in Java.
Your for loop has three parts, the middle part resolves to a true/false condition. It can be simple, like you have or complex, like this:
for(index=0; index<MAX && !done; index++)
Where done is a boolean that is false until you detect a value that indicates you want to stop then becomes true.
I would use a generic array list http://www.oracle.com/technetwork/articles/javase/generics-136597.html
Related
Hello java pros and experts, the first problem I have is implementing a code into my program where it tells a user "No numbers were entered" when they do not enter any numbers and the array is empty.
the second problem I have is implementing a code if the user enters too many numbers, put out an Error message that the size of the array has been exceeded; then print out the numbers entered on the next line.
This is my code so far:
import java.util.Scanner;
public class FunWithArrays
{
public static void main(String[] args)
{
final int ARRAY_SIZE = 10; // Size of the array
// Create an array.
int[] numbers = new int[ARRAY_SIZE];
// Pass the array to the getValues method.
getValues(numbers);
System.out.println("Here are the " + "numbers that you entered:");
// Pass the array to the showArray method.
showArray(numbers);
}
public static void getValues(int[] array)
{
// Create a Scanner objects for keyboard input.
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a series of " + array.length + " numbers.");
// Read the values into the array
for (int index = 0; index < array.length; index++)
{
System.out.print("Enter the number " + (index + 1) + ": ");
array[index] = keyboard.nextInt();
}
}
public static void showArray(int[] array)
{
// Display the array elements.
for (int index = 0; index < array.length; index++)
System.out.print(array[index] + " ");
}
}
I was wondering if you pros or experts have any advice on how to approach this problem without changing any of the codes in my program? my professor instructed me to do a do-while loop for the problem, but do not know how to create the code for it... any suggestions?
Here is my Code
import java.util.*;
public class dowhile
{
public static void main (String [] args)
{
Scanner kb = new Scanner (System.in);
System.out.println("Enter number of # to be displayed: ");
int tim = kb.nextInt();
String hash = "#";
do
{
System.out.println(hash);
hash = hash + 1;
} while (hash.equals(5));
}
}
I am confused on how to display number of # after asked by the user..
I know hash.equals(5) does not make sense.
how can i fix this code?
Any one please give the suggestion to me.
You could use tim as a counter, and decrement it before testing if it's greater than 0. Something like,
int tim = kb.nextInt();
do {
System.out.print("#");
} while (--tim > 0);
System.out.println();
You can also use Apache commons-lang3 which has StringUtils.repeat(String, int)
Parameters:
str - the String to repeat, may be null
repeat - number of times to repeat str, negative treated as zero
hash is the string that you are going to print, so you should never change its value like this:
hash = hash + 1; // this does not actually compile anyway.
To keep track of how many times you still need to print, you need an int variable. As you can see, tim is an int and it already has the user input stored in it. Let's use tim as our counter.
Each time you print a # you decrease tim by 1. And in the loop condition, you write tim > 0. This will make the loop run as long as tim is greater than 0.
Scanner kb = new Scanner(System.in);
System.out.println("Enter number of # to be displayed: ");
int tim = kb.nextInt();
String hash = "#";
do {
System.out.println(hash);
tim--; // this is equivalent to tim = tim - 1;, in case you did not know
} while (tim > 0);
However, I don't think using a do-while loop is suitable here. What if the user entered 0? One # will still be printed. That's no good isn't it?
I suggest a for loop here:
Scanner kb = new Scanner(System.in);
System.out.println("Enter number of # to be displayed: ");
int tim = kb.nextInt();
String hash = "#";
for (int i = 0 ; i < tim ; i++) {
System.out.println(hash);
}
Declare one int variable before the loop. Increment number by one in do and check then number in while loop is will print your desired output.
int i=0;
do
{
System.out.println(hash);
i=i + 1;
} while (i<tim);
I have a project due and the details are as follows: write a Java program that holds 6 player's names and reads in and stores his/her best game score and the calculate:
Average Score
Highest Score
Lowest Score
I have coded the following
import java.io.*;
public class Assignment2 {
public static void main(String[] args) throws IOException {
String greeting = "Hello"; //greetings
String myName; //string to store names
int[] scores = new int[7];
String[] scores1 = new String[7];
int highest ;
int smallest;
int averages;
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("*** Welcome to the program ***\n"); //displays greetings
System.out.println(greeting);
for (int i = 0; i < 6; i++ ) // gets 6 names
{
System.out.println("Please type names of players :");
myName = br.readLine();
System.out.println( " " + myName);
}
for (int i = 0; i < scores1.length-1; i++)
{
System.out.print("\n\nEnter Score " + (i+1) + ": ");
scores1[i] = br.readLine();
}
}
}
I am finding it difficult to display the numbers and so on. Any help would be appreciated.
I'm not going to write your code for you. You won't learn to program is someone else does your programming for you. But here are some hints.
Hints:
"I am finding it difficult to display the numbers and so on."
You already have written code to display a number!
You need to figure out how to convert a string to an integer. Read the javadocs for the Integer class.
A simply way to print an array of integers is to use Arrays.toString(...). Alternatively use a loop.
To calculation an average you start by calculating a sum. (You remember four high school maths lessons?)
To find the highest number, you pick a candidate (e.g. the first), test it against all of the others, replacing the candidate if it is not the largest. It can be done with a simple for loop, a temporary variable and an if statement.
What you need to do is instead of finding the highest and lowest number is to find the index at which those numbers exist. Doing so will allow you to match the highest and lowest numbers to the name. Example names[0] = Fred and numbers[0] = Fred's number. So if Fred got the lowest number, we would keep track of his index (in this case 0) and then display his name with his score at the end of the program.
I suggest reading this answer I recently posted: https://stackoverflow.com/questions/41912197/need-help-displaying-information-from-a-loop/41912486#41912486
I just wrote this basic program. It takes 5 values from the user and stores all of them in an array and tells the highest number.
import java.util.Scanner;
public class HighestNumber {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int [] numbers = new int [5];
int max = numbers[0];
System.out.println("Enter " + numbers.length + " numbers:");
for (int i=0; i<numbers.length; i++) {
numbers[i] = input.nextInt();
if (numbers[i] > max) {
max = numbers[i];
}
}
System.out.println("The highest number is:" +max);
}
}
I'd like to take off the restriction of 5 numbers and allow the user to add as many numbers as he wants. How can I do that?
Appreciate the assistance. :)
Thanks
If the user knows the number of numbers in advance (before they enter the actual numbers):
Ask the user how many numbers they want to enter:
System.out.println("How many numbers?");
int numberOfNumbers = input.nextInt();
Use that as the array size:
int[] numbers = new int[numberOfNumbers];
If the user shouldn't need to know the number of numbers in advance (e.g. if they should be able to type "stop" after the last number) then you should consider using a List instead.
Alternatively, you could use an ArrayList and keep on adding elements until the user enters a blank line. Here is a tutorial on using ArrayList.
Some pseudocode could be:
numbers = new list
while true
line = readLine
if line == ""
then
break
else
numbers.add(convertToInteger(line))
...
The benefit of this approach is that the user does not need to even count how many numbers he/she wants to enter.
I'm having a few problems with my code, this is the over all goal of the program.
One of your professors hears of your emerging programming expertise and asks you to write a SINGLE program that can be used to help them with their grading. The professor gives three 50-point exams and a single 100-point final exam. Your program will prompt the user for the student’s name, entered as Firstname Lastname (i.e. Bob Smith), the student’s 3-exam scores and 1-final exam score (all whole numbers). Class size varies from semester to semester, but 100 is the limit (declare as a constant).
Read in information for ALL students before doing any calculations or displaying any output. Verify that the 3 exam scores are between 0-50 points and that the final is between 0-100 as they are entered. Declared minimums and maximums as constant so that they can easily be updated, as needed. If invalid, display an error message and allow the user to re-enter that invalid score. Once all student info is read in, display each student’s name in the format LASTNAME, FIRSTNAME (all uppercase), the student’s exam percentage (total of all exams plus final / total possible) to 1 decimal and the student’s final grade.
This is what I have:
import java.util.*;
import java.text.*;
public class Proj4 {
public static void main(String[] args){
Scanner s= new Scanner(System.in);
String input;
String again = "y";
final int MAX_STUDENTS = 100;
final int MIN_EXAM = 0;
final int MAX_EXAM = 50;
final int MIN_FINAL = 0;
final int MAX_FINAL = 100;
String[] names = new String[MAX_STUDENTS];
int [] exams = new int[MAX_STUDENTS * 4];
int student = 1;
do
{
System.out.print("PLease enter the name of student " + student + ": " );
for (int k = 0; k < 1; k++) {
names[k] = s.nextLine().toUpperCase();
}
for ( int i = 0; i < 4; i++){
if(i==3){
System.out.print("Please enter score for Final Exam: ");
exams[i] = s.nextInt();
}
else{
System.out.print("Please enter score for Exam " + (i+1) + ": ");
exams[i] = s.nextInt();
if((exams[0]<MIN_EXAM||exams[0]>MAX_EXAM)||(exams[1]<MIN_EXAM||exams[1]>MAX_EXAM)||(exams[2]<MIN_EXAM||exams[2]>MAX_EXAM)){
System.out.println("Invalid enter 0-50 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
else if(exams[3]<MIN_FINAL||exams[3]>MAX_FINAL){
System.out.println("Invalid enter 0-100 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
}
}
System.out.print("do you wish to enter another? (y or n) ");
again = s.next();
if(again!="y")
student++;
}while (again.equalsIgnoreCase ("y"));
System.out.println("***Class Results***");
System.out.println(names[1] + "," + names[0] + " " + "Exam Percentage: "+ ((exams[0]+exams[1]+exams[2]+exams[3])/(MAX_EXAM*3+MAX_FINAL)));
}
}
The problems i have have are:
figuring out how to assign the user entered test scores beyond just the first student, i believe i have it set up correct for just one, but it runs into a problem when i would move on to the second student.
For some reason that I cannot figure out the line
System.out.print("do you wish to enter another? (y or n) ");
again = s.next();
doesn't allow me to enter anything, not y not n not anything, so my program effectively ends there, it doesn't make sense to me because I've done it exactly like that before and it has worked.
other than that, if there are any other problems that you can see with my code pointing them out would be extremely helpful.
Thank you
EDIT-
new problem i am having, after changing to
if(!again.equalsIgnoreCase("y"))
student++;
}while (again.equalsIgnoreCase ("y"));
it lets me type things in now, but after i type in y it prints the next line as
Please enter the name of student 1: Please enter score for Exam 1:
I don't know why or what i need to change to fix it, any suggestions?
`if(again!="y")` is the culprit here
You should use equals() method to check string equality.
if(!again.equals("y"))
If you compare Strings in Java using the == or != operators then you are not actually comparing the values. Instead you are testing if the two Strings are the same Object.
This post explains String comparison well.
To do what you want, change if (again != "y") to if(! (again.equalsIgnoreCase("y")) )
EDIT
I believe your new problem stems from the first for loop you do inside your do loop. Each time you type "y" at the end of your do/while you are going to execute the entire
for (int k = 0; k < 1; k++) {
loop again. This is why after you type "y" you are seeing Please enter the name of student 1: Please enter score for Exam 1:
A "solution" to your new issue would be to make it so the outer for enclosed the inner one, looping through 4 exams for each student usually referred to as a "double for" or "nested for loop".
That said you would then be presented with the issue of having all the exams for ALL students in a single array.
I think now is the time to sit down and put some serious thought into the design of your program. It would be much easier for you if you used a Student object to represent a student and hold their exam scores, IMO. Then you could create an array of Students as opposed to two different arrays you have now.
Here are some "starter" steps (Not necessarily a complete list):
Make a Student class that has variables for the student's first & last name, as well as an array to hold that Students exam scores
In your main class create an ArrayList to hold all of the new Student objects you will be creating.
Do your do/while loop. At the beginning of the loop create a new Student object. Then ask for the Students name and exam scores (note that if you KNOW there will only be the 4 exam scores you don't have to do any extra logic there. You can simply ask for the 4 exam scores using a for loop, or if you want all at one time. if there are a variable number of scores you will have to do some sort of check)
Add the new Student you have created to the ArrayList of Students.
Once the person selects "n", loop through the ArrayList and print the information for each Student!
Your for (int k = 0; k < 1; k++) loop will execute only once (for one student) because you have it set up to execute only while k < 1, which will happen only once. As soon, as you increase k to 1, the loop will stop. I would change it to for (int k = 0; k < MAX_STUDENTS; k++) to make sure it will loop through until you reach the max number of students allowed.