java.util.NoSuchElementException reading user input - java

I'm getting an error message (java.util.NoSuchElementException) in thread main when attempting to compile the following code with the input 3, then 4, 5, and 7. I've tried to tweak the code, but there's something I'm missing. I was thinking it may be due to my use of arrays since I am just learning how to use those, but I've tried to look closely at them and I didn't see anything I did wrong, but I definitely missed something. Any help would be appreciated. Thanks!
import java.util.Scanner;
public class ArrayMethods2 {
public static int[] findMinAndMax(int[] x) {
int i;
int min = x[0];
int max = x[0];
for (i = 0; i < x.length; i++) {
if (x[i] < min) {
min = x[i];
}
if (x[i] > max) {
max = x[i];
}
}
int [] minAndMax = new int[2];
minAndMax[0] = min;
minAndMax [1] = max;
return minAndMax;
}
public static double averageWithDrop(int[] x) {
int i;
int min = x[0];
int minIndex1 = 0;
int minIndex2 = 0;
int sum = 0;
for (i = 0; i < x.length; i++) {
if (x[i] < min) {
minIndex1 = i;
}
}
for (i = 0; i < x.length; i++) {
if (x[i] < min) {
if (i != minIndex1)
minIndex2 = i;
}
}
for (i = 0; i < x.length; i++) {
if (i == minIndex1) {
sum = sum + 0;
}
else if (i == minIndex2) {
sum = sum + 0;
}
else {
sum = sum + x[i];
}
}
double average = sum / (x.length - 2);
return average;
}
public static void main (String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.print("How many numbers would you like to enter? (must be at least 3) ");
int userValue = scnr.nextInt();
System.out.println(userValue);
while (userValue < 3) {
System.out.println("Invalid value, must be at least 3. Please try again ");
userValue = scnr.nextInt();
System.out.println(userValue);
}
int x = 0;
int indexVal;
int [] userArray = new int [userValue];
while (x <= userValue) {
System.out.print("Enter value for index " + x + ": ");
indexVal = scnr.nextInt();
System.out.println(indexVal);
userArray[x] = indexVal;
x++;
}
int [] minAndMaxVal = new int [2];
minAndMaxVal = findMinAndMax(userArray);
System.out.println("Min value: " + minAndMaxVal[1] + ", Max value: " + minAndMaxVal[2]);
double avg = averageWithDrop(userArray);
System.out.println("Average excluding two lowest values: " + avg);
}
}

Running your code, I did not get any NoSuchElementException, however I got IndexOutOfBoundsException. Check the class your are running.
Please remember arrays are 0 based.
In the main method change while (x <= userValue)to while (x < userValue)
Again, arrays are 0 based, change:
System.out.println("Min value: " + minAndMaxVal[1] + ", Max value: " + minAndMaxVal[2]);
to
System.out.println("Min value: " + minAndMaxVal[0] + ", Max value: " + minAndMaxVal[1]);

There are few problems in the code :
Update this (x <= userValue) to (x<userValue) , else it will give array index out of bounds exception
Start the for loop in minMaxFunction from 1 , since you have already stored the value of arr[0] to min and max like below . This is just an optimization in the code.
for (i = 1; i < x.length; i++) {
if (x[i] < min) {
min = x[i];
}
if (x[i] > max) {
max = x[i];
}
}
This line in main method should have index 0 and index 1 . There is no index 2 since you have declared the array of length 2 , else it will give array index out of bounds exception
minAndMaxVal = findMinAndMax(userArray);
System.out.println("Min value: " + minAndMaxVal[0] + ", Max value: " + minAndMaxVal[1]);

Related

Java Array: Finding how many numbers are less then the Mean

