Finding the minimum and maximum values in a user inputed array (Java) - java

So I've been tasked with creating a code that creates a predetermined array list for users to input up to over 100 integers with the option of using 0 to signify once their done with their inputs. However, when trying to call for say the minimum value, it just returns a value of 0. How would I properly format it so it compares it to all the value in the user inputted array list? Appreciate any help I can get! I added comments on the side to show which areas I have questions about or where I believe that the error lies.
public static void main(String[] args) {
Scanner TextIO = new Scanner(System.in);
String calc;
double[] numbers2; //An array for storing double values.
int[] numbers; // An array for storing the int values.
int count; // The number of numbers saved in the array.
int num; // One of the numbers input by the user.
int max;
int min;
/* Initialize the summation and counting variables. */
numbers2 = new double[100]; // Space for 100 doubles.
numbers = new int[100]; // Space for 100 ints.
count = 0; // No numbers have been saved
max = Integer.MIN_VALUE; //Properly initialized?
min = Integer.MAX_VALUE; //Properly initialized?
/*Start of min method. */
if (calc.equals("min")){
System.out.println("Enter up to 100 positive integers;
while (true) { // Get the numbers and put them in the array.
System.out.print("-> ");
num = TextIO.nextInt();
if (num <= 0) {
break; } /*Zero marks the end of the input. All
have been inputted. */
else {
numbers[count] = num; // Put num in position count.
count++;
}
for (int i=0; i<numbers.length;i++) { //"For" statement needed here?
if (numbers[i] < min) {
min = numbers[i];}
}
}
System.out.println("Your minimum is : " + min);
}
}
}

Your for loop that finds the minimum should be after the while loop that reads the input, not inside it (since currently it goes over un-initialized elements of the array, so it always finds a 0 as the minimum). If you do that, you should also change the for loop to only iterate over the elements you assigned to the array (indices 0 to count-1), and not the entire array.
Alternately, you can remove the for loop and just put the
if (numbers[count-1] < min) {
min = numbers[count-1];
}
condition inside the while loop.
This will find the minimum in the same loop that reads the input.
Of course, if you do that, you don't need to store the elements in an array at all, so you can further simplify the code.
Here's a possible solution the keeps the array and the for loop :
while (count < numbers.length) { // avoid too many inputs
System.out.print("-> ");
num = TextIO.nextInt();
if (num <= 0) {
break;
} else {
numbers[count] = num;
count++;
}
}
for (int i=0; i<count;i++) {
if (numbers[i] < min) {
min = numbers[i];
}
}

Related

How to use Ctrl+Z to stop asking for input?

