Doing an integrity check in an array? - java

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

Related

Finding best subarray sum and returning it and the subarray

I am relatively new to Java and to coding as well and am currently trying to solve a subset problem.
The goal is to have the user input the amount of numbers and then input every number up to the amount specified, with the computer asking for every n-th number accordingly.
Afterwards the computer should calculate the sum of all subsets, and return the one closest to pi, as well as the subset in this form [x,y,z] within the same line.
I managed the first part just fine, although it might have been improved with a switch-case for convenience. It adds the input numbers into the array
But I struggle with the second part of this problem, and I have no idea how to progress/arrange the code so that it outputs the desired result. The suggestion I got was that, a for-loop for a set with n elements :
for a from 0 to 2^n
for i from 0 to n
when the binary representation of x on has a 1 at the i-th position
add data[i] to solution.
This should supposedly find all subsets of an array. After that I should add each element, check if the distance from pi decreases and add the element to the solution set. Or at least that is the goal, but my code is not functional as I don't know where to start arranging it. I also don't know what to initialize bestsum with, or how the binary representation algorithm works, or how to add elements to the solution array in order.
Edit : I have made progress, the code below outputs all the subarrays, and it properly calculates the closest sum, but I have no idea how to 'save' the best subarray (subarray with the closest sum) so that I can output it at the end with the sum. I am quite new so I haven't learned about lists or even methods, but this problem in this book at this chapter and I would like to solve it with the suggested method and possibly only simple loops.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many numbers should be read? ");
int count = input.nextInt();
double[] data = new double[count];
double [] solution = new double[count];
double bestsum = 0.0;
for (int i = 0; i < count; i++) {
if ((i + 1) % 10 == 1) {
System.out.println("Enter " + (i + 1) + "st number: ");
data[i] = input.nextDouble();
} else if ((i + 1) % 10 == 2) {
System.out.println("Enter " + (i + 1) + "nd number: ");
data[i] = input.nextDouble();
} else if ((i + 1) % 10 == 3) {
System.out.println("Enter " + (i + 1) + "rd number: ");
data[i] = input.nextDouble();
} else {
System.out.println("Enter " + (i + 1) + "th number: ");
data[i] = input.nextDouble();
}
}
for (int j = 0; j <(1 << count); j++) {
System.out.print("{ ");
double sum = 0.0;
for (int x = 0; x < count; x++) {
if ((j & (1 << x)) > 0) {
System.out.print(data[x] + " ");
sum = sum + data[x];
}
solution[x] = data[x];
}
System.out.println("}");
if (Math.abs(sum - Math.PI) < Math.abs(bestsum - Math.PI)) {
bestsum = sum;
}
}
System.out.println(bestsum);
System.out.println(Arrays.toString(solution));
}
}
Here's my solution to this problem.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many numbers should be read? ");
int count = input.nextInt();
Double data[] = new Double[count];
Double bestsum = 0.0;
List<Double> bestArray= Collections.emptyList();
Set<List<Double>> possibleArrays = new LinkedHashSet<>();
for (int i = 0; i < count; i++) {
if (i == 0) {
System.out.println("Enter " + (i+1) + "st number: ");
data[i] = input.nextDouble();
} else if (i == 1) {
System.out.println("Enter " + (i+1) + "nd number: ");
data[i] = input.nextDouble();
} else if (i == 2) {
System.out.println("Enter " + (i+1) + "rd number: ");
data[i] = input.nextDouble();
} else {
System.out.println("Enter " + (i+1) + "th number: ");
data[i] = input.nextDouble();
}
}
input.close();
for (int i = 0; i < (1<<count); i++)
{
int m = 1; // m is used to check set bit in binary representation.
List<Double> currentArray = new ArrayList<>();
for (int j = 0; j < count; j++)
{
if ((i & m) > 0)
{
currentArray.add(data[j]);
}
m = m << 1;
}
possibleArrays.add(currentArray);
}
Iterator<List<Double>> iterator = possibleArrays.iterator();
iterator.next();
for (int i = 1; i < possibleArrays.size(); i++) {
Double sum=0.0;
List<Double> currentArray = iterator.next();
sum = currentArray.stream().collect(Collectors.summingDouble(Double::doubleValue));
if(Math.abs(sum-Math.PI)<Math.abs(bestsum-Math.PI)) {
bestArray = currentArray;
bestsum = sum;
}
}
System.out.println("possibleArrays: " + possibleArrays);
System.out.println("solution: " + bestArray);
System.out.println("bestsum: " + bestsum);
}

