Novice java code about sorting numbers - java

This is the code I was working on in class. I would be asking my teacher but today is a sunday.
okay straight off the bat, I need to sort through some numbers and find the highest number and the lowest.
So what works and what doesn't?
The code finds the highest number under the variable of iMax. With the tweaking of a new variable name iMin, and a < (lesser sign) it should be giving me the lowest number found but it doesn't and that's the problem. Instead its telling me 0.0 and that is not one of the many random numbers I could choose. To put it plainly, the numbers 1000,2000,3000,4000,5000. it tells me 5000 is the highest number and 0.0 was the lowest. 0.0 was not one of my numbers and I have scratched my head for too long, please help me with this problem as it is driving me up the wall. So here's the code:
import java.util.Scanner;
public class JustWork {
public static void main(String[] args) {
double [] run1 = new double[7];
double iMax = run1[0];
double iMin = run1[0];
Scanner input = new Scanner(System.in);
for (int i = 0; i<run1.length; i++)
{
System.out.println("Score from Judge " + (i+1) + ": ");
run1[i] = input.nextDouble();
}
for (int i = 1; i<run1.length; i++)
{ if (run1[i]< iMin)
iMin = run1[i];
}
for (int i = 1; i<run1.length; i++)
{ if (run1[i]> iMax)
iMax = run1[i];
}
System.out.println("the minimum score is: " + iMin);
System.out.println("the maximum score is: " + iMax);
}
}
For example, if I put in the following numbers:3,4,5,6,7,8,9 System.out.prints out this:
Score from Judge 1:
3
Score from Judge 2:
4
Score from Judge 3:
5
Score from Judge 4:
6
Score from Judge 5:
7
Score from Judge 6:
8
Score from Judge 7:
9
the minimum score is: 0.0
the maximum score is: 9.0

When you initialize the double array, they are by default assigned 0s for each element.Then when you assign run1[0] to iMin and iMax, you have already set 0 as min implicitly.
To avaoid that, just assign the initial values after getting the input
public static void main(String[] args) {
double [] run1 = new double[7];
Scanner input = new Scanner(System.in);
for (int i = 0; i<run1.length; i++)
{
System.out.println("Score from Judge " + (i+1) + ": ");
run1[i] = input.nextDouble();
}
double iMax = run1[0];
double iMin = run1[0];
for (int i = 1; i<run1.length; i++)
{ if (run1[i]< iMin)
iMin = run1[i];
}
for (int i = 1; i<run1.length; i++)
{ if (run1[i]> iMax)
iMax = run1[i];
}
System.out.println("the minimum score is: " + iMin);
System.out.println("the maximum score is: " + iMax);
}

Initialize iMin and iMax after your first for loop. When you initialize before, then the values are 0.
double [] run1 = new double[7]; // <-- an array of 7 elements, all 0.0
// double iMax = run1[0]; // <-- 0.0
// double iMin = run1[0]; // <-- 0.0
Scanner input = new Scanner(System.in);
for (int i = 0; i < run1.length; i++)
{
System.out.println("Score from Judge " + (i+1) + ": ");
run1[i] = input.nextDouble();
}
double iMax = run1[0];
double iMin = run1[0];

Related

Display Min/Max array