I am writing a program that takes integers from the user and stores them in an array, then calculates the arrays average.
The array can hold at maximum 100 integers. If the user wants to do less than 100, they hit CTRL+Z (or Command+D) to stop prompting for numbers.
Here is my main method:
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int [] array = new int[100];
System.out.printf("Enter a stream of numbers: ");
readIntoArray(input, array);
for (int i = 0; i<=array.length;i++) {
array[i] = input.nextInt();
}
}
And here is the method that reads into the array.
public static int readIntoArray(Scanner input, int[] nums) {
int count = 0; //number of elements entered into the array
while (count <= nums.length && input.hasNextInt()) {
nums[count]=input.nextInt();
count++;
}
return count;
}
And here is the average method.
public static void printAboveAverage(int[] nums, int size) {
double average;
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum =+ nums[i];
}
average = sum/size;
System.out.print(average);
What am I doing wrong?
I keep getting a NoSuchElementException immediately after hitting CTRL+Z.
Here:
while (count <= nums.length && input.hasNextInt()) {
This loop will probably stop when you hit ctrl-z and there is no more int. But next statement is:
array[i] = input.nextInt();
In other words: your read method seems to correctly check if enough numbers are in, or if the scanner stopped having input.
But your main method ignores that, and just asks for another number from the scanner.
So it could be as simple as: just drop that for loop within your main method that wants more numbers.
I suggest you have a try and catch if it gives you an Exception, maybe use it to get unlimited numbers (dont use the max 100 numbers) and when he finds the exception he counts the average?
Not the best solution, excpetion are not meant to always be used, Thanks to domsson for the reminder
something like:
try{
//Get the numbers
}
catch(Exception e){
//Calculate the average
}
Just thinking out loud, it may help you.

How do you count the amount of numbers when the input is given separated by spaces, ended with a letter?

I'm quite new to java.
I'm trying out some things for a project but I don't get why this does not work.
The goal here is to let the user input numbers separated by spaces and end with a letter. The program then needs to count the even and odd indexed numbers and output which sum is larger.
I already made this successfully when the amount of numbers given was a constant, but now I want to make it adapt to the user input.
Because I want to put the numbers in an array I need to know the length of this array. To get this I want to count the amount of numbers the user puts in so I can create the appropriate length array.
For some reason the while loop does not end and keeps running. How do I count the amount of numbers put in?
EDIT
I've added in.next(); in the first while loop so it is not stuck at the first input element. This brings me to a further problem however of having two while loops trying to loop through the same input. I have tried to create a second scanner and resetting the first one, but it does not get the second loop to start at the first element. Previous answers show that this is not possible, is there a way to put this in one while loop while still using arrays to store the values?
P.S. The input values should be able to be any positive or negative integer.
Here is my complete code:
import java.util.Scanner;
public class LargerArraySum {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int length = 0;
System.out.println("Enter your numbers seperated by spaces, end with a letter");
while(in.hasNextInt()) {
length++;
in.next();
}
System.out.println(length);
int arra[] = new int[length];
while(in.hasNextInt()) {
for(int i=0;i<length;i++) {
int x = in.nextInt();
arra[i] = x;
}
}
int evenSum = EvenArraySum(arra);
int oddSum = OddArraySum(arra);
if(evenSum<oddSum) {
System.out.println("The sum of the odd indexed elements is bigger");
} else if(oddSum<evenSum) {
System.out.println("The sum of the even indexed elements is bigger");
} else {
System.out.println("The sum of the odd and even indexed elements is equal");
}
}
public static int EvenArraySum(int[] a) {
int sum = 0;
for(int i=1;i<a.length;i+=2) {
sum += a[i];
}
System.out.println("The sum of the even indexed elements is: " + sum);
return sum;
}
public static int OddArraySum(int[] a) {
int sum = 0;
for(int i=0;i<a.length;i+=2) {
sum += a[i];
}
System.out.println("The sum of the odd indexed elements is: " + sum);
return sum;
}
}
add in.next(); in the loop. Actually you don't need array. You can sum even and odd indexed numbers while reading without saving them.
1) Your first while-loop does not work because the iterator is always checking for further numbers in from the same position.
Example:
Position 0 1 2 3 4 5
Value 1 3 5 7 9 0
At start the iterator points to position 0. If you call hasNextInt() it will check if position 1 is available, in this case it will be true. At this moment the interator still points to position 0. So you increase your length and do the same thing again, so you have an infinite loop.
To move the iterator to the next position you need to call nextInt().
2) You can't iterate over the same Scanner with a second while-loop in that way. If you would correct you first while-loop the iterator would point to position 5 (it reached the end of the scanner). So the check for hasNextInt() will be false and the second while-loop will not be entered.
3) The comments already mentioned it, you could use an ArrayList for this use case like so:
final ArrayList<Integer> input = new ArrayList<>();
while ( in.hasNextInt() ) {
input.add( in.nextInt() );
}
System.out.println( input.size() );
( or like kitxuli mentioned in his answer, dont even store the values, just count them in the first while-loop)
Your code has 2 major problems . The first and the second while loops lets take a look at your first loop .
while(in.hasNextInt()) {
length++;
}
your condition in.hasNextInt() made you insert input because no variable was initialized with in.nextInt but also returns either [true] or [false] so as long as its true it will add to the length variable without prompting you to insert a [new input] .so the code should look like.
Int length = 0;
int k ;
while(in.hasNextInt()) {
length++ ;
k = in.nextInt();
}
you insert the input into an initialized variable k for ex then prompt the user to further input into k after adding to [length] then the loop will check your condition without prompting user for input.
Lets look at your second while loop.
while(in.hasNextInt()) {
for(int i=0;i<length;i++) {
int x = in.nextInt();
arra[i] = x;
}
}
In in.NextInt() you are prompting the user to enter new input once again so you don't need int x.Not even the while loop .However you MUST declare a new scanner in this ex: I call it c .The code should look like this.
int [] a = new int [length];
Scanner c = new Scanner (System.in);
for(int i=0;i<length;i++) {
if (c.hasNextInt()){
a[i] = c.nextInt();
} else
break;
}
You must add the if statement because if you get an alphabet in the int array you will get an exception error .The array a[i] will not prompt the user.
Of course it isn't practical to make the user enter the values twice so a better code to implement without using ArrayList class which I think you may not know very well is by using an empty String .
NEW CODE :-
String g = "";
String j ="";
int y ;
int q=0;
int w = 0;
while (in.hasNextInt())
{
y = in.nextInt();
g =g+y+",";
q++;
}
int arra [] = new int [q];
for(int r =0;r<g.length();r++) {
if(g.charAt(r)==(',')){
arra[w]=Integer.parseInt(j);
System.out.println(arra[w]);
w++;
j="";
}else{
j=j+g.charAt(r);
}
}
Another even better code :-You just insert your numbers separated by spaces without a letter ,hit enter and the array is filled.
Scanner in = new Scanner (System.in);
String g = "";
String j ="";
int y ;
int q=0;
int i=0;
int w = 0;
System.out.println("inset your input separated by spaces");
g = in.nextLine();
while(i<g.length()){
if((g.charAt(i))==(' ')){
q++;
}
i++;
}
int a [] = new int [q+1];
for(int r =0;r<g.length();r++) {
if(g.charAt(r)==(' ')){
a[w]=Integer.parseInt(j);
System.out.println(a[w]);
w++;
j="";
}else{
j=j+g.charAt(r);
}
}
a[w]=Integer.parseInt(j);
System.out.println(a[w]);

