I want to find the largest number in an array then print them out, but I getting incorrect largest number output. Below is the output, as you can see the second and the third output for the largest number are incorrect.
Below is my code:
double x [][] = {{3.24,-0.96},
{-1.56,-0.61},
{-1.1,2.5},
{1.36,-4.8}};
String y [] = {"B","C","A","C"};
double w[][] = {{0,1.94,3.82},{0,-4.9,-4.03},{0,4.48,3.25}};
double threshold = 1;
int n = x.length;
int m = w.length;
double total [] = new double[3];
double max = 0;
double input = 0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
total[j] = (threshold * w[j][0]) + (x[i][0] * w[j][1]) + (x[i][1] * w[j][2]);
System.out.print(total[j] +", ");
input = total[j];
max = Math.max(input,max);
}
System.out.println();
System.out.println("Maximum is "+ max);
}
You never reset your max value, so it is still set as the max from the last calculation.
It will also fail when all values are below zero. You should initialise max to Integer.MIN_VALUE before each run.
You are continuing to keep the max value from j Loop for the subsequent i loop.
Reset the value of Max to min value before the start of subsequent i loop. Also edit the initial declaration from sero to min value.
Please refer below
double x [][] = {{3.24,-0.96},
{-1.56,-0.61},
{-1.1,2.5},
{1.36,-4.8}};
String y [] = {"B","C","A","C"};
double w[][] = {{0,1.94,3.82},{0,-4.9,-4.03},{0,4.48,3.25}};
double threshold = 1;
int n = x.length;
int m = w.length;
double total [] = new double[3];
double max = Integer.MIN_VALUE;
double input = 0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
total[j] = (threshold * w[j][0]) + (x[i][0] * w[j][1]) + (x[i][1] * w[j][2]);
System.out.print(total[j] +", ");
input = total[j];
max = Math.max(input,max);
}
System.out.println();
System.out.println("Maximum is "+ max);
max = Integer.MIN_VALUE;
}
Related
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
Hi so I'm new at java programming and i'm currently at learning array. So what i'm trying to do is find the maximum and minimum value of an array but for some reason i cant find the minimum value but i can find the maximum value.
Here is my output:
Enter the number of elements: 5
Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: 5
The maximum number is:5
The minimum number is: 0
I've used the same statement for getting the max value by only changing the operator. But somehow the output is always zero.
Here is my code:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int elements = input.nextInt();
int [] array = new int[elements];
int max = array[0];
int min = array[0];
for(int i = 0; i<elements; i++){
System.out.print("Enter a number: ");
array[i] = input.nextInt();
if(array[i]>max){
max = array[i];
}
if(array[i]<min){
min = array[i];
}
}
System.out.print("The maximum number is:" + max);
System.out.println();
System.out.print("The minimum number is: " + min);
}
}
Any help would be appreciated thanks!
int min = array[0];
This statement is executed at a time when array[0] is zero.
You have not read any values at this point, so initialize your min and max values with:
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
In fact, you don't need the array at all, since you don't use it after the loop. Just assign the scanner result to an int variable, declared inside the loop.
Assing highest value to min and lowest value to max
min = Integer.MAX_VALUE;
max = Integer.MIN_VALUE;
When you allocate memory using new operator,
int [] array = new int[elements];
each element of array is initialized to zero.
So when you do int min=array[0], min is assigned value 0. Then on comparing with 1,2,3,4 and 5 ,min is smallest and hence does not change.
To solve this,
First input all the elements in array using for loop , then initialize min and max to array[0]
Try this
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int elements = input.nextInt();
int [] array = new int[elements];
for(int i = 0; i<elements; i++){
System.out.print("Enter a number: ");
array[i] = input.nextInt();
}
int max = array[0];
int min = array[0];
for(int i = 0; i<elements; i++){
if(array[i]>max){
max = array[i];
}
if(array[i]<min){
min = array[i];
}
}
System.out.print("The maximum number is:" + max);
System.out.println();
System.out.print("The minimum number is: " + min);
}
}
The default initial value of an Integer is 0.
for this reason when checking if it is bigger than the input value the default value stays the same
Why do you need an array for this in the first place?
Scanner console = new Scanner(System.in);
int entries = console.nextInt();
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for(int i = 0; i < entries; i++){
int temp = console.nextInt();
if(temp < min) {
min = temp;
}
if (temp > max) {
max = temp;
}
}
I've written a Java program which reads a series of real numbers from a text file into an array. I would like to use -1.0 as a sentinel so that scanner stops reading from the file when it reaches -1.0.
I'm struggling to insert the sentinel in the correct position, and also unsure if this should be done with an if or while statement. Any help much appreciated:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class CalculatingWeights {
public static void main(String[] args) throws FileNotFoundException {
//Create file and scanner objects
File inputFile = new File("in.txt");
Scanner in = new Scanner(inputFile);
//declare variables
double [] myArray = new double [100];
int i = 0;
double min = myArray[0];
double max = myArray[0];
//Read numbers from file, add to array and determine min/max values
while(in.hasNextDouble()) {
myArray[i] = in.nextDouble();
if(myArray[i] < min) {
min = myArray[i];
}
if(myArray[i] > max) {
max = myArray[i];
}
i++;
}
//Calculate and print weighting
for(int index = 0; index < myArray.length; index++) {
double num = myArray[index];
double weighting = (num - min) / (max - min);
System.out.printf("%8.4f %4.2f\n", num, weighting);
}
}
}
without changing a lot of your code use this
double [] myArray = new double [100];
int count = 0;
double min = myArray[0];
double max = myArray[0];
//Read numbers from file, add to array and determine min/max values
while(in.hasNextDouble()) {
myArray[count] = in.nextDouble();
//sentinel
if(myArray[count]==-1.0)
break;
if(myArray[count] < min) {
min = myArray[count];
}
if(myArray[count] > max) {
max = myArray[count];
}
count++;
}
//Calculate and print weighting
for(int index = 0; index < count; index++) {//<-----NOTE HERE: as the array is filled upto "count"
double num = myArray[index];
double weighting = (num - min) / (max - min);
System.out.printf("%8.4f %4.2f\n", num, weighting);
}
I have a 2D array and I want to find the largest average set of results, so far I can calculate the average of each set of results but I'm not sure how to select the biggest from the output.
My code:
static int[][] studentMarksArray = new int[10][3];
for(int i=0;i<10;i++){
double total = (studentMarksArray[i][0]*studentMarksArray[i][1]*studentMarksArray[i][2])/3;
System.out.println(total);
}
An attempted solution:
for(int i=0;i<10;i++){
double total = (studentMarksArray[i][0]*studentMarksArray[i][1]*studentMarksArray[i][2])/3;
double newTotal = total;
if(newTotal>total){
newTotal = total;
System.out.println(newTotal);
}
}
Like this:
double max = 0;
for(int i = 0; i < 10; i++){
double total = (studentMarksArray[i][0]*studentMarksArray[i][1]*studentMarksArray[i][2])/3;
max = Math.max(max, total);
}
or if you want the index:
int index = -1;
double max = 0;
for(int i = 0; i < 10; i++){
double total = (studentMarksArray[i][0]*studentMarksArray[i][1]*studentMarksArray[i][2])/3;
if(Math.max(max, total) == total) {
index = i;
max = total;
}
}
Ok if you want to have an array of averages at the end, do this:
int index = -1;
double max = 0;
double [] averages = new double[10];
for(int i = 0; i < 10; i++){
double total = (studentMarksArray[i][0]*studentMarksArray[i][1]*studentMarksArray[i][2])/3;
averages[i] = total;
if(Math.max(max, total) == total) {
index = i;
max = total;
}
}
add this after variable initialisation
int largest=0,lp=0;
add this before forloop ends but after calculating total
if(largest<total){
largest=total;lp=i;
}
at the end of forloop you will have largest average in the variable largest and its position in variable i.
You can save the outPut at every step in to a priority queue(which saves the elements in natural ordering) and in the last step the pull() the highest value from this priority queue.
import java.util.PriorityQueue;
public class Test1 {
public static void main(String[] arg){
int[][] studentMarksArray = new int[10][3];
PriorityQueue<Double> pq = new PriorityQueue<Double>();
for(int i=0;i<10;i++){
double total = (studentMarksArray[i][0]*studentMarksArray[i][1]*studentMarksArray[i][2])/3;
System.out.println(total);
pq.add(total);
}
System.out.println(pq.poll());;
}
}
I'm relatively new to the world of OOP, and for some reason, the console of IntelliJ and Eclipse doesn't give me an output in the console for the following program. I'm trying to store 12 numbers into an array using scanner and to find the standard deviation, mean, lowest number, and highest number. Can anyone spot what's wrong?
import java.util.Arrays;
import java.util.Scanner;
public class untitled
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int[] grades = new int[12];
int size = grades.length;
for (int i = 0; i < size; i++)
{
grades[i] = in.nextInt();
}
Arrays.sort(grades);
int low = grades[0];
int high = grades[11];
int sum = 0;
for (int i: grades)
{
sum += i;
}
int m = sum / size;
double var = 0;
double variance;
double sd;
for (int i = 0; i < size; i++)
{
var = var + ((grades[i] - m) * (grades[i] - m));
}
variance = (int) var / size;
sd = Math.pow(variance,.5);
String lowest = ("Lowest Grade:" + low);
String highest = ("Highest Grade:" + high);
String average = ("Average Grade:" + m);
String standdev = ("Standard Dev.:" + sd);
System.out.println(lowest);
System.out.println(highest);
System.out.println(average);
System.out.println(standdev);
}
}
Thanks.
What you have done is to accept 12 inputs.. try entering 12 inputs in console and then your output will appear..
And yeah this doesnt seem to use OOP concepts. Please refer this link for more info regarding OOPS :
http://en.wikipedia.org/wiki/Object-oriented_programming
The problem is, that you need to enter values first, before the calculation and output can continue. Without having some printed text on the console (like "Enter a new number: ") the console will just stay empty.
You could either enter 12 numbers, or fill the list automatically with Random values. In this case the output will immediately be visible on the console.
...
nt[] grades = new int[12];
int size = grades.length;
Random random = new Random();
for (int i = 0; i < size; i++) {
grades[i] = random.nextInt(15); // value between 0 and 14
}
Arrays.sort(grades);
int low = grades[0];
...