The final output will show who has the highest grade and who has the lowest grade.
I'm lost on how to call the lowest name/grade to the final output.
In the code I have some comments on where I'm stuck with the "currentMinIndex", the "currentMaxIndex" works just fine and will show it to the final output. I tried to mirror it but it isn't going how I expected. Not sure if something with "(int k = 1; k>= m; k++)" is incorrect.
import java.util.*;
public class MyArrayEX {
// Sort grades lowest on top
public static int[] reverseInt(int[] array) {
int[] input = new int[array.length];
for (int i = 0, j = input.length - 1; i < array.length; i++, j--) {
input[j] = array[i];
}
return input;
}
public static void main(String[] args) {
// Scanners
Scanner input = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
// Input amount
System.out.print("\nEnter number of students: ");
int numOfStu = input.nextInt(); // Number of Students
int[] grades = new int[numOfStu];
String[] names = new String[numOfStu];
// Start loop, amount is based off of "numOfStu"
for (int i = 0; i < numOfStu; i++) {
System.out.print("\rEnter student first name: ");
String name = keyboard.next();
System.out.print("Enter the students grade: ");
int grade = input.nextInt();
// Assigning i
names[i] = name;
grades[i] = grade;
//System.out.println("");
}
// This is the area that sorts it from least to greatest
// i is the indexed value of the last number in array
for (int i = grades.length - 1; i > 0; i--) {
// Resets both to 0 to start at the beginning of the array
int currentMax = grades[0];
int currentMaxIndex = 0;
// i is back-limit that gets chopped off by one each time
for (int k = 1; k <= i; k++) {
if (currentMax < grades[k]) {
currentMax = grades[k];
currentMaxIndex = k;
}
}
// This is where im lost on how to call the min value
// Trying to mirror the one above but using it
// to show the minimum grade along with the name
for (int m = grades.length - 1; i > 0; i--) {
int currentMin = grades[0];
int currentMinIndex = 0;
// Min grades
for (int k = 1; k >= m; k++) {
if (currentMin < grades[m]) {
currentMin = grades[m];
currentMinIndex = m;
}
}
// After largest number is found, assign that number to i
// Im trying to have the final output show the min/max grade with who has it
// Would the MinIndex be assigned to a different variable?
grades[currentMaxIndex] = grades[i];
grades[currentMinIndex] = grades[m];
grades[i] = currentMax;
grades[m] = currentMin;
String highName = names[currentMaxIndex];
String lowName = names[currentMinIndex];
names[currentMaxIndex] = names[i];
names[currentMinIndex] = names[m];
names[i] = highName;
names[m] = lowName;
// This shows the name and grade for the highest number
System.out.print("\rThe highest grade is " + highName + " with a " + currentMax);
// Unsure how to call this.
System.out.println("\r and the Lowest grade is " + lowName + " with a " + currentMin);
}
}
input.close();
keyboard.close();
}
}
Your code has multiple problems. First is with the 2 scanners that you are using for same System.in input stream and second you are using nested loops to find the min/max values which is totally unnecessary. Since the question is about finding the min/max so I will focus on that part only and for the scanner I would say remove the keyboard scanner and use only input scanner. Anyways, use the following code block to find the maximum and minimum grades with names:
int currentMaxIndex = 0;
int currentMinIndex = 0;
// Get min max
for (int i = 1; i<grades.length; i++) {
if (grades[currentMaxIndex]<grades[i]) {
currentMaxIndex=i;
}
if (grades[currentMinIndex]>grades[i]) {
currentMinIndex=i;
}
}
String highName = names[currentMaxIndex];
String lowName = names[currentMinIndex];
int currentMax = grades[currentMaxIndex];
int currentMin = grades[currentMinIndex];
System.out.print("\rThe highest grade is " + highName + " with a " + currentMax);
System.out.println("\r and the Lowest grade is " + lowName + " with a " + currentMin);
The approach is quite simple. We first aasume that the first element in the grades array is min and max then we loop to the remaining elements from 1 to grades.length and compare the index min/max to the current index element values and accordingly change our min/max indices. If the current index value is greater than currentMaxIndex then we copy it to currentMaxIndex and same but opposite for currentMinIndex. So in the end we will have the highest and lowest value indices of grades array. The complete code is here https://ideone.com/Qjf48p

How do i find max and min of an nested ArrayList?

