Java grades exercise - java

I'm Adrian and i'm kinda new to programming, would like to learn more and improve. I was asked to do a grade average exercise and i did this , but i'm stuck at making the code so if you type a number instead of a name the code will return from the last mistake the writer did , like it asks for a name and you put "5". In my code gives an error and have to re-run it. Any tips?
import java.util.*;
import java.math.*;
import java.io.*;
class Grades {
public static void main(String[] args) {
int j = 1;
double sum = 0;
double average;
Scanner keyboard = new Scanner(System.in);
System.out.println("Insert Student's Name");
String name = keyboard.next();
System.out.println("Insert Student's Surname");
String surname = keyboard.next();
System.out.println("Student's name: " + name + " " + surname);
System.out.println("How many Grades?");
int nVotes = keyboard.nextInt();
int[] arrayVotes = new int[nVotes];
System.out.println("Now insert all the grades");
for (int i=0; i<arrayVotes.length; i++) {
System.out.println("Insert the grade " + j);
arrayVotes[i] = keyboard.nextInt();
j++;
}
for (int i=0; i<arrayVotes.length; i++) {
sum += arrayVotes[i];
}
average = sum / arrayVotes.length;
System.out.println("Student's grade average is: " + average);
System.out.println("Does he have a good behaviour? Answer with true or false");
boolean behaviourStudent = keyboard.nextBoolean();
average = !behaviourStudent ? Math.floor(average) : Math.ceil(average);
System.out.println("The grade now is: " + average);
keyboard.close();
}
}

At the heart of any solution for this, it requires a loop, and a condition for resetting.
String result = null;
while (result == null) {
//OUT: Prompt for input
String input = keyboard.next();
if (/* input is valid */) {
result = input; //the loop can now end
} else {
//OUT: state the input was invalid somehow
}
//Since this is a loop, it repeats back at the start of the while
}
//When we reach here, result will be a non-null, valid value
I've left determining whether a given input is valid up to your discretions. That said, you may consider learning about methods next, as you can abstract this prompting/verification into a much simpler line of code in doing so (see: the DRY principle)

There are several ways to do it.
But the best way is to use regex to validate the user input.
Have a look at the below code, you can add other validations as well using regex.
import java.util.Scanner;
class Grades {
public static boolean isAlphabetOnly(String str)
{
return (str.matches("^[a-zA-Z]*$"));
}
public static void main(String[] args) {
int j = 1;
double sum = 0;
double average;
Scanner keyboard = new Scanner(System.in);
System.out.println("Insert Student's Name");
String name = keyboard.next();
if(!isAlphabetOnly(name)){
System.out.println("Please enter alfabets only");
return;
}
System.out.println("Insert Student's Surname");
String surname = keyboard.next();
System.out.println("Student's name: " + name + " " + surname);
System.out.println("How many Grades?");
int nVotes = keyboard.nextInt();
int[] arrayVotes = new int[nVotes];
System.out.println("Now insert all the grades");
for (int i=0; i<arrayVotes.length; i++) {
System.out.println("Insert the grade " + j);
arrayVotes[i] = keyboard.nextInt();
j++;
}
for (int i=0; i<arrayVotes.length; i++) {
sum += arrayVotes[i];
}
average = sum / arrayVotes.length;
System.out.println("Student's grade average is: " + average);
System.out.println("Does he have a good behaviour? Answer with true or false");
boolean behaviourStudent = keyboard.nextBoolean();
average = !behaviourStudent ? Math.floor(average) : Math.ceil(average);
System.out.println("The grade now is: " + average);
keyboard.close();
}
}

Related

Need to get the index of the largest value in teamScores[] and print the associated string with the matching index from teamNames[]

