Questions about one dimensional arrays and sorting in Java - java

I'm currently in the second half of a computer science class but I wasn't able to take the second one right after the first one. So I've forgot a large portion of my coding knowledge. I'm trying to re learn it all but it's quite tough without just going all the way back to the basics.
An assignment I'm working on currently is asking me to do the following:
Design a solution that requests and receives student names and an exam score for each. Use one-dimensional arrays to solve this.
The program should continue to accept names and scores until the user inputs a student whose name is “alldone”.
After the inputs are complete determine which student has the highest score and display that student’s name and score.
Finally sort the list of names and corresponding scores in ascending order.
I wasn't really sure how to organize and start this but I went ahead and just started writing some code to at least make some progress and maybe figure something out.
The way I've set up my program doesn't exactly respond to the prompt as I was experimenting with array lengths and for loops to get reacquainted.
SO MY QUESTION IS, How would I make it so when users type "alldone" the program stops taking inputs and calculates the highest grade with the person who had it only using 1D Arrays.
Is it possible to take the names as a string and then insert the strings into an array?
Here is my code so far, It's not what the assignment is looking for but I just want to get some inspiration on some things I could do:
public static void main(String[] args) {
int studentcount;
Scanner input = new Scanner(System.in);
Scanner sc= new Scanner(System.in);
//Input to set array length
System.out.println("How many students are you grading? ");
studentcount=sc.nextInt();
//One dimensional array to hold student names/grades
String [] names = new String [studentcount+1];
int [] grades = new int [studentcount];
//Input to record student names/grades
System.out.println("Please enter the name of the students ");
for (int i = 0; i < names.length; i++) {
names[i] = sc.nextLine();
}
System.out.println("Please enter the grades of the students ");
for (int i = 0; i < grades.length; i++) {
grades[i] = sc.nextInt();
}
// For loop to display student names and grades
for (int i = 0; i < studentcount; i++) {
System.out.println(names[i+1] + " " + grades[i]);
}}}
The output looks like this:
How many students are you grading?
3
Please enter the name of the students
John
Brett
Wendy
Please enter the grades of the students
10
20
30
John 10
Brett 20
Wendy 30

It doesn't make sense to enter the number of students and also signal the end of input with a keyword. Since you must key in on "alldone" to stop taking input, it is implied (to me) you must initially over allocate you arrays. I chose 3 for demo purposes. If more input is required the arrays can be adjusted as demonstrated. This example simply explains how to take in the data and populate the arrays. It does not deal with the mechanics of sorting as that was not part of your question.
int studentCount = 0;
Scanner input = new Scanner(System.in);
// allocate space for three students
String[] names = new String[3];
int[] grades = new int[3];
int maxInput = names.length;
System.out.println(
"Please enter name and grade of student (e.g. john 23)\non each line.");
// now enter the student and their grade
for (int i = 0; i < maxInput; i++) {
String name = input.next();
// this is where you check for the keyword to signal
// end of input
if (name.equals("alldone")) {
break;
}
names[studentCount] = name;
grades[studentCount++] = input.nextInt();
// if you have maxed out your arrays you need to copy
// the contents to a larger array
if (studentCount == maxInput) {
// increase array size
maxInput += 3; // increase by 3.
names = Arrays.copyOf(names, maxInput);
grades = Arrays.copyOf(grades, maxInput);
}
}
// once here, the input part is over. This displays the entered data
for (int i = 0; i < studentCount; i++) {
System.out.println(names[i] + " " + grades[i]);
}
Note, at this point it is possible that your arrays will contain extra spaces that could affect your sort (and possibly cause an error). You can trim the excess space using Arrays.copyOf as before, specifying the number of students.
Or if you sort using your own routine, you can ignore the excess spaces by using studentCount instead of the length of the arrays.

