Display Min/Max array - java

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

Related

How do I make a calculator that multiplies more than two numbers?

I made a calculator that does multiple things (adding consecutive numbers, adding multiple numbers, etc) but I am having trouble making it so that the calculator can multiply multiple numbers. So far, I've basically copied the code that adds multiple numbers, but I can't figure out how to make it multiply instead of add.
Here is my code:
import java.util.Scanner;
public class SumOfNumbers {
public static void main(String arg[])
{
int n;
int sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("Please enter how many numbers you want to add up to: ");
n = s.nextInt();
System.out.println("you entered: " + n + "");
sum = addConsecutiveNumbers(n);
System.out.println("sum of 1 to "+n+" = "+sum);
//following code is sum of any numbers you entered from console
//store the numbers into an array
int num;
int sumOfNums=0;
System.out.print("Please enter how many numbers you want to sum: ");
num=s.nextInt();
System.out.println("you want to sum "+num+" numbers ");
sumOfNums = addNumbers(num);
System.out.println("sum of "+num+" numbers = "+sumOfNums);
}
//Define a method which add consecutive numbers based on user's input and return the sum of the numbers
private static int addConsecutiveNumbers (int number)
{
int sum = 0;
for (int i = 1; i <= number; i++)
{
sum = sum + i;
}
return sum;
}
//Define a method which add numbers based on user's input and return the sum of the numbers
private static int addNumbers (int num)
{
Scanner s = new Scanner(System.in);
int a[] = new int[num];
int sumOfNums = 0;
for(int k = 0; k < num; k++)
{
System.out.println("enter number "+(k+1)+":");
a[k] = s.nextInt();
System.out.println("The array of a[" + k + "] = " + a[k]);
}
for(int j = 1;j < num ; j++)
{
sumOfNums += a[j];
}
return sumOfNums;
}
//below is the part of code that I am having trouble with.
public static int multiplyNumbers(int num)
{
int Area = 0;
Scanner s = new Scanner(System.in);
int a[] = new int[num];
System.out.println("Please enter how many numbers you want to multiply:");
num=s.nextInt();
for(int l = 0; l < num; l++)
{
System.out.println("enter number "+(l+1)+":");
a[l] = s.nextInt();
System.out.println("The array of a[" + l + "] = " + a[l]);
}
return Area;
}
}
I see one thing right away; The way I see your code, the following two lines a redundant:
System.out.println("Please enter how many numbers you want to multiply:");
num=s.nextInt();
You should have already asked the user how many numbers they want to multiply, because it's passed in as a parameter. As for your actual problem, take a look at these lines from the addNumbers() method:
for(int j = 1;j < num ; j++)
{
sumOfNums += a[j];
}
All you gotta do is copy that code in right before your return statement (return Area;). You'll need to tweak it a bit so instead of using the sumOfNums variable, it uses the Area variable, and instead of adding, it multiplies. This can be done like so:
for(int j = 0;j < num ; j++) //j also needs to start at 0, I think you may have made a mistake when writing the summing method
{
Area *= a[j];
}
You'll notice there's an issue with this algorithm though (almost didn't catch it myself). Area starts off with a value of 0, so 0 multiplied by any number will always still be 0. Simple fix; just manually set Area to the first value before the loop. Something like this:
Area = a[0];
for(int j = 1; j < num; j++)
{
sumOfNums += a[j];
}
Also notice I started the for loop at j = 1 this time. This is because I already started Area as a[0], so we don't want to multiply that number twice.
You don't need to store values in an array for multiplication similarly for addition you can directly update the final result
public static int multiplyNumbers(int num) {
int Area = 1;
Scanner s = new Scanner(System.in);
System.out.println("Please enter how many numbers you want to multiply:");
num = s.nextInt();
for (int l = 0; l < num; l++) {
System.out.println("enter number " + (l + 1) + ":");
int temp = s.nextInt();
Area *= temp;
System.out.println("The array of a[" + l + "] = " + temp);
}
return Area;
}

How do I get a specific component of an array that doesn't have set length?

What I'm trying to do is get a set of numbers from the user, the console will print out the second highest number in english and the second lowest number in spanish.
First I'm trying to get the input from user, put it in an array and grab the second highest and second lowest value of the components. But I can't figure out how to grab ones I need.
public static void main(String[] args) {
//get the length from user
int length;
Scanner input = new Scanner(System.in);
System.out.println("How many variables are you going to enter?: ");
length = input.nextInt();
//allocate array for that length
int[] variables = new int[length];
for(int counter = 0; counter < length; counter++) {
System.out.println("Enter variable: ");
variables[counter] = input.nextInt();
}
input.close();
//print the variables
System.out.println("Your variables are");
for(int counter = 0; counter < length; counter++) {
System.out.println(variables[counter]);
}
}
System.out.println("------------------");
Arrays.sort(variables); //sort array
System.out.println(variables[1]); //2nd lowest value
System.out.println(variables[variables.length-2]); //2nd highest value
try this brother
add this to your code
class Demo
{
public static void findNum(int arr[]){
int largest = arr[0], second_largest = arr[0];
int minimum = are[0], second_minimum = are[0];
for(int i=0;i<arr.length;i++){
if(arr[i] >= largest){
second_largest = largest;
largest = arr[i];
}
else if(arr[i]>second_largest){
second_largest = arr[i];
}
if(arr[i] <= minimum){
second_minimum = minimum;
minimum = arr[i];
}
else if(arr[i]<second_minimum){
second_minimum = arr[i];
}
}
System.out.println("Second Largest = " + second_largest + " Second_minimum = "+second_minimum);
}
public static void main (String[] args) throws java.lang.Exception
{
int arr[] = {5,3,2,1,8,77};
findNum(arr);
}
}
You can do something like this if you're particular about not sorting your original array.

Array that takes user input to fill but does not allow duplicate elements

I'm trying to write a part of a program that I have for an assignment. This part of the program should take 8 user inputed integers to fill however if the user inputs a digit that has already been inputed an error is displayed and the user is asked to input a different number. As of yet I haven't written the error code and second attempt part of the code because I am having issues with the checking for duplicates part. At present the out put is True no matter what I put in.
int maxNum = 8;
int[] arrayIn = new int[maxNum];
boolean duplicates = false;
// Run while not true
while (!duplicates) {
// For loop for input into array
for (int j = 0; j < maxNum; j++) {
System.out.println("Enter digit " + digCounter + ":");
arrayIn[j] = in1.nextInt();
digCounter++;
// Check for duplicates
for (int a = 0; a < maxNum; a++) {
for (int k = a + 1; k < maxNum; k++) {
if (k != a && arrayIn[k] == arrayIn[a]) {
// Quit loop if duplicate found
duplicates = true;
}
}
}
}
System.out.println(duplicates);
}
You should look into a collection called Set. There is a pretty handy function Set.contains that will return true or false depending if a number is already in the Set or not. Something like this would do the trick:
Scanner scanner = new Scanner(System.in);
int maxNum = 8;
Set<Integer> numbers = new HashSet<>();
int digCounter = 1;
//Run while we need numbers
while (digCounter <= maxNum) {
System.out.println("Enter digit " + digCounter + ":");
int tempNumber = scanner.nextInt();
if (numbers.contains(tempNumber)) { //If number is already chosen
System.out.println("Sorry that number has already been added");
} else { //If new number
digCounter++;
numbers.add(tempNumber);
}
}
System.out.println(numbers);
Or if you HAVE to use only arrays you can do something like this:
Scanner scanner = new Scanner(System.in);
int maxNum = 8;
int[] arrayIn = new int[maxNum];
boolean duplicate;
int digCounter = 1;
// Run while we need numbers
while (digCounter <= maxNum) {
//reset duplicate
duplicate = false;
//Get user input
System.out.println("Enter digit " + digCounter + ":");
int temp = scanner.nextInt();
for (int i = 0; i <= digCounter - 2; i++) { //Loop through accepted numbers
if (temp == arrayIn[i]) { //We have found a match
duplicate = true;
break;
}
}
//Check if duplicate
if (duplicate) {
System.out.println("Sorry that number has already been added");
} else {
arrayIn[digCounter - 1] = temp;
digCounter++;
}
}
System.out.println(Arrays.toString(arrayIn));
Hope this helps!
This code will also work if you don't want to use set.
// creating the array
int[] array = new int[10];
// Taking the first number
System.out.println("Please enter your numbers: ");
array[0] = input.nextInt();
// taking other inputs
int count;
for (count = 1; count < array.length; count++) {
int num = input.nextInt();
// Scanning the array for the number
int n;
for (n = 0; n < count; n++) {
while (array[n] == num) { // This will also work if the user
// wants to give duplicate after
// duplicate
System.out.println("You have entered this number before! Add another..");
num = input.nextInt();
n = 0;
}
}
array[count] = num;
}

Displaying odd values in an array

I am trying to display the odd numbers in an array, but only once per number (i.e. numbers[3] = 3,3,1; would only display 3 and 1 instead of 3, 3 and 1.)
this is the code that I have as of now, the program completely will create an with the specific length entered by the user and then will calculate the max min, and odd values in the array.
import java.util.Scanner;
public class ArrayLab
{
static Scanner input = new Scanner (System.in);
public static void main(String[] args)
{
System.out.println("Enter the number of numbers: ");
final int NUMBER_OF_ELEMENTS = input.nextInt();
double[] numbers = new double[NUMBER_OF_ELEMENTS];
System.out.println("Enter the numbers: ");
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
numbers[i] = input.nextDouble();
}
input.close();
double max = numbers[0];
double min = numbers[0];
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
if (numbers[i] > max)
{
max = numbers[i];
}
}
System.out.println("The max is: " + max);
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
if (numbers[i] < min)
{
min = numbers[i];
}
}
System.out.println("The min is: " + min);
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
if (numbers[i] % 2 != 0)
{
System.out.println ("The odd numbers are: " + numbers[i]);
}
}
}
}
thanks for any help.
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
if (numbers[i] % 2 != 0)
{
set.add(numbers[i]);
}
}
System.out.println ("The odd numbers are: " +set);
This can be done a lot simpler using Java8:
double[] d = Arrays.toStream(numbers).filter(d -> (d % 2) == 1).distinct().toArray();
for(double tmp : d)
System.out.println(tmp);
System.out.println("min: " + Arrays.toStream(numbers).min((a , b) -> new Double(a).compareTo(b)));
System.out.println("max: " + Arrays.toStream(numbers).max((a , b) -> (new Double(a).compareTo(b))));
For you're solution: you never eliminate repeating numbers, thus the duplicates remain in the array until you print all odd numbers and the maximum-number.
This elimination can be done in several ways:
Using Java8 as above
add all values to a Set, since these don't allow duplicate values
eliminate them in your own way (i won't provide any code for this since it's rather complicated to design an efficient solution for this)
Updated solution for what you need. And Please use a better coding standard. Do note the condition check !oddNumbers.contains(numbers[i]) is not very necessary as HashSet never takes any duplicate values.
import java.util.HashSet;
import java.util.Scanner;
public class ArrayLab {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter the number of numbers: ");
final int NUMBER_OF_ELEMENTS = input.nextInt();
double[] numbers = new double[NUMBER_OF_ELEMENTS];
System.out.println("Enter the numbers: ");
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
numbers[i] = input.nextDouble();
}
input.close();
HashSet<Double> oddNumbers = new HashSet<Double>(NUMBER_OF_ELEMENTS);
double max = numbers[0];
double min = numbers[0];
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
if (numbers[i] < min) {
min = numbers[i];
}
if (numbers[i] % 2 != 0 && !oddNumbers.contains(numbers[i])) {
oddNumbers.add(numbers[i]);
}
}
System.out.println("The max is: " + max);
System.out.println("The min is: " + min);
System.out.println("The odd numbers are: " + oddNumbers);
}
}
A more meaningful solution to your approach would be as follows:
int[] tempArray; //temporary array to store values from your original "array"
int count=0;
for(int i=0; i<numbers.length; i++) {
if(numbers[i]%2 != 0) {
count++;
}
}
tempArray = new int[count]; //initializing array of size equals to number of odd digits in your array
int j = 0;
for(int i=0; i<numbers.length; i++) {
boolean check = true;
for(int k=0; k<j; k++) {
if(tempArray[k] == numbers[i]) {
check = false; //this will prevent duplication of odd numbers
}
}
if(numbers[i]%2 != 0 && check) {
tempArray[j]=numbers[i];
j++;
}
}
//Now print the tempArray which contains all the odd numbers without repetition
A few people have mentioned sets, but there is a different way as well. Simply sort the array, then scan through it, checking each number against the last one printed. i.e.,
int lastPrinted = 0;
// Sort the array
Arrays.sort(numbers);
System.out.print("The odd numbers are: ");
// Scan through the array
for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
{
// if it's odd and doesn't match the last one...
if (numbers[i] % 2 != 0 && numbers[i] != lastPrinted)
{
// ...print it and update lastPrinted
System.out.print( "" + numbers[i] );
lastPrinted = numbers[i];
}
}
System.out.println("");
As a side note, you really don't have to scan through the array twice to find your max and min, you can do that in one go.
I think you can use inbuilt hashmap class and its method to achieve the task without affecting the complexity of algorithm to any great extent .
import java.util.HashMap;
public class Hashing {
public static void main(String[] args) {
//declare a new hasmap
HashMap<Integer, Integer> map = new HashMap<>();
//consider Arr as your Array
int Arr[] = {3,3,1,4,5,5,7,8};
//traverse through the array
for(int i=0;i<Arr.length;i++){
//check if the required condition is true
if(Arr[i]%2==1){
/*now we insert the elements in the map but before
that we have to make sure that we don't insert duplicate values*/
if(!map.containsKey(Arr[i])){// this would not affect the complexity of Algorithm since we are using hashMap
map.put(Arr[i], Arr[i]);//We are storing the Element as KEY and as VALUE in the map
}
}
}
//now We can get these element back from map by using the following statement
Integer[] newArray = map.values().toArray(new Integer[0]);
//All the required elements are now present in newArray
for(int ele:newArray){
System.out.println(ele);
}
}
}