Need to get the index of the largest value in teamScores[] and print the associated string with the matching index from teamNames[]. This is really starting to get on my nerves. I had been able to successfully get the right value for the scores printed but it kept printing the wrong team. When I was trying to troubleshoot I was getting the right team but the wrong score. I am absolutely lost and have no other ideas. Anybody offer some advice? I have to use two separate arrays so I cannot just reduce it to one array. I also have to use a for loop to retrieve the values, so I can't do like I did with the lowScore.
public class SmithJustin_Asgn6 {
public static int highScore(int[] teamScores, int highIndex) {
int max = teamScores[0];
for(int i = 0; i < teamScores.length; i++) {
if(max < teamScores[i]) {
max = teamScores[i];
highIndex = i;
}
}return highIndex;
}
public static int lowScore(int[] teamScores) {
Arrays.sort(teamScores);
int low = teamScores[0];
return low;
}
public static void main(String[] args) {
int highIndex = 0;
Scanner userInput=new Scanner(System.in);
Scanner scoreInput=new Scanner(System.in);
System.out.print("Enter the number of teams would you like to enter data for: ");
int teams=scoreInput.nextInt();
int [] teamScores= new int[teams];
String [] teamNames= new String[teams];
for(int i = 0; i < teams; i++) {
System.out.println("\nTeam "+ (i) +":");
System.out.println();
System.out.print("Enter Team's name: ");
String teamName=userInput.nextLine();
teamNames[i]=teamName;
System.out.print("Enter Team's score (400-1000): ");
int teamScore=scoreInput.nextInt();
teamScores[i]=teamScore;
System.out.println();
}
highScore(teamScores, highIndex);
lowScore(teamScores);
System.out.println();
System.out.println("The high score is "+ teamScores[highScore(teamScores, highIndex)] +" by team " + teamNames[highScore(teamScores, highIndex)] + " and the low score is "+ lowScore(teamScores) +".");
userInput.close();
scoreInput.close();
}
}
Been trying every way to slice it and I am completely stuck
You can create a class to store team name and its score. Then sort the array of class objects based on a comparator. Also, you don't need to use two Scanner objects.
class Team
{
public int score;
public String name;
}
class SmithJustin_Asgn6 {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Enter the number of teams would you like to enter data for: ");
int teams = userInput.nextInt();
Team[] teamArray = new Team[teams];
for(int i = 0; i < teams; i++) {
teamArray[i] = new Team();
userInput.nextLine();
System.out.println("\nTeam "+ (i) +":");
System.out.println();
System.out.print("Enter Team's name: ");
teamArray[i].name = userInput.nextLine();
System.out.print("Enter Team's score (400-1000): ");
teamArray[i].score = userInput.nextInt();
System.out.println();
}
userInput.close();
Arrays.sort(teamArray, new Comparator<Team>() {
#Override
public int compare(Team o1, Team o2) {
return Integer.compare(o1.score, o2.score);
}
});
System.out.println();
System.out.println("The high score is "+ teamArray[teams - 1].score +" by team " + teamArray[teams - 1].name + " and the low score is "+ teamArray[0].score +".");
}
}
As mentioned by #Andrey your Arrays.sort is the main culprit. You need a logic to get the low score index the same as you have done for high score index.
public static int lowScore(int[] teamScores, int lowIndex) {
// Arrays.sort(teamScores);
int low = teamScores[0];
//logic to low score's index
return lowIndex;
}
After you have both the indexes, you can easily get values from respective arrays using them.
In your main method you are calling the same methods multiple times instead of that you can do
int lowIndex = 0;
highIndex = highScore(teamScores, highIndex);
lowIndex = lowScore(teamScores, lowIndex);
System.out.println();
System.out.println("The high score is " + teamScores[highIndex] + " by team " + teamNames[highIndex] + " and the low score is " + teamScores[lowIndex] + ".");
Start learning stream. Its easy and fun ;).
int h1 = IntStream.range(0, teamScores.length)
.reduce((i, j) -> teamScores[i] > teamScores[i] ? i : j)
.getAsInt();
int lowScore = Arrays.stream(teamScores).min().getAsInt();
System.out.println("The high score is " + teamScores[h1] + " by team " + teamNames[h1]+ " and the low score is " + lowScore + ".");