Okay so im trying to find the amount of numbers that are less then
the mean of the first array. Everything but the last part is working and i
cant figure it out. The code at the bottom is what im having problems with.
for example. if i enter 1 2 3 4 5. the mean is 3 and, 1 and 2 are less then 3. so the answer would be 2 numbers.
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("How many integers should we analyze?" );
int num;
num=in.nextInt();
while ( num <= 2)
{
System.out.println( "Please reenter, integer must be greater than 1" );
num=in.nextInt();
}
int[] arr = new int[num];
System.out.println( "Please enter the "+ num +" integers:" );
for (int i = 0; i < arr.length; i++)
{
arr[i] = in.nextInt();
}
System.out.print("Number of integers input: " + num);
System.out.println();
double total = 0;
for( int element : arr) {
total += element;
}
System.out.print("Total: " + (int) total);
System.out.println();
double mean = 0;
if ( arr.length > 0) {
mean = total / arr.length;
}
System.out.print("Mean: " + mean );
int big = arr[0];
for (int i = 0 ; i < arr.length; i++) {
if (arr[i] > big) {
big = arr[i];
}
}
System.out.println();
System.out.print("Largest: " + big);
System.out.println();
///////////////////////////////////////////////////////////////////////////////////////////////
int less;
for(int i=0;i<mean;i++) {
int num2 = i;
int[] arr2 = new int[num2];
int count = 0;
while ( num2 != 0 )
{
num2/=10;
++count;
System.out.print("Numbers less than the mean: " + count);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
}
}
you could use this code below
int count = 0;
for(int i =0;i< arr.length;i++) {
if(arr[i] < mean)
count++;
}
System.out.println("numbers less than mean " + count);
what this does is it loops through all of the original integers and if one is less than the mean, the count variable goes up by 1.
You should iterate over the array and check each element if they are under the mean. If yes, then increment an integer.
int less = 0;
for(int i = 0; i < arr.length; i++) {
if(arr[i] < mean) {
less++;
}
}
System.out.print("Numbers less than the mean: " + less);

Adding 1 to Integer.MAX_VALUE in a loop causes unexpected behaviour (not the one where it goes to Integer.MIN_VALUE)