You should create a class and implement the Comparable interface like this. The way I have it set up here, it sorts by name. If you want to sort by the score, just comment out the name compare and uncomment the grade compare.
public class Student implements Comparable<Student> {
private String name;
private int grade;
public Student(String name, int grade) {
this.name = name;
this.grade = grade;
}
public String getName() {
return name;
}
public int getGrade() {
return grade;
}
#Override
public int compareTo(Student o) {
//sorting by name
return name.compareTo(o.name);
//Compare by grade -- reversed so it's highest first
//return Integer.compare(o.grade, grade);
}
#Override
public String toString() {
return "Student [name=" + name + ", grade=" + grade + "]";
}
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
Student [] students = new Student[0];
while(true) {
System.out.println("Please enter the name of the student or \"alldone\" if complete: ");
String name = input.next();
if (name.contentEquals("alldone")) {
break;
}
System.out.println(String.format("Please enter %s's grade: ", name));
int grade = input.nextInt();
input.reset();
students = Arrays.copyOf(students, students.length+1);
students[students.length-1] = new Student(name, grade);
}
Arrays.sort(students);
for (Student student : students) {
System.out.println(student);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Related

Loop amount of times given inside a For Loop

I have a For Loop and it's asking the user how many times the loop should be looped inside the loop. How do I loop it the number of times given without repeating the question "how many names would you like to input"?
The issue is that I don't want to repeat the question after the user answered it. When the user answers the question, I want it to ask for the names x amount of times and then move on.
The main problem is that I need to ask how many times to loop it after the name is asked. It's says it the assignment sheet.
Thanks so much!
for (int i = 0; i < num; i++) {
System.out.println("Enter name #" + (i+1));
names[i] = input.next();
System.out.println("How many names would you like to input?");
num = input.nextInt;
}
You must move your num getter code outside of loop like this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many names would you like to input?");
int num = input.nextInt();
String names[] = new String[num];
for (int i = 0; i < num; i++) {
System.out.println("Enter name #" + (i+1));
names[i] = input.next();
}
}
Always move these kinds of questions out of the loop rather than inside.
System.out.println("How many names would you like to input?");
num = input.next();
for (int i = 0; i < num; i++) {
System.out.println("Enter name #" + (i+1));
names[i] = input.next();
}
num = input.next();
You are asking a numbers not a string should change the .next() to either nextInt or nextShort.
#DevilsHnd the first code won't work indeed, I never saw that String [] = new String [] use array before plus this will explain better why.
#J.A.P link with code may work
import java.util.Scanner;
public class Newpro{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("how many times you want to loop?")
int num = sc.nextInt();//input the no of times you want to loop
String names[i] = new String[num];//initialize a string array for reading names
for(i=0;i<num;i++){
System.out.println("enter name#"+(i+1));
names[i]=sc.next();
}
for(j=0;j<num;j++){
//printing the names entered by you
System.out.println("the entered names by you are"+" "+names[j]);
}
as others suggested, you have to move your 'num' getter part out of the loop and after that initialize a string array for reading your names by specifying how many names you want to enter(index of string array = number of names you want to enter and no of times you want to loop as well==>'num') and based on that number the looping will be done with above code.
finally iterate through the array and print the names entered by you.
Edit:1
check with the below code if you need to ask "how many names user wants to input AFTER it asks for a first name.
import java.util.Scanner;
public class Newpro2{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
//make sure you create a string array with index = no of names you want to
//enter
String[] names = new String[10];
System.out.println("enter name#1");
names[0]= sc.next();
System.out.println("how many inputs you want to give?");
num=sc.nextInt();//give the no of inputs you want to give here
//read the remaining names
for(int i=1;i<num;i++){
System.out.println("enter name#"+(i+1));
names[i] = sc.next();
}
//print all the names entered by you
for(int j=0;j<num;j++){
System.out.println("entered name#"+(j+1)+"by you is"+" "+names[j]);
}

Store user input in array multiple times

I'm working on a project which...
Allows the user to input 4 numbers that are then stored in an array for later use. I also want every time the user decided to continue the program, it creates a new array which can be compared to later to get the highest average, highest, and lowest values.
The code is not done and I know there are some things that still need some work. I just provided the whole code for reference.
I'm just looking for some direction on the arrays part.
*I believe I am supposed to be using a 2-D array but I'm confused on where to start. If I need to explain more please let me know. (I included as many comments in my code just in case.)
I tried converting the inputDigit(); method to accept a 2-D array but can't figure it out.
If this question has been answered before please redirect me to the appropriate link.
Thank you!
package littleproject;
import java.util.InputMismatchException;
import java.util.Scanner;
public class littleProject {
public static void main(String[] args) {
// Scanner designed to take user input
Scanner input = new Scanner(System.in);
// yesOrNo String keeps while loop running
String yesOrNo = "y";
while (yesOrNo.equalsIgnoreCase("y")) {
double[][] arrayStorage = inputDigit(input, "Enter a number: ");
System.out.println();
displayCurrentCycle();
System.out.println();
yesOrNo = askToContinue(input);
System.out.println();
displayAll();
System.out.println();
if (yesOrNo.equalsIgnoreCase("y") || yesOrNo.equalsIgnoreCase("n")) {
System.out.println("You have exited the program."
+ " \nThank you for your time.");
}
}
}
// This method gets doubles and stores then in a 4 spaced array
public static double[][] inputDigit(Scanner input, String prompt) {
// Creates a 4 spaced array
double array[][] = new double[arrayNum][4];
for (int counterWhole = 0; counterWhole < array.length; counterWhole++){
// For loop that stores each input by user
for (int counter = 0; counter < array.length; counter++) {
System.out.print(prompt);
// Try/catch that executes max and min restriction and catches
// a InputMismatchException while returning the array
try {
array[counter] = input.nextDouble();
if (array[counter] <= 1000){
System.out.println("Next...");
} else if (array[counter] >= -100){
System.out.println("Next...");
} else {
System.out.println("Error!\nEnter a number greater or equal to -100 and"
+ "less or equal to 1000.");
}
} catch (InputMismatchException e){
System.out.println("Error! Please enter a digit.");
counter--; // This is designed to backup the counter so the correct variable can be input into the array
input.next();
}
}
}
return array;
}
// This will display the current cycle of numbers and format all the data
// and display it appropriatly
public static void displayCurrentCycle() {
int averageValue = 23; // Filler Variables to make sure code was printing
int highestValue = 23;
int lowestValue = 23;
System.out.println(\n--------------------------------"
+ "\nAverage - " + averageValue
+ "\nHighest - " + highestValue
+ "\nLowest - " + lowestValue);
}
public static void displayAll() {
int fullAverageValue = 12; // Filler Variables to make sure code was printing
int fullHighestValue = 12;
int fullLowestValue = 12;
System.out.println(" RESULTS FOR ALL NUMBER CYCLES"
+ "\n--------------------------------"
+ "\nAverage Value - " + fullAverageValue
+ "\nHighest Value - " + fullHighestValue
+ "\nLowest Value - " + fullLowestValue);
}
// This is a basic askToContinue question for the user to decide
public static String askToContinue(Scanner input) {
boolean loop = true;
String choice;
System.out.print("Continue? (y/n): ");
do {
choice = input.next();
if (choice.equalsIgnoreCase("y") || choice.equalsIgnoreCase("n")) {
System.out.println();
System.out.println("Final results are listed below.");
loop = false;
} else {
System.out.print("Please type 'Y' or 'N': ");
}
} while (loop);
return choice;
}
}
As far as is understood, your program asks the user to input four digits. This process may repeat and you want to have access to all entered numbers. You're just asking how you may store these.
I would store each set of entered numbers as an array of size four.
Each of those arrays is then added to one list of arrays.
A list of arrays in contrast to a two-dimensional array provides the flexibility to dynamically add new arrays.
We store the digits that the user inputs in array of size 4:
public double[] askForFourDigits() {
double[] userInput = new double[4];
for (int i = 0; i < userInput.length; i++) {
userInput[i] = /* ask the user for a digit*/;
}
return userInput;
}
You'll add all each of these arrays to one list of arrays:
public static void main(String[] args) {
// We will add all user inputs (repesented as array of size 4) to this list.
List<double[]> allNumbers = new ArrayList<>();
do {
double[] numbers = askForFourDigits();
allNumbers.add(numbers);
displayCurrentCycle(numbers);
displayAll(allNumbers);
} while(/* hey user, do you want to continue */);
}
You can now use the list to compute statistics for numbers entered during all cycles:
public static void displayAll(List<double[]> allNumbers) {
int maximum = 0;
for (double[] numbers : allNumbers) {
for (double number : numbers) {
maximum = Math.max(maximum, number);
}
}
System.out.println("The greatest ever entered number is " + maximum);
}

How do you use a method to calculate 1 array parameter of grades and returns the total of the array?

My schoolwork is asking me to write a Java program. I'm not getting something quite right.
Basically I have to create a Java method that gets a user to enter x amount of grades (users choice), store the grades in an array and then add the grades in the array up to be called in the main method.
Here's my code:
import java.util.Scanner;
public class Sample {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Hello Drews, how many total grades do you want to process?");
int numberOfGrades = keyboard.nextInt();
int [] storeGrades = new int[numberOfGrades];
}
public static int getTotalScore(int numberOfGrades[]) {
Scanner keyboard = new Scanner(System.in);
int getTotalScore;
int []storeGrades;
for (int i = 0; i < getTotalScore; i++) {
System.out.println("Please enter grade " + (i + 1) + ": ");
int userGradeNumbers = keyboard.nextInt();
storeGrades[i] = userGradeNumbers;
sum += userGradeNumbers;
}
}
}
I'm getting an error at "sum" that it hasn't been resolved to a variable? It won't let me initialize sum within the for loop, nor the getTotalScore method. Why not?
First, get the grades. Then call the method to get the sum. Declare the sum and initialize it to 0 before your loop. Return it after. Like,
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Hello Drews, how many total grades do you want to process?");
int numberOfGrades = keyboard.nextInt();
int[] storeGrades = new int[numberOfGrades];
for (int i = 0; i < numberOfGrades; i++) {
System.out.println("Please enter grade " + (i + 1) + ": ");
storeGrades[i] = keyboard.nextInt();
}
System.out.println(getTotalScore(storeGrades));
}
public static int getTotalScore(int[] storeGrades) {
int sum = 0;
for (int i = 0; i < storeGrades.length; i++) {
sum += storeGrades[i];
}
return sum;
}
Your code has the right intent about it, but some of the ordering of things is a little off and there are syntactical issues at the moment.
I would advocate splitting up your code into two methods (unless you're specifically prohibited from doing so based on the assignment). One method to get the grades from the user, and another to sum the grades. The reason for this, is that you end up trying to both store and sum the grades at the same time (which is technically more efficient), but that doesn't teach you how to calculate a running total by iterating over an array (which is likely the point of the lesson).
One other thing that I would call out (which may be beyond where you are in the course right now), is that when you're using a Scanner, you need to validate that the user has typed what you think they've typed. It's entirely plausible that you want the user to type a number, and they type "Avocado." Because Java is strongly typed, this will cause your program to throw an exception and crash. I've added in some basic input validations as an example of how you can do this; the general idea is:
1) Check that the Scanner has an int
2) If it doesn't have an int, ask the user to try again
3) Else, it has an int and you're good to proceed. Store the value.
One last thing about Scanners. Remember to close them! If you don't, you can end up with a memory leak as the Scanner continues to run.
Below is how I would have revised your code to do what you want. Shoot me a comment if something doesn't make sense, and I'll explain further. I left comments inline, as I figured that was easier to digest!
package executor;
import java.util.Scanner;
public class StudentGrades {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
// Initial prompt to the user
System.out.println("Hello Drews, how many total grades do you want to process?");
// This loop validates that the user has actually entered an integer, and prevents
// an InputMismatchException from being thrown and blowing up the program.
int numberOfGrades = 0;
while (!keyboard.hasNextInt()) {
System.out.println("Sorry, please enter a valid number!");
keyboard.next();
}
// If the program makes it through the while loop, we know that the Scanner has an int, and can assign it.
numberOfGrades = keyboard.nextInt();
// Creating the array using the method getGrades().
int[] storedGrades = getGrades(numberOfGrades, keyboard);
// Calculating the total score using the method getTotalScore().
int totalScore = getTotalScore(storedGrades);
System.out.println("Total Score is: " + totalScore);
keyboard.close();
}
/**
* Asks the user to provide a number of grades they wish to sum.
* #param numberOfGrades the total number of grades that will be requested from the user.
* #param keyboard the scanner that the user will use to provide the grades.
* #return the summed grades as an int.
*/
public static int[] getGrades(int numberOfGrades, Scanner keyboard) {
int[] grades = new int[numberOfGrades];
// Asking the user i number of times, to enter a grade to store.
for (int i = 0; i < numberOfGrades; i++) {
System.out.println("Please enter grade " + (i + 1) + ":");
// More input validation to ensure the user can't store "Cat."
while (!keyboard.hasNextInt()) {
System.out.println("Sorry, please enter a valid number!");
keyboard.next();
}
int userEnteredGrade = keyboard.nextInt();
// Storing the user's entry.
grades[i] = userEnteredGrade;
}
return grades;
}
/**
* Sums all of the grades stored within an integer array.
* #param storedGrades the grades to be summed.
* #return the total value of summed grades.
*/
public static int getTotalScore(int[] storedGrades) {
int totalScore = 0;
for (int i = 0; i < storedGrades.length; i++) {
totalScore += storedGrades[i];
}
return totalScore;
}
}