How to loop a prompt for a user to re-enter a number if they input a number outside of the parameters

I'm trying to set up a program where the user(student) inputs how many courses they have left to graduate and and how many classes the intend to take per terms and the program will form this data into an array and print out how many terms they have left. The user is not allowed to take more than 5 courses per term so I want to prompt the user that the number they input is incorrect while also looping that input for that specific student without have to close the console and re-run the program. I've tried placing a while(true){} loop there in order to loop it but i can't seem to get the loop i desire.
I've tried placing the while(true){} loop in multiple spots of the code and can't get the desired result.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[][] students = new int[10][2];
for (int i = 0; i < students.length; i++) {
System.out.println("Enter classes remaining and taking each term for student " + (i + 1) + ": ");
for (int j = 0; j < students[i].length; j++) {
students[i][j] = input.nextInt();
if (students[i][1] > 5)
System.out.println("The number of classes per term for student " + (i + 1) + " is invalid.");
}
}
System.out.println();
for (int i = 0; i < students.length; i++) {
System.out.println("Student " + (i + 1) + " has " + (int) Math.round(students[i][0] / students[i][1]) + " terms left to graduate.");
}
}
I expect the output for the first input to print","The number of class per term for student n is invalid." and repeat the prompt to enter the numbers for that same student n without proceeding to the next student input.
Here is the updated one based on your new comments. You should be good from here, make changes whatever you need.
public class StudentInfo
{
public static int totalStudents = 6;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int[][] Students = new int[totalStudents][3];
// Student[i][0] will hold the Remaining classes.
// Student[i][1] will hold the Classes per semester and
// Student[i][2] will hold the number of total Semesters to complete all courses.
for (int i = 0; i < totalStudents; i++)
{
System.out.print("\n\nEnter the information for " + (i + 1) + "-th student.");
System.out.print("\n\nEnter the total number of remaining courses: ");
Students[i][0] = input.nextInt();
System.out.print("\nEnter the total number of courses per semester: ");
Students[i][1] = input.nextInt();
while (Students[i][1] > 5)
{
System.out.println("\nStudents are not allowed to take more than 5 classes per semester.");
System.out.print("Enter the total number of courses per semester: ");
Students[i][1] = input.nextInt();
}
int ts = Students[i][0] / Students[i][1];
if (Students[i][0] % Students[i][1] != 0)
ts++;
Students[i][2] = ts;
System.out.println("\nThis student needs a total of " + ts + " semesters to finish all courses.");
}
input.close();
}
}
public static void main(String[] args) {
//scanner library
Scanner input = new Scanner (System.in);
//Initialize array
int[][] students = new int [10][2];
//iterate scanner and condition loop
for(int i=0; i<students.length; i++){
System.out.print("Enter classes remaining and taking each term for student "+ (i+1) +": ");
for (int j=0; j<students[i].length;j++){
students[i][j]= input.nextInt();
}
while(students [i][1] > 5) {
System.out.println("The number of classes per term for student " + (i+1) + " is invalid.");
i--;
break;
}
}
System.out.println();
//Print out results compiled from array
for(int i =0; i<students.length; i++) {
System.out.println("Student "+(i+1)+" has "+ (int) Math.ceil((double)students[i][0]/students[i][1]) + " terms left to graduate.");
}
}

How do I show the numbers I entered in Java