How can I change the values exceeding the int data type to the long data type in this code?

In the last portion of this code (where the last for loop and if statements are), I'm trying to change the data type of the integers to long when they exceed the integer data type limit. What am I doing wrong in this code? When I run, I get the same values as before I even tried to change them to long (which are increasingly huge integers until they get negative).
public class UniqueElements {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int maxValue = 0;
int numElements = 0;
int programRuns = 12;
Scanner sc = new Scanner(System.in);
for (int newExecution = 0; newExecution <= programRuns; newExecution++ ) {
System.out.print("Enter the maximum value for an element: ");
//prompt user to enter the maximum value
maxValue = sc.nextInt(); //user input for max value
System.out.print("Enter the number of elements in the array: ");
numElements = sc.nextInt(); //number of elements in an array
int A[] = new int[numElements];
//array comprising of the number of elements chosen by the user
int totalComp = 0; //set total comparisons to 0
for (int runs = 1; runs <= 100; runs++) { //program runs 100 times
Random rand = new Random(System.nanoTime());
//initiate the random number generator
int numComp = 0; //set number of comparisons to 0
for (int index = 0; index < numElements; index++) {
A[index] = rand.nextInt(maxValue);
//length of array is the number of elements the user puts in
}
for (int i = 0; i < A.length; i++) { //for each integer in the array
for (int j = i + 1; j < A.length; j++) {
//for each integer following i
if (A[i] == A[j]) { //if the are equal to eachother
//end the if statement
break;
}
if (numComp == (int)numComp) {
numComp++;
}
else {
Long.valueOf(numComp);
numComp++;
}
}
}
totalComp+= numComp;
} //end 100 loops
if (totalComp == (int)totalComp)
System.out.println("Average number of comparisons: " + totalComp / 100);
else {
System.out.println("Average number of comparisons: " +
Long.valueOf(totalComp) / 100L);
}
}
}
}
update:
somehow.... changing the total number of runs to 2 and dividing the totalComp variable by 2 and 2L made it work. Anyone know how that changed it?
You can't change the type of a variable after it's already been declared. You can cast that variable to another type, or "interpret" it as another type (as in your Long.valueOf()), but the variable still remains whatever type you declared it as.
In your code, you've declared totalComp to be an int, which in Java means it holds 32 bits (one of which is a sign bit). There's no way to make Java store more than 32 bits in an int. If you continue to add beyond Integer.MAX_VALUE, or subtract below Integer.MIN_VALUE, the value in the variable will simply under/overflow. So this statement after your for loop isn't doing what you expect, and will always be true: if (totalComp == (int)totalComp)
In other words, you can't go "back in time" and re-declare your primitive int as a long because you found out at runtime that you need to store larger values. The easiest way to solve this problem would be to declare totalComp as a long. If for some reason you can't change the type of totalComp, it is possible to detect overflow/underflow before performing the calculation; see this answer for details.