Specific index of Array

So I'll give you some brief background, I'm in AP computer science and I'm confused on this program.
We are suppose to enter in the size of the array, then the program runs through a for loop, get the full name in one string, ( use scanner.nextLine();), then the test Score, which isn't that important. The user then will enter the first name of ANYONE and there should be a for loop running through each array seeing if firstName is in the first name array.
The problem is firstName when is printed out is blank.. fixed the first error.
import java.util.Scanner;
public class totalScores {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.println("Enter the size of the array: ");
int sizeOfArray = input.nextInt();
String kline[] = new String[sizeOfArray];
for ( int index= 0; index< kline.length; index++)
{
System.out.println("Enter the name: ");
String name = input.next();
kline[index]= name;
input.nextLine();
}
double[] testScore= new double[sizeOfArray];
for (int i = 0; i< testScore.length; i++)
{
System.out.println("enter the test score");
double testz = input.nextDouble();
testScore[i]= testz;
input.nextLine();
}
System.out.println("Enter first name : ");
String want = input.next();
for( int index = 0; index < kline.length; index++)
{
String firstName="";
String namez;
namez = kline[index];
int space = namez.indexOf("");
firstName = namez.substring(0,space);
if (want.equalsIgnoreCase(firstName))
{
System.out.println("The test score is: "+ testScore[index]);
}
else
{
System.exit(0);
}
}
}
}
Your example is not too clear but I can see the for loop is running with kline.length as the limit, but you are getting nameofarray[index] which could be an array with different size than kline.
Possibly the problem is here:
int space = namez.indexOf(" ");
In case the namez don't contain spaces in it, the value for space will be -1. So it will form this statement:
namez.substring(0, -1)
Of-course you will encounter exception.
Try doing this:
String firstName = kline[index].split(" ")[0];
System.out.println(firstName);
This will return the first word of kline[index] even if it doesn't contain a space.
The error is occurring most likely because your kline[index] does not contain a space (therefore, indexOf(" ") returns -1. And you cant substring with (0,-1)

Using a loop to print output of arrays?

import java.io.*;
import java.util.*;
public class AP_ExamArray
{
//User Input AP Exam Scores Using For Loops
public static void main(String args[])
{
int [] scores = new int[5];
int j;
int sum_exam=0;
for (j=0; j<scores.length; j++)
{
Scanner kbReader = new Scanner(System.in);
System.out.println("Please enter AP Exam Score (1-5): ");
scores[j]=kbReader.nextInt();
sum_exam+=scores[j];
}
//Initializer List Final Percentage
double [] final_percent = {97.3, 89.8, 96.2, 70.1, 93.0};
double sum_percent=0;
int k;
for(k=0; k<final_percent.length;k++)
{
sum_percent+=final_percent[k];
}
// String array containing last name (while loop)
String [] last_name = new String[5];
int i=0;
while (i<last_name.length)
{
Scanner kbReader = new Scanner(System.in);
System.out.println("Please enter last name: ");
last_name[i]=kbReader.next();
i++;
}
//Average Exam Scores
double avg_exam = (double) sum_exam/scores.length;
//Average Final Percentage
double avg_percent = (double) sum_percent/final_percent.length;
}
}
The directions are:
"For your output use a loop to print the student names, percentages, and test score, and be sure to include appropriate data below each column heading:
Student Name Student Percentage Student Test Score."
I'm not sure how to do this!
How about:
for(i=0; i<scores.length; i++)
System.out.println(last_names[i] +"\t"+ final_percent[i] +"\t"+ scores[i]);
A for loop is used because you want to loop through the entire
array of a known size.
If, instead, you wanted to loop only while a certain condition holds
you would use a while loop: (e.g. while(condition) loop;).
System.out.println() will print a new line after each call, and \t will add a tab.
For better formatting check out this Oracle doc on using printf and format

Categories

Resources