I'm writing a program where at the end I have to display the numbers I entered and the maximum and minimum of those entered numbers. However I'm running into a little problem, here is my code,
import java.util.*;
public class question3controlstructures {
public static void main (String [] args) {
Scanner in = new Scanner (System.in);
int numberEntered;
int numbersinput = 0;
String answer ="";
double sum = 0;
do {
System.out.println("Enter a number");
numberEntered = in.nextInt();
numbersinput ++;
System.out.println("do you want to enter another number?");
answer = in.next();
sum = sum + numberEntered;
} while (answer.equals("yes"));
System.out.println("The sum is: " + sum);
System.out.println("The average is: " + sum/numbersinput);
System.out.println(numberEntered);
}
}
The above comment are absolutely useful. However, here is little code
package com.mars;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Question3controlstructures {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.print("Enter integers please ");
System.out.println("(EOF or non-integer to terminate): ");
while (scan.hasNextInt()) {
list.add(scan.nextInt());
}
Integer[] nums = list.toArray(new Integer[0]);
int sum = 0;
int i = 0;
for ( ; i < nums.length; i++) {
sum = sum + nums[i];
}
System.out.println("sum..." + sum);
System.out.println("The average is: " + sum / i);
System.out.println(i);
System.out.println("max.. "+Collections.max(list));
System.out.println("min.. "+Collections.min(list));
scan.close();
}
}
As suggent in comments , you need a list to store the multiple numbered entered.
just compare the min and max every time you enter a number
int min = Integer.MAX_VALUE
int max = Integer.MIN_VALUE
int numberEntered;
int numbersinput = 0;
String answer ="";
double sum = 0;
do {
System.out.println("Enter a number");
numberEntered = in.nextInt();
System.out.println("YOU HAVE ENTERED: " + numbersEntered);
if (min > numberEntered) min = numberEntered;
if (max < numberEntered) max = numberEntered;
numbersinput ++;
sum = sum + numberEntered;
System.out.println("do you want to enter another number?");
answer = in.next();
} while (answer.equals("yes"));
System.out.println("The sum is: " + sum);
System.out.println("The average is: " + sum/numbersinput);
System.out.println(numberEntered);
//you can print your min max here.
The IntSummaryStatistics class together with Java 8's Stream API may be less verbose than dealing with min, max, sum and avg calculation manually.
public static void main(String[] args) {
// Get user input.
List<Integer> numbers = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
// No user friendly way to gather user input, improve!
numbers.add(scanner.nextInt());
}
// Transform input to statistics.
IntSummaryStatistics stats = numbers.stream()
.collect(Collectors.summarizingInt(Integer.intValue()));
// Print statistics.
String jointNumbers = numbers.stream()
.collect(Collectors.joining(", "));
System.out.printf("You entered %d numbers: %s\n, stats.getCount(), jointNumbers);
System.out.println("Min: " + stats.getMin());
System.out.println("Max: " + stats.getMax());
System.out.println("Sum: " + stats.getMax());
System.out.println("Avg: " + stats.getAverage());
}

How do you incorperate an AVERAGE and LETTERGRADE in a java program which has 2D Array

I have written a program with minimal errors but do not know where I should place the Average or Letter grade function:
package org.education.tutorial;
import java.util.Scanner;
public class GradingScale
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter the number of students attending your current session :");
int numberOfStudents = keyboard.nextInt();
System.out.println();
System.out.print("Also, please enter the amount of exams taken during the duration of the course : ");
int examScores = keyboard.nextInt();
AssignValueToArray(numberOfStudents, examScores);
keyboard.close();
}
public static void AssignValueToArray(int amountOfStudents, int amountOfExams)
{
int[][] overallScore = new int[amountOfStudents][amountOfExams];
Scanner keyboardArray = new Scanner(System.in);
int numberValue = 1;
for (int index = 0; index < amountOfStudents; index++)
{
System.out.println ("\n" + "Please submit Student #" + numberValue + " 's score :" );
for(int indexOfHomeWork=0; indexOfHomeWork < amountOfExams; indexOfHomeWork++)
{
overallScore[index][indexOfHomeWork] = keyboardArray.nextInt();
}
numberValue++;
}
DisplayvalueInArray(overallScore);
keyboardArray.close();
}
public static void DisplayvalueInArray(int[][] overallScoreArray)
{
System.out.println ("The students' scores are posted below : " + "\n");
int studentCount = 1;
for (int index = 0; index < overallScoreArray.length; index++)
{
System.out.print("Grades for student " + studentCount +": ");
for (int indexOfHomeWork = 0; indexOfHomeWork < overallScoreArray[index].length;
indexOfHomeWork++)
{
System.out.print(overallScoreArray[index][indexOfHomeWork]+"\t");
}
System.out.println();
studentCount++;
}
}
I would highly recommend learning how to use variable scope and possibly objects before doing something such as this.
You never declare any variables in the class's scope.
Most of your functions don't affect anything outside their own scope, and therefore shouldn't be functions. Instead use comments to encapsulate.
Many of your variables are named poorly, instead of keyboardArray, which is not an array at all, do something like kb, or keyboardScanner
For computing average and lettergrades, think 'what am i averaging' and use that as your parameter, with the average as your return type, so something like static int average(int[] scores)