How to get the minimum and maximum value inside a user-defined array?

I want to get the minimum value and maximum value inside an array. After the user inputs n number of arrays, it will print the minimum and max value inside that array.
Here is an example output
Here is my code so far
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try {
System.out.println("Enter array size: ");
int n = input.nextInt();
int [] array = new int[n];
int max = getMaxValue(array);
int min = getMinValue(array);
System.out.println("Enter " + n + " elements:");
for (int i = 1; i <= array.length; i++) {
array[i] = input.nextInt();
}
System.out.println("Max Value: " + max);
System.out.println("Min Value: " + min);
} catch (InputMismatchException e) {
System.out.println("INVALID INPUT >> PLEASE INPUT A NUMBER");
}
}
private 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;
}
private 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;
}
}
There are a few problems keeping this program from working:
getMinValue and getMaxValue should be called after your input loop
All 3 of your loops index starting from 1, they should start from 0
The input loop repeats until i <= array.length, but it should end at i < array.length
Problem 1 is that these method are called on the empty array.
Problems 2 and 3 will cause an ArrayIndexOutOfBoundsException.
Here's how the corrections would look in your code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try {
System.out.println("Enter array size: ");
int n = input.nextInt();
int [] array = new int[n];
System.out.println("Enter " + n + " elements:");
for (int i = 0; i < array.length; i++) {
array[i] = input.nextInt();
}
int max = getMaxValue(array);
int min = getMinValue(array);
System.out.println("Max Value: " + max);
System.out.println("Min Value: " + min);
} catch (InputMismatchException e) {
System.out.println("INVALID INPUT >> PLEASE INPUT A NUMBER");
}
}
private static int getMaxValue(int[] array) {
int maxValue = array[0];
for (int i = 0; i < array.length; i++){
if (array[i] > maxValue){
maxValue = array[i];
}
}
return maxValue;
}
private static int getMinValue(int[] array) {
int minValue = array[0];
for (int i = 0; i < array.length; i++){
if (array[i] < minValue) {
minValue = array[i];
}
}
return minValue;
}
}
There were 3 problems in your code which are as follows:
int max = getMaxValue(array) int min = getMinValue(array) are called in wrong places
when we initialize an int array the default value present in it is0.
So when you had call getMaxValue().
array[0] = 0 is compared with all rest of the values in the array (which are 0) and from all 0 is the maximum.
Same goes for getMinValue().
You have called the function getMaxValue() and getMinValue() without filling the array,with user input.
you should have used a for loop from 0 to array.length.
for(int index = 0 ; index < array.length ; index++){
array[index] = input.nextInt();
}
Has you would have noticed, I have index staring from 0 to array size.
what you did:
for (int i = 1; i <= array.length; i++) {
array[i] = input.nextInt();
}
this will cause ArrayIndexOutOfBoundException Because array indexing starts from 0 to n-1 and you allowed it to run till 1 to n.
Additionally, the finding of min and max can be done in one function.
by keeping the return type as an array.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try {
System.out.println("Enter array size: ");
int n = input.nextInt();
int [] array = new int[n];
System.out.println("Enter " + n + " elements:"); // <-- changed
for (int i = 0; i < array.length; i++) {
array[i] = input.nextInt();
}
int max_min[] = getMax_MinValue(array); // <- notice this.
System.out.println("Max Value: " + max_min[0]);
System.out.println("Min Value: " + max_min[1]);
} catch (InputMismatchException e) {
System.out.println("INVALID INPUT >> PLEASE INPUT A NUMBER");
}finally {
input.close(); // close the scanner
}
}
// return type changed
private static int[] getMax_MinValue(int[] array) {
int maxValue = array[0];
int minValue = array[0];
for (int i = 0; i < array.length; i++){
if (array[i] > maxValue){
maxValue = array[i];
}
if(array[i] < minValue) {
minValue = array[i];
}
}
int min_max[] = {maxValue,minValue}; // min_max[0] has max value and min_max[1] has min value
return min_max;
}
Output:
Enter array size:
8
Enter 8 elements:
5
23
9
14
45
36
42
39
Max Value: 45
Min Value: 5
This is not an appropriate answer.
However as the implementations of getMaxValue & getMinValue have a slight flaw: empty arrays will raise an ArrayIndexOutOfBoundException.
And especially one might use the Stream classes.
private static int getMaxValue(int[] array) {
return IntStream.of(array).max().orElse(0);
}
private static int getMinValue(int[] array) {
return IntStream.of(array).min().orElse(0);
}
max and min yield an OptionalInt, and for empty arrays one may give a default (orElse).