I was working on a HackerRank challenge for "Array Manipulation", and there was an unexpected, interesting problem encountered. I'm running a big for loop, where I'm adding prefix sums, and the moment I pass over Integer.MAX_Value in the prefix sum (where the sum is stored as an int), the number jumps down by a few thousand instead of looping into the negative which is my expected behaviour.
Anyone know why this could be occuring? There is no problem if you store the prefix sum as a long.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ArrayManipulation {
public static long arrayManipulationPrefixSumLong(int n, int[][] queries) {
long[] array = new long[n];
for (int i = 0; i < queries.length; i++) {
int lowIndex = queries[i][0] - 1;
int highIndex = queries[i][1] - 1;
int addend = queries[i][2];
array[lowIndex] += addend;
if (highIndex + 1 < n)
array[highIndex + 1] -= addend;
}
long maxInt = 0;
for (int i = 0; i < array.length; i++) {
if (i != 0)
array[i] = array[i - 1] + array[i];
if (array[i] > maxInt)
maxInt = array[i];
}
return maxInt;
}
public static int arrayManipulationPrefixSumInt(int n, int[][] queries) {
int[] array = new int[n];
for (int i = 0; i < queries.length; i++) {
int lowIndex = queries[i][0] - 1;
int highIndex = queries[i][1] - 1;
int addend = queries[i][2];
array[lowIndex] += addend;
if (highIndex + 1 < n)
array[highIndex + 1] -= addend;
}
int maxInt = 0;
for (int i = 0; i < array.length; i++) {
if (i != 0)
array[i] = array[i - 1] + array[i];
if (array[i] > maxInt)
maxInt = array[i];
}
return maxInt;
}
public static void main(String[] args) {
Scanner scanner = null;
try {
scanner = new Scanner(new File("input10ArrayManipulation_Subset85545.txt"));
// scanner = new Scanner(new File("input10ArrayManipulation.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int n = scanner.nextInt();
// System.out.println(n);
int qn = scanner.nextInt();
// System.out.println(qn);
int[][] queries = new int[qn][3];
for (int i = 0; i < qn; i++) {
queries[i] = new int[]{scanner.nextInt(), scanner.nextInt(), scanner.nextInt()};
}
scanner.close();
System.out.println(new String(new char[85]).replace("\0", "*"));
System.out.println("Trying to find why exceeding Integer.MAX_VALUE in a loop causes unexpected behaviour.");
System.out.println(new String(new char[60]).replace("\0", "-"));
//Relevant part
long arrayManipulationPrefixSumLong = arrayManipulationPrefixSumLong(n, queries);
int arrayManipulationPrefixSumInt = arrayManipulationPrefixSumInt(n, queries);
//Notice these two give different values
System.out.println("The long version: " + arrayManipulationPrefixSumLong);
System.out.println("The int version: " + arrayManipulationPrefixSumInt);
// Adding past the max value in a loop doesn't result in a negative number,
// to see this behaviour, increment the last line of input10ArrayManipulation_Subset85545 by 1.
System.out.println(Integer.MAX_VALUE - arrayManipulationPrefixSumLong);
//The below is my expected behaviour, where integer overflow occurs.
System.out.println("Max integer is: " + Integer.MAX_VALUE + " | Max integer +1 is: " + (Integer.MAX_VALUE + 1));
System.out.println(new String(new char[60]).replace("\0", "-"));
System.out.println("Now testing with the other file that has 1 incremented on the last line, which makes it exceed the Integer.MAX_VALUE");
try {
scanner = new Scanner(new File("input10ArrayManipulation_Subset85545_increment1.txt"));
n = scanner.nextInt();
// System.out.println(n);
qn = scanner.nextInt();
// System.out.println(qn);
queries = new int[qn][3];
for (int i = 0; i < qn; i++) {
queries[i] = new int[]{scanner.nextInt(), scanner.nextInt(), scanner.nextInt()};
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
arrayManipulationPrefixSumLong = arrayManipulationPrefixSumLong(n, queries);
arrayManipulationPrefixSumInt = arrayManipulationPrefixSumInt(n, queries);
//Notice these two give different values
System.out.println("The long version: " + arrayManipulationPrefixSumLong);
System.out.println("The int version: " + arrayManipulationPrefixSumInt);
scanner.close();
}
}
The text files used to test this program can be found at:
https://drive.google.com/drive/folders/1ktlEixYsqeD2l4x12iD4gEVvM-1gVetK?usp=sharing

Program will print largest number and smallest number

I have some trouble when I try to code a program.
double max = 0, min = 0;
int i;
double array[] = new double[10];
Scanner input = new Scanner(System.in);
for (i = 0; i < 10; i++) {
System.out.println("Give the " + (i + 1) + " number");
array[i] = input.nextDouble();
}
for (i = 0; i < 10; i++) {
if (array[i] > max) {
max = array[i];
}
for (i = 0; i < 10; i++) {
if (array[i] < min) {
min = array[i];
}
}
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);
When I type 10 numbers that include one largest number and one smallest number,
the result is
The Max is : largest number
The Min is : 0.0
Always the Smallest I get the 0.0 whatever I type. No 2 I will type, No 4 I will type as a smallest number (always on separate launch), every time I get 0.0.
Your initial value for minimum is zero, and I assume your data has nothing that is less than zero.
Try setting your min initial value to Double.MAX_VALUE
you Initializing max and min before entering number into the array , when tring to find the max and the min , first enter the numbers to the array then compare them with the array[0].
second thing is that you dont need to for loops to check whether you need to change max or min , you can do it in one for loop .
try this :
double array[] = new double[10];
int i;
Scanner input = new Scanner(System.in);
for (i = 0; i < 10; i++) {
System.out.println("Give the " + (i + 1) + " number");
array[i] = input.nextDouble();
}
double max = array[0], min = array[0];
for (i = 0; i < 10; i++) {
if (array[i] > max) {
max = array[i];
}
if (array[i] < min) {
min = array[i];
}
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);
Two simple corrections:
You just have to set initialized min and max to some values in array. (e.g. array[0] for your problem)
there is no need to 3 for loops to find the min and max, just use one.
see below code:
int i;
double array[] = new double[10] ;
Scanner input = new Scanner (System.in) ;
System.out.println("Give the " + (1) + " number") ;
array[0] = input.nextDouble();
double max = array[0], min = array[0];
for (i = 1; i < 10; i++)
{
System.out.println("Give the " + (i+1) + " number") ;
array[i] = input.nextDouble();
if(array[i] > max)
max = array[i] ;
if (array[i] < min)
min = array[i];
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);
Your curly braces are not proper. You are ending the max loop before the SYSOUT.
double max = 0, min = 0;
int i;
double array[] = new double[10] ;
Scanner input = new Scanner (System.in) ;
for (i = 0; i < 10; i++)
{
System.out.println("Give the " + (i+1) + " number") ;
array[i] = input.nextDouble();
}
max = array[0];
min = array[0];
for (i = 0; i < 10; i++) {
if (array[i] > max) {
max = array[i];
}
}
for (i = 0; i < 10; i++) {
if (array[i] < min) {
min = array[i];
}
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);
Run this. It will give the proper result.

calculating the sum between two integers (java)

What did I do wrong? I'm really not sure what else to try or where my mistake is. Thanks for any help. It's supposed to calculate the sum of integers between two numbers, e.g. between 3 and 6 it would be 3 + 4 + 5 + 6
import java.util.Scanner;
public class TheSumBetweenTwoNumbers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("First:");
int n = Integer.parseInt(reader.nextLine());
System.out.println("Second:");
int max = Integer.parseInt(reader.nextLine());
int sum = 0;
int i = 0;
int difference = max - n;
while (i < difference) {
sum = n + (n + 1);
n++;
i++;
}
System.out.println("Sum is " + sum);
}
}
Why all this you need just a piece of code like this :
public static void main(String args[]) {
int min = 3, max = 6, sum = 0;
for (int i = min; i <= max; i++) {
sum += i;
}
System.out.println(sum);
}
With while loop it should be :
...
int i = min;
while (i <= max) {
sum += i;
i++;
}
...
You don't need to find a difference and loop over it, just running a loop from n to max will do. Also, you need to add the value to sum (+=) instead of assigning a value to it (=, which overwrites previous value)
Try this:
int i = n;
while (i <= max) {
sum += i;
i++;
}
You're overwriting the previous sum value with the most recent n + (n + 1), instead of accumulating the previous sum. Also, your loop is one iteration short. Try this:
int sum = 0;
for (int i = n; i <= max; i++) {
sum += i;
}
System.out.println("Sum is " + sum);
Change this snippet
int sum = 0;
int i = 0;
int difference = max - n;
while (i < difference) {
sum = n + (n + 1);
n++;
i++;
}
In
int sum = 0;
int i = n;
while (i <= max) {
sum = sum + i;
i++;
}
You made it a little bit overcomplicated. All you really need is a for loop that runs from n to max that adds up the incrementing variables:
int sum = 0;
for(int i = n; i <= max; i++){
sum += i;
}

Doing an integrity check in an array?

Doing a rather large assignment for my java class. I've written the entire program, but I've run into one last problem, there needs to be a check on the user input into the array to make sure it is an integer that the user is inputting, and not junk(a, Z, 2.0, #%&##%*#%^, etc.) and if that error happens, it has to loop back, reallowing the input with an error message until they comply.
I've heard of using try/catch to try as a solution, and I've also thought of maybe a while loop, but still not sure on how to go about it. Any tips?
import java.util.Scanner;
import java.util.Arrays;
public class Assignment6 {
public static int getMaxValue(int[] array) {
int maxValue = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > maxValue) {
maxValue = array[i];
}
}
return maxValue;
}
public static int getMinValue(int[] array) {
int minValue = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < minValue) {
minValue = array[i];
}
}
return minValue;
}
public static double average(int[] array) {
double sum = 0, average = 0;
for (int i = 0; i < array.length; i++) {
sum = sum + array[i];
average = sum / array.length;
}
return average;
}
public static double Median(int[] array) {
int Median = array.length / 2;
if (array.length % 2 == 1) {
return array[Median];
} else {
return (array[Median - 1] + array[Median]) / 2.0;
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter size of array: ");
int[] array = new int[input.nextInt()];
for (int i = 0; i < array.length; i++) {
System.out.print("Enter value #" + (i + 1) + ": ");
array[i] = input.nextInt();
}
System.out.println("\nYour data is:");
for (int i : array)
System.out.print(i + "\n");
System.out.println();
System.out.println("Average is : " + average(array));
System.out.println("Smallest value is: " + getMinValue(array));
System.out.println("Largest value is: " + getMaxValue(array));
System.out.println("\nYour sorted data is: ");
Arrays.sort(array);
for (int i = 0; i < array.length; i++)
System.out.println(array[i]);
double Median = Assignment6.Median(array);
System.out.println("\nThe median is: " + Median);
int Range = Assignment6.getMaxValue(array) - Assignment6.getMinValue(array);
System.out.println("\nThe range is: " + Range);
double midRange = (Assignment6.getMaxValue(array) + Assignment6.getMinValue(array)) / 2.0;
System.out.println("\nThe Midrange is: " + midRange);
}
}
Since you used Scanner.nextInt(), it is not possible that non-integer input was added to the array. Additionally, it is not possible that a non-integer value got into your int[]. The program would likely not compile, and even if it did, would throw a run-time exception.
However, if the user inputs a non-integer, your program will crash. It doesn't really have anything to do with an array, but I'm guessing this is what you meant by your question. The correct way to safely read only integer input from the user with a Scanner would be:
for (int i = 0; i < array.length; i++) {
System.out.print("Enter value #" + (i + 1) + ": ");
while (!input.hasNextInt()) { // <-- 'peeks' at next token
System.out.println("Please enter an integer!");
input.next(); // <-- skips over invalid token
}
array[i] = input.nextInt();
}
You can also use Integer.parseInt(yourString) and it will throw a NumberFormatException if the String is not a valid

Categories

Resources