Methods unindentified error in java

I wrote a small program consisting of two classes. I am trying to call the methods from the second class but I get an error.
The error is:
Exception in thread "main" java.lang.Error: Unresolved compilation
problems: The method getSum(int[]) is undefined for the type
UserInteraction The method getAverage(int[]) is undefined for the type
UserInteraction at UserInteraction.main(UserInteraction.java:66)
Here's the code of the first class:
import java.util.Scanner;
public class UserInteraction {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int choice = 0;
String[] subjects = new String[10];
int grades[] = new int[10];
double sum = 0.0;
Grades method = new Grades();
do
{
System.out.println("1. Enter a course name and a grade");
System.out.println("2. Display all grades");
System.out.println("3. Calculate the average grade");
System.out.println("4. Exit program");
choice = scan.nextInt();
if ( choice == 1 )
{
Scanner scansubjects = new Scanner(System.in);
Scanner scangrades = new Scanner(System.in);
System.out.println("Enter 10 subjects and their corresponding grades:");
System.out.println();
int i = 0;
for( i = 0; i < 10; i++ )
{
System.out.println("Subject:");
String temp = scansubjects.nextLine();
subjects[i] = temp.toLowerCase();
System.out.println("Grade:");
grades[i] = scangrades.nextInt();
if( i == ( subjects.length - 1 ) )
{
System.out.println("Thank you!");
System.out.println();
}
}
}
if ( choice == 2 )
{
System.out.println("Subjects" + "\tGrades");
System.out.println("---------------------");
for(int p = 0; p < subjects.length; p++)
{
System.out.println(subjects[p] + "\t" + "\t" + grades[p]);
}
}
if ( choice == 3 )
{
System.out.println("Total of grades: " + getSum(grades));
System.out.println("Count of grades: " + grades.length);
System.out.println("Average of grades: " + getAverage(grades));
System.out.println();
}
} while ( choice != 4);
}
}
And the second class is:
public class Grades {
public static double getAverage(int[] array)
{
int sum = 0;
for(int i : array) sum += i;
return ( ( double ) sum )/array.length;
}
public static double getSum(int[] array)
{
int sum = 0;
for (int i : array)
{
sum += i;
}
return sum;
}
}
You don't need this, because it only has static methods:
Grades method = new Grades(); // <-- delete this line
To call static methods they must be preceded with their class name like this:
System.out.println("Total of grades: " + Grades.getSum(grades));
System.out.println("Count of grades: " + grades.length);
System.out.println("Average of grades: " + Grades.getAverage(grades));
Your code doesn't compile. Don't try to execute non-compiling code. Fix all the compilation errors before executing the code. They're visible in the "Problems" view of your Eclipse IDE.
You need to call Grades.getSum and Grades.getAverage to get the right result. Also, don't forget to import the Grade class, using the command import Grades; in the beginning of the UserInteraction class.

Categories

Resources