How to check array and compute a number from it? - java

I have an array and inside its filled with marks for students. However I cannot display the array contents as I keep receiving a reference code or something. I am now trying to check each index in the array and compare it to the pass mark of 40. When I do use an if statement I can never print the [i] afterwards, all help would be appreciated.
public class Exammarks {
public static void main(String[] args) {
int i = 0;
int [] studentmarks = new int[] {45,60,70,21,95,35,83,80,5,41,40,25};
for(i=1;i < studentmarks.length; i++); {
if (studentmarks[i] < 40)
System.out.println(studentmarks[i]);
}
}
}

try to use for each loop
int [] studentmarks = new int[] {45,60,70,21,95,35,83,80,5,41,40,25};
System.out.println("studentmarks size = " + studentmarks.length);
for(int marks : studentmarks) {
System.out.println("marks = " + marks);
if (marks < 40)
System.out.println("marks less than 40 = " + marks);
}

The Array index starts from 0 whereas you have initialized for loop from 1.
int [] studentmarks = {45,60,70,21,95,35,83,80,5,41,40,25};
for(i=0;i < studentmarks.length; i++)
{
if (studentmarks[i] < 40)
{
System.out.println(studentmarks[i]);
}
}
Also, there was ; at the end of for(i=1;i < studentmarks.length; i++);, which means, scope of for loop end there and below part of the code doesn't come under for loop scope.
{
if (studentmarks[i] < 40)
{
System.out.println(studentmarks[i]);
}
}

You can do this more easily by creating a Stream from the array, filtering out the numbers less than 40 and either converting the stream back to an array if you need or just print the result. For example:
int [] studentmarks = new int[] {45,60,70,21,95,35,83,80,5,41,40,25};
Arrays.stream(studentmarks)
.filter(m -> m < 40)
.toArray();
// [21, 35, 5, 25]
Or if you just need to print the result:
Arrays.stream(studentmarks)
.filter(m -> m < 40)
.forEach(System.out::println);

Related

Finding missing elements in arrays