Sorting even numbers from original array

I have to create a program that reads an arbitrary number of positive integers from the user and store them into an array. The number of input data is not more than 100. After the user finishes the program should remove all even integers and place them in another array leaving all odd integers in the original array with no holes. It should display the contents in the original array as the order of input, the contents of the even integer array with a count, and the contents of the original array after taking out all even integers with a count
No third array should be used
Im having trouble displaying the original array and original integer array after taking out the even integers. here is my code so far
import java.util.*;
public class Arrays
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter in any amount of positive numbers, Enter -1 when finished");
int i=0;
int nextElm=0;
int a,b;
int[] origArray = new int[100]; /* Two arrays at length 100*/
int[] evenArray = new int[100];
while((i<origArray.length && i<evenArray.length)&& nextElm!= -1)
{
System.out.println("Enter next number: ");
nextElm = scan.nextInt();
if (nextElm%2 != 0)//Sorts even numbers
{
origArray[i]= nextElm;
}
else
evenArray[i] = nextElm;
i++;
}
System.out.print("\n");
System.out.println("Even Array: ");
for (b=0; b<evenArray.length;b++)
{
if (evenArray[b]== -1)
{
evenArray[b]= 0;
}
if(evenArray[b]!= 0)
{
System.out.print(evenArray[b]+" ");
}
}
System.out.print("\n");
System.out.println("Original Array: ");
for(a=0; a<origArray.length && a<evenArray.length; a++)
{
if (origArray[a]== -1)
{
origArray[a]= 0;
}
if(origArray[a]!= 0)
{
System.out.print(origArray[a]+" " + evenArray[a]);
}
}
System.out.print("\n");
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter in any amount of positive numbers, Enter -1 when finished");
int i = 0;
int nextElm = 0;
int a, b;
int[] origArray = new int[100]; /* Two arrays at length 100 */
int[] evenArray = new int[100];
while (nextElm != -1) {
System.out.println("Enter next number: ");
nextElm = scan.nextInt();
if (nextElm > 0) {
origArray[i] = nextElm;
i++;
}
}
int x = 0;
System.out.println();
// Displays original array and sorts even numbers to even array +
// original count
System.out.printf("\nTotal count of original array is : %d", i);
System.out.println();
for (int orgNumber : origArray) {
if (orgNumber != 0) {
System.out.print(orgNumber + " ");
}
if (orgNumber % 2 == 0) {
if (orgNumber != 0) {
evenArray[x] = orgNumber;
x++;
}
}
}
System.out.println();
// Displays sort even numbers to even array + even count
System.out.printf("\nTotal count of even array is : %d", x);
System.out.println();
for (int evenNumber : evenArray) {
if (evenNumber != 0) {
System.out.print(evenNumber + " ");
}
}
// Displays sort odd numbers from original array + odd count
System.out.printf("\nTotal count of orignal array without even is : %d", i - x);
System.out.println();
for (int oddNumber : origArray) {
if (oddNumber % 2 != 0) {
System.out.print(oddNumber + " ");
}
}
}
This should work perfectly if I understood your question well. Hope you find this helpful.
You want three separate loops. One for inputting the values (I would suggest the while construct as you have done) and one for sorting the values.
Your input loop should read in a new number each time and only quit when the user wants to. For example, if the user inputs a negative number, then your loop will quit. Like this:
System.out.println("Enter any number of numbers; enter a negative when finished.");
int nextElm = 0;
int count = 0;
while (nextElm >= 0) {
nextElm = scan.nextInt();
origArray[count] = nextElm;
count++;
}
// This is where you would put a print statement that prints the original array with a count.
Now after this, use the java.util.Arrays.copyOf() method to trim out the empty elements of the array, like so:
origArray = java.util.Arrays.copyOf(origArray, count+1);
Next, use a for loop to iterate through the array, and move even numbers to the other array. This is the tricky part, because removing items from an array requires iteration to move each value to it's previous index.
int j = 0;
for (int i=0; i<count; i++){
if (origArray[i] % 2 == 0){
evenArray[j] = origArray[i]; //add even number to evenArray
j++; //move to next index of evenArray
for (int k=i; k<(origArray.length-1); k++){
origArray[k] = origArray[k+1]; //store next value in current index
}
}
}
Then finally, use the java.util.Arrays.copyOf() method to trim out the empty elements of the array again, like so:
evenArray = java.util.Arrays.copyOf(evenArray, j+1);
Disclaimer: This was all coded from the hip so let me know if I missed something or did something incorrectly.