Let's say i have N ArrayLists and inside them, there are M other ArrayLists, so i'm trying to find the min and max of each of these M ArrayLists, what's the best way to do that?
ArrayList<String> myname = new ArrayList<String>(n);
ArrayList<Integer> myscore = new ArrayList<Integer>(m);
for (int i = 0; i < n; i++) {
System.out.println("enter name of contestant");
myname.add(input.next());
for (int j = 0; j < m; j++) {
System.out.println("enter score");
myscore.add(input.nextInt());
}
You can use IntSummaryStatistics class:
IntSummaryStatistics istats = IntStream.of(1,22,33,44,55).
collect(IntSummaryStatistics::new, IntSummaryStatistics::accept,
IntSummaryStatistics::combine);
System.out.println("Max: "+istats.getMax()+", Min: "+istats.getMin());
// Max: 55, Min: 1
Your question is not that much explanatory. Lets say that you want to add the names of some student and you also want to save the corresponding marks obtained by each student. So you will need three ArrayList reference variable. First one is for storing the names, second one is for storing the marks obtained by the student, and the third one is for storing the ArrayList of marks obtained by a single student. Here goes the code
package exmaple;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Finder {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int n = userInput.nextInt();
int m = userInput.nextInt();
ArrayList<String> names = new ArrayList<String>(n);
ArrayList<Integer> numbers;
ArrayList<ArrayList<Integer>> holderOfMarksArayList = new ArrayList<ArrayList<Integer>>();
for(int i = 0; i<n; i++) {
System.out.println("Enter name of contentant.");
String name = userInput.next();
names.add(name);
numbers = new ArrayList<Integer>(m);
for(int j = 0; j<m; j++) {
System.out.println("Enter score.");
numbers.add(userInput.nextInt());
}
holderOfMarksArayList.add(numbers);
}
int counter = 0;
for(String name : names) {
numbers = holderOfMarksArayList.get(counter);
Collections.sort(numbers);
int maxScore = numbers.get(numbers.size() - 1);
int minScore = numbers.get(0);
System.out.println(name +", Max Score = " + maxScore + " Min Score = " + minScore);
counter++;
}
userInput.close();
}
}
If you try with the following input
AAA = 20, 80, 10
XXX = 66, 98, 96
YYY = 65, 12, 76
You will get the following output
AAA, Max Score = 80 Min Score = 10
XXX, Max Score = 98 Min Score = 66
YYY, Max Score = 76 Min Score = 12
You can use Collections.max(arrayList). Just to illustrate how it works.
public static void main(String[] args)
{
ArrayList<ArrayList<Integer>> n = new ArrayList<>();
ArrayList<Integer> m0 = new ArrayList<>();
ArrayList<Integer> m1 = new ArrayList<>();
m0.add(100);
m0.add(200);
m0.add(300);
m0.add(400);
n.add(m0);
m1.add(10);
m1.add(20);
m1.add(30);
m1.add(40);
n.add(m1);
System.out.println(n);
System.out.println(Collections.max(n.get(0)));
System.out.println(Collections.min(n.get(0)));
System.out.println(Collections.max(n.get(1)));
System.out.println(Collections.min(n.get(1)));
}
RUN
[[100, 200, 300, 400], [10, 20, 30, 40]]
400
100
40
10
For your case, you can loop through your n arraylists to get the min and max of each of them.
If you want to find out the winner you should sum the marks obtained by each winner and compare it with a temp variable. if the sum is greater then the temp then assign the sum to the temp. the last value assigned in the temp will be highest mark obtained. After the first for loop the code will be like that.
String winnerName = "";
int temp = 0;
int counter = 0;
for(String name : names) {
numbers = holderOfMarksArayList.get(counter);
int sum = 0;
for( int number : numbers ) {
sum += number;
}
if( sum > temp ) {
temp = sum;
winnerName = name;
}
Collections.sort(numbers);
int maxScore = numbers.get(numbers.size() - 1);
int minScore = numbers.get(0);
System.out.println(name +", Max Score = " + maxScore + " Min Score = " + minScore +" Sum " + sum);
counter++;
}
System.out.println("Winner " + winnerName + " Total "+ temp);

Display number of values over a certain percentage Java

