Java Beginner arrays, loops and strings - java

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

Related

Printing Arrays back to user (java)

I'm quite new to java programming so excuse the basic misunderstandings and interpretations of the fundamentals.
This program is supposed to ask the user for the size of an array, then ask the user for input n amount of times and then prints the array back to the user. So far, the first 2 parts work. The program asks for the size of the array and then prints "Enter element n: " based on how many times the user specified in part 1. However, i can't seem to figure out how to print back the string input back out (In my first for loop) the second for loop i tried does not work and just ends the program straight after the first for loop finishes executing. If anyone could help me it would be much appreciated and contribute to my learning of the basics of java. Cheers.
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter array size: ");
int arraySize = scanner.nextInt();
int[] array = new int[arraySize];
for (int i = 0; i<array.length; i++){
System.out.print("Enter element " + (i + 1) + ": ");
String element = scanner.next();
}
System.out.print(array[0]);
for (int i = 1; i < array.length; i++){
System.out.print(array[i]);
}
System.out.println("}");
}
You're not storing any input value into the array.
replace this line:
String element = scanner.next();
with the following one:
array[i] = scanner.nextInt();

GPA calculator assistance

Hi I was wondering if I could get some help with a GPA calculator.
What it needs to do is:
The input will consist of a sequence of terms, e.g., semesters.
The input for each term will consist of grades and credits for courses taken within that term.
For each term, the user will type in an integer that represents the number of courses
taken within that term.
Each course is specified by a String letter grade and an int number of credits, in that order, separated by white space. 5. If the user types in -1 for the number of courses taken in a term, then the program must print a final overall summary and then terminate.
DO NOT prompt for any input. Thus, after you run your program in BlueJ, type Ctrl-T to force the Terminal window to pop up.
As always, follow the input / output format depicted in the Sample runs section.
Shown below is the error message I get and the code I have, thank you for any assistance in advance or tips I could try.
Terminal window and error message:
import java.util.Scanner;
/*
*
*
*/
public class Prog2 {
public static void main(String args[]) {
Scanner numberInput = new Scanner(System.in);
int numberofClasses = numberInput.nextInt();
Scanner input = new Scanner(System.in);
String [] grade = new String[5];
int [] credit = new int [5];
double totalCredit = 0.0;
double realGrade = 0.0;
double result = 0.0;
while (numberofClasses > 0)
{
for (int x = 0; x < numberofClasses; x++ )
{
grade[x] = input.next();
credit[x] = input.nextInt();
}
for(int x=0;x < numberofClasses; x++ ){
if(grade[x].equals("A+")){
realGrade=4.0;
}
else if(grade[x].equals("A")){
realGrade=4.0;
}
else if(grade[x].equals("A-")){
realGrade=3.67;
}
else if(grade[x].equals("B+")){
realGrade=3.33;
}
else if(grade[x].equals("B")){
realGrade=3.00;
}
else if(grade[x].equals("B-")){
realGrade=2.67;
}
else if(grade[x].equals("C+")){
realGrade=2.33;
}
else if(grade[x].equals("C")){
realGrade=2.00;
}
else if(grade[x].equals("C-")){
realGrade=1.33;
}
result = result+realGrade*credit[x];
totalCredit=totalCredit+credit[x];
}
System.out.println("Summary for term:");
System.out.println("----------------------------------");
System.out.println("Term total grade points: " + result);
System.out.println("Term total credits:" + totalCredit);
System.out.println("GPA:"+result/totalCredit);
}
// This block is getting used later please ignore
System.out.println("Final Summary:");
System.out.println("----------------------------------");
System.out.println(" Overall terms");
System.out.println(" Total grade points: " + result);// this needs to be all );
System.out.println(" Total credits" + totalCredit);//This needs to be all );
System.out.println("Cumulative GPA:"+result/totalCredit);
}
}
When your while loop ends, numberofClasses still contains the value that was entered before the while loop started the first time. Specifically, after you output the line:
GPA=3.0588...
you hit the end of the loop, then return to:
while (numberofClasses > 0)
which is true. The next "3" that you enter doesn't go into numberofClasses, it is picked up by
grade[x] = input.next();
Then the "A" is picked up by
credit[x] = input.nextInt();
which throws an exception since it's not an integer.
All you need to do is ask for the number of classes again at the end of the while loop:
System.out.println("GPA:"+result/totalCredit);
numberofClasses = numberInput.nextInt();
}
Output:
5
A 3
B 2
C 4
A 5
C 3
Summary for term:
----------------------------------
Term total grade points: 52.0
Term total credits:17.0
GPA:3.0588235294117645
3
A 3
B 5
C 1
Summary for term:
----------------------------------
Term total grade points: 81.0
Term total credits:26.0
GPA:3.1153846153846154
i recommend looking into whether your compiler or IDE has a "debug" feature. It is a very helpful tool, and lets you watch how your program goes through your code
Just a tip...
When you ask for input, print what you're asking for first. When I launched your program I had no idea what to do. Try adding System.out.println("input number of classes you took");before you prompt for that number.
Here is what is wrong. (If you printed what you're asking for first, this would be more apparent).
after your program displays the stats, you enter 5. Yet your program is actually still on this line grade[x] = input.next(); on line 22 i believe.
when you enter 5, your scanner is expecting a letter. and an exception is thrown.
you need to consider how you escape this loop here. while (numberofClasses > 0) perhaps use an if statement? otherwise your program loops for forever, never asking for a new class number

Dynamic array in Java - so we can decide the size of an array according to user's input

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.

Can't figure why my program doesnt work

import java.util.Scanner;
public class pointSystem {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int points;
int total = 0;
final int judges = 5;
System.out.println("Give points: ");
for(int i=0;i<judges;i++)
{
System.out.println("Give judge's "+ (i+1) + " points: ");
points = scanner.nextInt();
if(points<0 || points>20) {
System.out.println("You can only give points between 0-20");
System.out.println("Judge "+ (i+1) + " points: ");
points = scanner.nextInt();
}
total+=points;
}
System.out.println("Total points are "+total);
}
}
So it's totally a simple program where it asks the user to input points for 5 judges in total and then sums up the points at the end. But points can only be inserted between 0-20, if it goes outside of the range, it gives an error telling us to input again and continues to do so until we have give a valid input.
Now the program works pretty well except for a point that if I enter "22" for example, it asks again like intended but if I enter "22" once again, it lets it pass and skip to next judge.
How can I make it to keep asking until I have given a valid input before it moves to next judge? Please give a small explanation if you fix my code.
Also I'm supposed to make a small edit that when it sums up the points at the end, it minus the highest and lowest score away, summing up only the points between. So if the points are "3,5,8,9,20" it will take "3 and 20" away and only sums up "5,8 and 9" making it 22.
In your code, you have an if statement to check the input, but if your input doesn't pass your program will accept your next input without checking it.
To fix this, don't progress your program until your input is valid using a while loop, like this:
while(points<0 || points>20) {
System.out.println("You can only give points between 0-20");
System.out.println("Judge "+ (i+1) + " points: ");
points = scanner.nextInt();
}
total+=points;
}

I need of assistance with array assigning user inputs to an array, and do-while loop repeat

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.

Categories