Find the most frequent value in an array of double in Java (without hashmaps or sorting)

Write a full Java program that does the following:
Creates an array of 100 double.
Reads in an unknown number of doubles from a file named values.txt .
There will be at least 2 distinct values, and no more than 100 distinct values in the file. The values will be in unsorted order. Values will be no smaller than 0, and no larger than 99.
Outputs the most frequently occurring value in the file.
Outputs the least frequently occurring value in the file. The value must occur at least once in order to be output.
Outputs the average of all array values.
You must create and use separate methods for each of the items #2-5.
This is what I have so far. I cannot for the life of me figure out how to get this right:
import java.util.*;
import java.io.*;
public class arrayProgram2 {
static Scanner console = new Scanner(System.in);
static final int ARRAY_SIZE = 100;
static int numOfElements = 0;
public static void main(String[] args) throws FileNotFoundException {
Scanner inFile = new Scanner(new FileReader("values.txt"));
double[] Arr1 = new double[ARRAY_SIZE];
while (inFile.hasNext()) {
Arr1[numOfElements] = inFile.nextDouble();
numOfElements++;
}
System.out.println("There are " + numOfElements + " values.");
System.out.printf("The average of the values is %.2f%n", avgArray(Arr1));
System.out.println("The sum is " + sumArray(Arr1));
inFile.close();
} //end main
//Method to calculate the sum
public static double sumArray(double[] list) {
double sum = 0;
for (int index = 0; index < numOfElements; index++) {
sum = sum + list[index];
}
return sum;
}
//Method to calculate the average
public static double avgArray(double[] list) {
double sum = 0;
double average = 0;
for (int index = 0; index < numOfElements; index++) {
sum = sum + list[index];
}
average = sum / numOfElements;
return average;
}
} //end program
Notice I am required to make an array of double even though it is not necessary.
If all values are int than you should use int array instead of double. As all values in range 0-99. So, you can increase input value frequency. Look at below logic:
int[] freqArr= new int[100];
while (inFile.hasNext()){
int value = inFile.nextInt();
freqArr[value]++; // count the frequency of selected value.
}
Now calculate the maximum frequency from freqArr
int maxFreq=0;
for(int freq : freqArr){
if(maxFreq < freq){
maxFreq = freq;
}
}
Note: If double array is mandatory than you can also use double array like:
double[] freqArr= new double[100];
while (inFile.hasNext()){
freqArr[(int)inFile.nextDouble()]++;
}
It's possible to find a most-occurring value without sorting like this:
static int countOccurrences(double[] list, double targetValue) {
int count = 0;
for (int i = 0; i < list.length; i++) {
if (list[i] == targetValue)
count++;
}
}
static double getMostFrequentValue(double[] list) {
int mostFrequentCount = 0;
double mostFrequentValue = 0;
for (int i = 0; i < list.length; i++) {
double value = list[i];
int count = countOccurrences(list, value);
if (count > mostFrequentCount) {
mostFrequentCount = count;
mostFrequentValue = value;
}
}
return mostFrequentValue;
}
Pham Thung is right : -
You read in integer inFile.nextInt(), why do you need to use double array to store them? – Pham Thung
You can achieve your first functionality in n time if its integer array.
you question says,
Values will be no smaller than 0, and no larger than 99.
So,
1. Make an array of size 100.(Counter[])
2. Iterate through values of your current array and add count to Counter array.
eg:
if double array contains
2 3 2 5 0 0 0
Our counter array will be like
location : 0 1 2 3 4 5 6 ...........100
values : 3 0 1 1 0 1 0 ..............
and so on.
You can use below algorithm for this
Sort the array (you only need to read unsorted array, but you can sort the array once read from the file)
Make double var : num, mostCommon, count = 0, currentCount = 1
Assign Arr1[0] to num
for i from 1 to length of Arr1
i. if(Arr1[i] == num)
a. Increment currentCount
ii. else
a. if(count > currentCount)
A. Assign currentCount to count
B. Assign num to mostCommon
C. Assign Arr1[i] to num
D. Assign 1 to currentCount
At the end of this loop, you will have most common number in mostCommon var and it's number of occurrence in count.
Note : I don't know how to format the algo

Categories