I need to write a Java program using a bi-dimensional array that stores marks achieved by 40 students in 8 subjects, finds the average and also finds the occurrences in which a distinction was obtained (a mark over 70%).
The program works fine except for the last requirement. Right now it's counting all marks if one or more are over 70% (therefore the result is always 8).
I guess I am confused on how to get a count of the marks above 70% only. Sample code is fine but please also try to explain what I am doing wrong...
Thank you! :)
import java.util.Scanner;
public class db {
public static void main(String[] args) {
//Variables
double mark = 0, average = 0, sum = 0, counter = 0, achievement = 0, percentage = 0, counterpercentage = 0;
double[][] marksTable = new double[40][8];
//New Scanner object
Scanner fromKeyboard = new Scanner(System.in);
for (int studentNo = 0; studentNo < 40; studentNo++) {
System.out.println("Enter marks for student no" + studentNo);
sum = 0;
counter = 0;
for (int moduleNo = 0; moduleNo < 8; moduleNo++) {
System.out.println("Mark for student " + studentNo + " for module no " + moduleNo + ":");
//Read value into variable mark
mark = fromKeyboard.nextDouble();
// Write mark into array
marksTable[studentNo][moduleNo] = mark;
//Calculations
sum = sum + mark;
counter = counter + 1;
}
percentage = mark;
average = sum / counter;
counterpercentage = counter;
//Display array
for (int moduleNo = 0; moduleNo < 8; moduleNo++) {
System.out.println("Average for student " + studentNo + " for module no " + moduleNo + " is: " + average);
break;
}
if (percentage >= 70) {
System.out.println(" The number of high marks achieved for this student are: " + counterpercentage);
}
if (percentage < 70) {
System.out.println("No high marks obtained");
}
}
}
}
Try this:
import java.util.Scanner;
public class db
{
public static void main (String []args)
{
//Variables
double mark=0, average=0, sum=0, counter=0, achievement=0, percentage=0, counterpercentage=0;
double[][] marksTable = new double[40][8];
//New Scanner object
Scanner fromKeyboard=new Scanner (System.in);
for (int studentNo = 0; studentNo < 40; studentNo++)
{
System.out.println("Enter marks for student no" +studentNo);
sum =0 ;
counter = 0;
for (int moduleNo = 0; moduleNo < 8; moduleNo++)
{
System.out.println("Mark for student "+studentNo+" for module no "+moduleNo+":");
//Read value into variable mark
mark = fromKeyboard.nextDouble();
// Write mark into array
marksTable[studentNo][moduleNo] = mark;
//Calculations
sum=sum+mark;
counter=counter+1;
if(mark >= 70) { //***Changed***//
counterpercentage++;
}
}
average=sum/counter;
//Display array
for (int moduleNo = 0; moduleNo < 8; moduleNo++)
{
System.out.println("Average for student "+studentNo+" for module no "+moduleNo+" is: "+average);
break;
}
if (counterpercentage >=0) //***Changed***//
{
System.out.println("The number of high marks achieved for this student are: "+ counterpercentage);
}
else
{
System.out.println("No high marks obtained");
}
}
}
}
It's because of this statement:
percentage = mark;
It assigns the value of mark to percentage, what we need to do here is to calculate the percentage, which would be total marks divided by max marks e.g.
percentage = (sum/(100.0 * marksTable[studentNo].length))*100; //(Assuming 100 as max marks for eah module)

How to divide doubles in an array in java?