My program is : In an array 1-10 numbers are stored, one number is missing how do you find it?
I have tried the following code, but it is not giving the right output.
public class MissingNumber {
public static void main(String[] args) {
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 9, 9, 10 };
System.out.println(arr.length);
int arr2[] = new int[10];
for (int i = 0; i < arr2.length; i++) {
arr2[i] = i + 1;
System.out.println("second array is : " + arr2[i]);
}
//compare two arrays i.e arr and arr2
for(int a=0;a<arr.length;a++){
for(int b=0;b<arr2.length;b++){
if(arr[a]==arr2[b]){
break;
}
else{
System.out.println("missing element is : "+arr[a]);
}
}
}
}
}
I want the number which is missing. Can anyone please let me know where I went wrong?
Check below code for if input array is any order or shuffled maner
public class MissingNumber {
public static void main(String[] args) {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 9, 9, 10};
System.out.println(arr.length);
int arr2[] = new int[10];
for (int i = 0; i < arr2.length; i++) {
arr2[i] = i + 1;
}
for (int a = 0; a < arr2.length; a++) {
int count = 0;
for (int b = 0; b < arr.length; b++) {
if (arr2[a] == arr[b]) {
break;
} else {
count++;
}
}
if (arr2.length == count) {
System.out.println("missing element is : " + arr2[a]);
}
}
}
}
You are breaking out from the loop once there is a match from the 2 arrays. From the point of your logic, change it to (you don't need nested loops):
if(arr[a]!=arr2[a]){
System.out.println("missing element is : "+arr[a]);
break;
}
But if it is certain that the array is always in sequential order from 1 onwards, you don't need another array. Just do it as:
for(int x=0; x<arr.lengthl x++){
if(arr[x] != (x+1)){
System.out.println("Missing element is " + (x+1));
break;
}
}
Remove the second array, you don't need it and it might just lead to errors once you add elements to the original array.
Basically, replace your test by:
if(arr[a] != (a+1)){ System.out.println("Missing element: " + (a+1)); }
Don't break out of it, since there might be more elements missing.
You just broke the code when u found a correct match:
Just use the following:
if(arr[a] != arr2[b]){
System.out.println("missing element is : "+arr[a]);
break;
}
Or just replace break with continue
It is not working because you are looping through arr looking for any value that is not in arr2, and every element in arr IS in arr2. You want arr2 as the outer loop.
My program is : In an array 1-10 numbers are stored, one number is missing how do you find it?
It can also be done using just the array itself. Please note that it only works if one of the numbers is missing as specified in this question.
For Example,
Let Array be array = {1,2,3,4,5,6,7,9,9,10}.
Now, let us assume that Array will not always be sorted and hence the first step is to sort the array.
Arrays.sort(array);
Next step is to simply check the array's value at any given location, if the value != location + 1 then that is the missing number.
for(int x = 0; x < array.length; x++) {
if(array[x] != x + 1) {
System.out.println("Missing Entry: " + (x+1));
break;
}
}

Printing value at array index returns hashcode

Just playing around with displaying values in a two dimensional array and noticed my code prints some hashcodes and then the values. But I am not printing the array object itself (as done in the post here) or at least explicitly calling the toString or hashcode method of the array object. Instead, I'm directly accessing and printing the values in the array using arrayObj[i] and arrayObj[i][j].
Here's my code:
class PrintTwoDimArray {
public int [][] createArray () {
int counter = 0;
int[][] intArray = new int [2][4];
for (int i = 0; i < intArray.length; i++) {
for (int j = 0; j < intArray[i].length; j++) {
intArray[i][j] = ++counter;
}
}
return intArray;
}
public void printArray ( int [][] arrayObj ) {
for (int i = 0; i < arrayObj.length; i++) {
System.out.print(arrayObj[i] + " ");
for (int j = 0; j < arrayObj[i].length; j++) {
System.out.print(arrayObj[i][j] + " ");
}
System.out.println();
}
}
}
class TestPrintTwoDimArray {
public static void main (String[] args) {
PrintTwoDimArray twoDim = new PrintTwoDimArray();
int [][] multiArray = new int [2][4];
multiArray = twoDim.createArray();
twoDim.printArray(multiArray);
}
}
My output is as follows:
It seems that my code is somehow calling the toString or hashcode method of the array. Thoughts? How can I modify to print just the values?
javac and java version 1.8.0
A two dimensional array is an array of arrays. The array you create (int[2][4]) looks like this
[ 0 ] -> [ 1, 2, 3, 4 ]
[ 1 ] -> [ 5, 6, 7, 8 ]
So when you only access the first dimension you will get the array that holds the second dimension.
int[][] arr = createArray();
System.out.println(arr[0]);
will output something like
[I#1db9742
To print an array's values you can use Arrays.toString(arr). In this case you can omit the inner loop, because Arrays.toString() will do it for you.
public void printArray ( int [][] arrayObj ) {
for (int i = 0; i < arrayObj.length; i++) {
System.out.println(Arrays.toString(arrayObj[i]));
}
}
The hash values come from your first System.print sentence.
System.out.print(arrayObj[i] + " ");
With this sentence you are printing an Object (an array) and therefore Java is invoking the default toString method.
When you print
arrayObj[i]
you get the default Object toString() from an array. You could use Arrays.toString(int[]) to make that a String like
System.out.println(Arrays.toString(arrayObj[i]));
Alternatively, you can use Arrays.deepToString(Object[]) to print your multi-dimensional array without a loop
System.out.println(Arrays.deepToString(arrayObj));
Edit
You could use formatted output to build your table.
public static void printArray(int[][] arrayObj) {
for (int i = 0; i < arrayObj.length; i++) {
System.out.printf("%03d: ", i + 1);
for (int val : arrayObj[i]) {
System.out.printf("% 4d ", val);
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] table = { { 3, 1, 2 }, { 5, 1, 4 }, { 100, 200, 300 } };
printArray(table);
}
Output is
001: 3 1 2
002: 5 1 4
003: 100 200 300

Finding how many times an item Appears in an Array

Given an array of integers ranging from 1 to 60, i'm attempting to find how many times the numbers 1-44 appear in the array. Here is my method
public static void mostPopular(int[] list, int count)
{
int[] numbers;
numbers = new int[44];
for (int i = 0; i<count;i++)
{
if (list[i]<45 )
{
numbers[i-1]=numbers[i-1]+1; //error here
}
}
for (int k=0; k<44;k++)
{
System.out.println("Number " + k + " occurs " + numbers[k-1]+ "times");
}
}
I'm trying to iterate through the array, list, that contains over 5000 numbers that are between 1-60, then test if that number is less than 45 making it a number of interest to me, then if the integer is 7 for example it would increment numbers[6] By 1. list is the array of numbers and count is how many total numbers there are in the array. I keep getting an ArrayIndexOutOfBoundsException. How do I go about fixing this?
Replace this line numbers[i-1]=numbers[i-1]+1;
with numbers[list[i] - 1] = numbers[list[i] - 1] + 1;
Now it will update the count of correct element.
You need to increment numbers[list[i]] because that's your value which is smaller than 45. i goes up to 5000 and your array numbers is too small.
You should really start using a debugger. All the modern IDE have support for it (Eclipse, IntelliJ, Netbeans, etc.). With the debugger you would have realized the mistake very quickly.
If your initial value is less than 45, it will add 1 to numbers[i-1]. However, since you start with i=0, it will try to add 1 to the value located at numbers[-1], which doesn't exist by law of arrays. Change i to start at 1 and you should be okay.
Very close, but a few indexing errors, remember 0-1 = -1, which isn't an available index. Also, this isn't c, so you can call list.length to get the size of the list.
Try this (you can ignore the stuff outside of the mostPopular method):
class Tester{
public static void main(String args[]){
int[] list = new int[1000];
Random random = new Random();
for(int i=0; i<list.length; i++){
list[i] = random.nextInt(60) + 1;
}
mostPopular(list);
}
public static void mostPopular(int[] list)
{
int[] numbers = new int[44];
for (int i = 0; i< list.length ;i++)
{
int currentInt = list[i];
if(currentInt<45 )
{
numbers[currentInt - 1] = (numbers[currentInt -1] + 1);
}
}
for (int k=0; k<numbers.length; k++)
{
System.out.println("Number " + (k+1) + " occurs " + numbers[k]+ "times");
}
}
}
When i is 0, i-1 is -1 -- an invalid index. I think that you want the value from list to be index into numbers. Additionally, valid indices run from 0 through 43 for an array of length 44. Try an array of length 45, so you have valid indices 0 through 44.
numbers = new int[45];
and
if (list[i] < 45)
{
// Use the value of `list` as an index into `numbers`.
numbers[list[i]] = numbers[list[i]] + 1;
}
numbers[i-1]=numbers[i-1]+1; //error here
change to
numbers[list[i]-1] += 1;
as list[i]-1 because your number[0] store the frequency of 1 and so on.
we increase the corresponding array element with index equal to the list value minus 1
public static void mostPopular(int[] list, int count)
{
int[] numbers = new int[44];
for (int i = 0; i<count;i++)
{
//in case your list value has value less than 1
if ( (list[i]<45) && (list[i]>0) )
{
//resolve error
numbers[list[i]-1] += 1;
}
}
//k should start from 1 but not 0 because we don't have index of -1
//k < 44 change to k <= 44 because now our index is 0 to 43 with [k-1]
for (int k=1; k <= 44;k++)
{
System.out.println("Number " + k + " occurs " + numbers[k-1]+ "times");
}
}

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException in Finding Max Element

Whenever I am trying to run this code, it gives me out of bound exception. Can anyone point me out what's wrong with it.
package com.programs.interview;
import java.util.Scanner;
public class FindMaxNumInArray {
public static void main (String[] args)
{
Scanner scan = new Scanner (System.in);
System.out.print("Enter the size of the array: ");
int arraySize = scan.nextInt();
int[] myArray = new int[arraySize];
System.out.print("Enter the " + arraySize + " values of the array: ");
for (int i = 0; i < arraySize; i++)
myArray[i] = scan.nextInt();
for (int j = 0; j < arraySize; j++)
System.out.println(myArray[j]);
System.out.println("In the array entered, the larget value is "+ maximum(myArray,arraySize) + ".");
}
public static int maximum(int[] arr, int Arraylength){
int tmp;
if (Arraylength == 0)
return arr[Arraylength];
tmp = maximum(arr, Arraylength -1);
if (arr[Arraylength] > tmp)
return arr[Arraylength];
return tmp;
}
}
Output
Enter the size of the array: 5 Enter the 5 values of the array: 1 2 3
4 5 1 2 3 4 5 Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 5 at
com.programs.interview.FindMaxNumInArray.maximum(FindMaxNumInArray.java:26)
at
com.programs.interview.FindMaxNumInArray.main(FindMaxNumInArray.java:17)
This is the problem:
if (arr[Arraylength] > tmp)
Valid array indexes go from 0 to length-1 inclusive. array[array.length] is always invalid, and on the initial call, ArrayLength is equal to arr.length.
It's not clear why you're using recursion at all, to be honest. An iterative solution would be much simpler - but you'll need to work out what you want to do if the array is empty.
EDIT: If you really want how I would write the recursive form, it would be something like this:
/** Returns the maximum value in the array. */
private static int maximum(int[] array) {
if (array.length == 0) {
// You need to decide what to do here... throw an exception,
// return some constant, whatever.
}
// Okay, so the length will definitely be at least 1...
return maximumRecursive(array, array.length);
}
/** Returns the maximum value in array in the range [0, upperBoundExclusive) */
private static int maximumRecursive(int[] array, int upperBoundExclusive) {
// We know that upperBoundExclusive cannot be lower than 1, due to the
// way that this is called. You could add a precondition if you really
// wanted.
if (upperBoundExclusive == 1) {
return array[0];
}
int earlierMax = maximumRecursive(array, upperBoundExclusive - 1);
int topValue = array[upperBoundExclusive - 1];
return Math.max(topValue, earlierMax);
// Or if you don't want to use Math.max
// return earlierMax > topValue ? earlierMax : topValue;
}
you can't access
arr[Arraylength]
the last element would be at
arr[Arraylength -1]
for example if you have
int arr[] = new int[5];
then the elements would be at 4, because index starts from 0
arr[0], arr[1], arr[2], arr[3], arr[4]
Your issue is in the following piece of code:
if (arr[Arraylength] > tmp)
return arr[Arraylength];
Indexes start at 0, so you will be out of bound for an array with 5 elements [1,2,3,4,5] indexes: [0,1,2,3,4].
I would use a plain loop. Java doesn't do recursion particularly well.
public static int maximum(int[] arr) {
int max = Integer.MIN_VALUE;
for(int i : arr) if (i > max) max = i;
return max;
}
here
System.out.println("In the array entered, the larget value is "+ maximum(myArray,arraySize) + ".");
you are passing the arraysize where in maximum method you are returning arr[Arraylength] which giving ArrayIndexOutOfBound so change either in calling maximum(yArray,arraySize-1) or return arr[Arraylength-1] statement.

Not all Array Elements Display When Using A Sort Method Logic

I have this code;
They both use system.out.println statements to print out the array elements. Originally I used a return statement with Arrays.toString(array) to show the array in the main method that worked fine. Now I could like to use print statements just to keep the level of complexity down. As you can see the output form sort is missing the last element in the array, this is because I am using array.length -1. however if I don't use array.length -1 I will get an .ArrayIndexOutOfBoundsException so anyone have a practical solution for this?
import java.util.Arrays;
public class SortMethod
{
static int[] array = {2,1,5,3,5};
public void sort(int[] arrays)
{
for(int i = 0;i < arrays.length - 1;i++ )
{
int store = 0;
if (arrays[i + 1 ] < arrays[i])
{
store = arrays[i];
arrays[i] = arrays[i + 1];
arrays[i + 1] = store;
}
System.out.print(arrays[i]);
}
System.out.println();
}
public void reverse (int[] arrays)
{
for (int i=arrays.length-1; i >=0; i--)
{
System.out.print(arrays[i]);
}
}
/**
* #param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
SortMethod sort = new SortMethod();
sort.sort(array);
sort.reverse(array);
}
}
Output;
From Sort:1235
From Reverse:55321
First of all your sorting method doesn't actually sort properly. You check values with the value immediately to its left, but what happens if you have a 4 at the end of the list?
{2,1,5,3,5,4}
would return the result:
123545
which is hardly sorted... You'll want to take every value you switch, and check it backwards as well making sure its not also smaller than the previous value. Right now you sort values to the right but never back to the left.
Also you can just do the sorting algorithm, and then iterate through the array afterwards and print the values then, rather than trying to print them in the middle of the sorting method:
public class TestCode
{
static int[] array = {2,1,5,3,5,4,9,1,99,7};
public void sort(int[] arrays)
{
for(int i = 0; i < arrays.length - 1 ;i++ )
{
int store = 0;
// Move larger values to the right
if (arrays[i] > arrays[i + 1])
{
store = arrays[i];
arrays[i] = arrays[i + 1];
arrays[i + 1] = store;
// Sort swapped smaller values to the left
for(int j = i; j > 1; j--)
{
if (arrays[j] < arrays[j - 1])
{
store = arrays[j];
arrays[j] = arrays[j - 1];
arrays[j - 1] = store;
}
}
}
}
for(int i = 0; i < array.length; i ++)
{
System.out.print(arrays[i] + " ");
}
System.out.println();
}
public void reverse (int[] arrays)
{
for (int i=arrays.length-1; i >=0; i--)
{
System.out.print(arrays[i] + " ");
}
}
/**
* #param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
TestCode sort = new TestCode();
sort.sort(array);
sort.reverse(array);
}
}
Gives the output:
1 1 2 3 4 5 5 7 9 99
99 9 7 5 5 4 3 2 1 1
SUMMARY:
When sorting arrays you'll need to iterate though the array array.length - 1 times to compare the values (you don't need to compare the last value with the value to its right because there isn't one).
When printing an array you need to iterate through it array.length times and print out each and every value. Your main problem is coming from trying to print out the array in your sorting algorithm which is only iterating through the array array.length - 1 times when you should probably just print the array outside of the sorting algorithm.
The last line of the public void sort(int[] arrays) function:
System.out.println();
should be
System.out.println(arrays[arrays.length - 1]);
as you want to print the hole array.
And for the record, the public void sort(int[] arrays) function does not actually sort an array. It is not what the sort should do just by one pass of checking and swapping of the neighboring elements.
For example, if the array is initialized as:
static int[] array = {2,1,5,3,5};
The resulting array of sort is: 53215, and the reversed array is 51235. Both are not the intended result.
In sort() you're iterating from 0 to arrays.length-1 (exclusive), so for arrays.length==5 variable i will take values: 0, 1, 2, 3
In reverse() you iterate from arrays.length-1 (inclusive) to 0 - i will take values: 4, 3, 2, 1, 0.
When you remove -1 part from arrays.length-1 in sort() you're getting ArrayOutOfBoundsException because you reference arrays[i + 1] which will be out of arrays range for i==4.
Change your sort method as follows :
public void sort(int[] arrays) {
// int i = 0;
for (int i = 0; i < arrays.length - 1; i++) {
int store = 0;
if (arrays[i + 1] < arrays[i]) {
store = arrays[i];
arrays[i] = arrays[i + 1];
arrays[i + 1] = store;
}
System.out.print(arrays[i]);
if (i + 1 == arrays.length - 1) {
System.out.print(arrays[i + 1]);
}
}
System.out.println();
}
Just added a new print statement
if (i + 1 == arrays.length - 1) {
System.out.print(arrays[i + 1]);
}
to print the last array element.
First of all I would like to point out that the code is incomplete. This is just half the sorting code, I can see you are trying to use bubble sort, but unfortunately the inner loop is missing.
Apart from this there is no problem in this code.
Could you just replace your sort method with the one given below? This will fix all the issues.
public void sort(int[] a){
int temp = 0;
for(int i = 0 ; i < a.length ; i++){
for(int j = 0 ; j< a.length - 1 ; j++){
if(a[j] > a[j+1]){
temp = a[j];
a[j] = a[j+1];
a[j+1]=temp;
}
}
}
printArray(a);
System.out.println();
}
public void printArray(int[] a){
for(int i = 0 ; i < a.length ; i++){
System.out.print(a[i]);
}
}
Also, I would recommend you to read about sorting techniques. You can always visit Sorting articles

Categories

Resources