How to display newly sorted integers?

I am doing a project in which the user enters a number, x ,it will then generate x amount of random numbers and add them to an arraylist. In one text field, it will display however many random integers are in the array, I then have to make it so in another textfield, it sorts those numbers through a selection sorting. I'm pretty sure I have the code for it right, I'm just not sure how to get the sorted numbers to display on the text field #2. Heres what I have:
ArrayList <Integer> Numbers = new ArrayList <Integer>();
....
String input;
int int1,int2 = 0, min = -1000, max = 1000,j, maximum;
input = Input.getText();
int1 = Integer.parseInt(input);
Random number = new Random();
while(int2 < int1){
for (int i = 0; i < int1; i++){
int randomInt = number.nextInt(max - min + 1) + min;
Numbers.add(randomInt);
int1--;
}
}
if(Selection.isSelected() && Ascending.isSelected()){
for (int i = 0; i<Numbers.size()-1; i++){
maximum = i;
for(j = i+1; j<=Numbers.size()-1;j++){
if(j < i){
int temp = i;
i = j;
j = temp;
}
}
}
}
Output1.setText("Unsorted Numbers " + Numbers);
Output2.setText("Sorted Numbers " + //what here? );
Numbers.clear();
Thanks for any help you might be able to offer.
what about this ?
public static void main(String[] args) {
//min and max value
int min = -1000;
int max = 1000;
//collection to store numbers
ArrayList<Integer> numbers = new ArrayList<Integer>();
Random random = new Random();
//receive input
Scanner myScanner = new Scanner(System.in);
int numberFromUser = Integer.parseInt(myScanner.nextLine());
for (int i = 0; i < numberFromUser; i++) {
numbers.add(random.nextInt(max - min + 1) + min);
}
System.out.println("Unsorted :" + numbers);
// sort the numbers
Collections.sort(numbers);
System.out.println("Sorted :" + numbers);
numbers.clear();
}
You should prepare a string:
String sortedNumbersOutput = "";
for (int i = 0; i < sortedNumbers.size(); i++) {
sortedNumbersOutput += sortedNumbers.get(i) + (i != sortedNumbers.size() - 1 ? "," : "");
}
Output2.setText("Sorted Numbers " + sortedNumbersOutput );
On a separate note, I don't believe you are sorting your list...
You are comparing on the indices and not the values at those indices.
Maybe you want to try:
boolean changes = true;
int temp;
while (changes) {
changes = false;
for (int i = 0; i < Numbers.size()-1; i++){
if (Numbers.get(i) > Numbers.get(i+1)) {
temp = Numbers.get(i);
Numbers.set(i, Numbers.get(i+1));
Numbers.set(i+1, temp);
changes = true;
}
}
}
which is called a bubble sort

Categories

Resources