I have in array with some doubles in them. I want to divide them, for example with an array that contains 6.0, 3.0 and 2,0 the result should be 1 (6/3/2). I wrote the following code:
System.out.print("How many numbers do you want to divide? ");
int division = input.nextInt();
double[] divisionArray = new double[division];
for(int i = 0; i < division; i++) {
System.out.print("Enter your " + (i + 1) + ". number: ");
divisionArray[i] = input.nextDouble();
}
for(int k = 0; k < division; k ++) {
double resultDivision = divisionArray[k] / divisionArray[k + 1];
}
System.out.println("Result: " + resultDivision);
but that doesn't seem to work. I get the error Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 I'm a complete java beginner. Could anyone help me out? Thanks
Your code has three issues.
resultDivision is defined within the scope of the for loop, so it's not visible afterwards, when you print the result.
With #1 fixed, you'll get an ArrayOutOfBounds exception because the second for loop tries to access divisionArray[k+1].
You don't check the arguments that the user gives you. What if a user specifies that it wants to divide -5 numbers? Your code will try to create an array with a length of -5, causing an Exception. Also, What if a user wants to divide by zero? Are you fine with that?
Here's a slightly better version:
Scanner input = new Scanner(System.in);
int division = 0;
do {
System.out.print("How many numbers do you want to divide? ");
division = input.nextInt();
} while (division <= 0);
double[] divisionArray = new double[division];
for (int i = 0; i < division; i++) {
System.out.print("Enter your " + (i + 1) + ". number: ");
divisionArray[i] = input.nextDouble();
if (divisionArray[i] == 0 && i>0) { // Remove this if you want to allow the user to divide by zero. Entering zero as the first argument is legal
System.out.println("Zero is an illegal argument, please enter a different number");
i--;
}
}
double resultDivision = divisionArray[0];
for (int k = 1; k < division; k++) {
resultDivision = resultDivision / divisionArray[k];
}
System.out.println("Result: " + resultDivision);
Good luck.
this should work:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many numbers do you want to divide? ");
int division = input.nextInt();
double[] divisionArray = new double[division];
for(int i = 0; i < division; i++) {
System.out.print("Enter your " + (i + 1) + ". number: ");
divisionArray[i] = input.nextDouble();
}
//remember the first value and divide it trough the second,
//third, fourth and so on...
double result = divisionArray[0];
for(int k = 1; k < division; k ++) {
result = result / divisionArray[k];
}
System.out.println("Result: " + result);
}

java array returned with incorrect values