java.util.NoSuchElementException reading user input

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]);

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);

Java program won't print out the smallest number in an array

I'm trying to find the largest and smallest number in my array however, it only seems to print out the largest and not the smallest, I'm fairly new so all help is appreciated, thank you.
import java.util.Scanner;
public class Ex1 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int[] numbers = new int[11];
int largest = numbers[0];
int smallest = numbers[0];
System.out.println("Enter 10 numbers = ");
for (int i = 1; i < numbers.length; i++) {
numbers[i] = keyboard.nextInt();
System.out.println("Number " + i + " = " + numbers[i]);
for (int y = 1; y < numbers.length; y++) {
if (numbers[y] > largest)
{
largest = numbers[y];
}
}
for (int x = 1; x < numbers.length; x++)
{
if (numbers[x] < smallest)
{
smallest = numbers[x];
}
}
}
System.out.println("Largest number = " + largest);
System.out.println("Smallest number = " + smallest);
} // main
} // class
It doesn't print out the smallest number because you set it in the beginning to 0, set it to Integer.MAX_VALUE instead.
Also to make sure your program works for negative numbers, set the value of largest to Integer.MIN_VALUE.
int smallest = numbers[0];
This is creating problem. This assigns value 0 in the beginning hence you are not getting smallest number.
Also your test dataset must be containing only positive numbers.
Solution
int largest = Integer.MIN_VALUE;
int smallest = Integer.MAX_VALUE;
There are some code issues other than correctly finding min and max of input numbers.
You don't have to write nested for loops for this. Check below code and that will simply find you min and max numbers,
Scanner keyboard = new Scanner(System.in);
int[] numbers = new int[11];
int largest = numbers[0];
int smallest = numbers[0];
System.out.println("Enter 10 numbers = ");
for (int i = 1; i < numbers.length; i++) {
numbers[i] = keyboard.nextInt();
System.out.println("Number " + i + " = " + numbers[i]);
if (i == 1) {
largest = numbers[i];
smallest = numbers[i];
}
if (numbers[i] > largest) {
largest = numbers[i];
}
if (numbers[i] < smallest) {
smallest = numbers[i];
}
}
System.out.println("Largest number = " + largest);
System.out.println("Smallest number = " + smallest);
try this,
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int[] numbers = new int[10];
System.out.println("Enter 10 numbers = ");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = keyboard.nextInt();
System.out.println("Number " + (i + 1) + " = " + numbers[i]);
}
int largest = numbers[0];
int smallest = numbers[0];
for (int y = 0; y < numbers.length; y++) {
if (numbers[y] >= largest)
{
largest = numbers[y];
}
if (numbers[y] <= smallest)
{
smallest = numbers[y];
}
}
System.out.println("Largest number = " + largest);
System.out.println("Smallest number = " + smallest);
}

Categories

Resources