I am a TA for a java class at my university and a student confronted me with a very odd problem today in lab. I looked over it for about an hour and had the other TA in lab do the same, yet we could not find a problem.
Effectively what we are doing here is creating 3 arrays, passing them into a new method. Modifying the value of those array in the new method and returning back to the original method. We are not using the return statement to return any of the arrays to the original method. Instead we are levering, what I can only describe being from a C background as pass-by-reference. However upon returning to the original method that values have changed to some incorrect values.
In this specific example we have three arrays called: "exams", "quizzes" and "labs." Each of these arrays are of size 1,000 and are initialized to -1. Inside the first method "calcGrade" we create these arrays and initialize them. Then we pass all three arrays to the second method which captures the amount of exams, quizzes and labs the user has and then stores the actual exam, quiz and lab grade values to the arrays.
METHOD 1 (calcGrade)
exams quizzes labs
-1 -1 -1
-1 -1 -1
-1 -1 -1
-1 -1 -1
. . .
. . .
. . .
METHOD 2 (getScores)
exams quizzes labs
90 80 90
-1 80 90
-1 -1 -1
-1 -1 -1
. . .
. . .
. . .
BACK to METHOD 1 (calcGrades)
exams quizzes labs
80 90 90
-1 -1 90
-1 -1 -1
-1 -1 -1
. . .
. . .
. . .
Can anyone think of any reason this could be happening? I am honestly stumped and I don't want him to lose credit for something that doesn't seem to be wrong...
Here is the code (please note that there are several println statements in there for debugging purposes):
import java.util.Scanner;
public class CSE1341Grade{
public static void main(String [] args){
Scanner input = new Scanner(System.in);
System.out.println("What is your first name? ");
String first = input.nextLine();
System.out.println("What is your last name? ");
String last = input.nextLine();
calcGrade(first, last);
}
public static void calcGrade(String first, String last){
int base = 1000;
int[] quizzes = new int [base];
int[] exams = new int [base];
int[] labs = new int [base];
for(int x = 0; x < base; x++)
{
quizzes[x] = -1;
exams[x] = -1;
labs[x] = -1;
}
int[] countarr = getScores(quizzes, exams, labs);
System.out.println("EXAMS:");
for(int x = 0; x < countarr[0]; x++)
System.out.println(exams[x]);
System.out.println("QUIZ:");
for(int x = 0; x < countarr[1]; x++)
System.out.println(quizzes[x]);
System.out.println("LABS:");
for(int x = 0; x < countarr[2]; x++)
System.out.println(labs[x]);
for(int x = 0; x < countarr.length; x++)
System.out.println(countarr[x]);
//System.out.println("----");
double examAvg =0.0;
for(int i=0;i<countarr[0];i++){ //adding together scores
examAvg+=exams[i];
//System.out.println(examAvg);
}
//System.out.println("----");
double quizAvg=0.0;
for(int i=0;i<countarr[1];i++){ //adding together scores
quizAvg+=quizzes[i];
//System.out.println(quizAvg);
}
//System.out.println("----");
double labAvg=0.0;
for(int i=0;i<countarr[2];i++){ //adding together scores
labAvg+=labs[i];
//System.out.println(labAvg);
}
examAvg = examAvg/countarr[0];
quizAvg = quizAvg/countarr[1];
labAvg = labAvg/countarr[2];
double totalAverage = (.5 * examAvg) + (.35 * quizAvg) + (.1 *labAvg) + 5.0;
System.out.println("Total Score: " +totalAverage);//display average
String grade = "";
if (totalAverage >= 90)
grade = "A";
else if (totalAverage >= 80)
grade ="B";
else if (totalAverage >= 70)
grade = "C";
else
grade = "F";
System.out.println(first + " " + last + " your grade is a: " + grade); //letter grade
}
public static int [] getScores(int [] exams, int [] quizzes, int [] labs){
Scanner input = new Scanner(System.in);
int [] countArray = new int[3]; //holding numbers of exams quizzes labs
System.out.println("How many exam grades do you have? ");
countArray[0] = input.nextInt();
System.out.println("How many quiz grades do you have? ");
countArray[1] = input.nextInt();
System.out.println("How many lab grades do you have?" );
countArray[2] = input.nextInt();
System.out.println(countArray[0] + ", " + countArray[1] + ", " + countArray[2]);
for(int counter = 0; counter < countArray[0]; counter++){ //every exam score
System.out.printf("Enter Exam" + " " + (counter + 1) + " " + "score: ");
exams[counter]=input.nextInt();
System.out.println(exams[counter]);
}
System.out.println("----");
for(int counter = 0; counter < countArray[1]; counter++){ //every quiz score
System.out.printf("Enter Quiz" + " " + (counter + 1) + " " + "score: ");
quizzes[counter]=input.nextInt();
System.out.println(quizzes[counter]);
}
System.out.println("----");
for(int counter = 0; counter < countArray[2]; counter++){ //every lab score
System.out.printf("Enter Lab" + " " + (counter + 1) + " " + "score: ");
labs[counter]=input.nextInt();
System.out.println(labs[counter]);
}
System.out.println("----");
System.out.println("EXAMS:");
for(int x = 0; x < countArray[0]; x++)
System.out.println(exams[x]);
System.out.println("QUIZ:");
for(int x = 0; x < countArray[1]; x++)
System.out.println(quizzes[x]);
System.out.println("LABS:");
for(int x = 0; x < countArray[2]; x++)
System.out.println(labs[x]);
System.out.println("************************");
return countArray; //return back to calc grade
}
}
You swapped the arguments in the call. Type checking can't save you here.
That is, when you call a function
public static int [] getScores(int [] exams, int [] quizzes, int [] labs) {...}
with
int[] countarr = getScores(quizzes, exams, labs);
you can't expect the results to make any sense!
There's a mismatch between the signature and what arguments you're calling it with.
int[] countarr = getScores(quizzes, exams, labs);
public static int [] getScores(int [] exams, int [] quizzes, int [] labs){
You've apparently mixed up the arguments

Categories

Resources