Print array length without using predefined functions - java

I am new to this programming world. I tried to print length of the array without using predefined functions.
But when i run my code i am getting Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
can someone please help me to find out the bug
Here is my code.
public class Arraylen {
public static void main(String[] args) {
int[] ary = {1, 3, 4, 5, 68, 9};
int len;
for(len = 1; ary[len] != '\0'; len++) {
System.out.println(len);
}
}
}

What is wrong with using ary.length? .length is a property and not a function. You would not be coding ary.length(), let alone that "function" doesn't even exist.
public class StackOverflow {
public static void main(String args[]) {
int[] ary = {1, 3, 4, 5, 68, 9};
System.out.println(ary.length);
}
}
Result:
6

Just use an enhanced for loop:
public class Arraylen
{
public static void main(String[] args)
{
int[] ary = {1,3,4,5,68,9};
int len = 0;
for(int number : ary)
{
len++;
}
System.out.println(len);
}
}
This iterates over every item in the array, without you having to worry that the index will go over the array size.

You could also use a while loop with a try-catch block to find the length.
Something like this:
boolean lengthFound = false;
int length = 0;
while (!lengthFound) {
try {
// This line throws an Exception when length is equal to the length of the array
int notImportant = array[length] + 2;
length++;
}
// This prevents the exception from breaking anything and gets you out of the
// loop
catch (ArrayOutOfBoundsException ex) {
lengthFound = true;
}
}
// At this point array.length == length

Related

How do I initialize elements of an array, 1 through 10, and then use that constructor in a method that will print the elements?

I have an assignment for object-oriented programming class. I've been trying to take the values of an array that were initialized in a constructor, and use the values from that constructor to print them in a different method called printArrayValues. I cannot seem to 'call' or return the values in the method.. I've been troubleshooting for hours and I'm getting frustrated.
The assignment's steps are as follows:
The constructor for the ExerciseOne class initializes and instantiates myArray as an array of ten integers, and initializes the elements of the array with the values 1 through 10, using a for-loop.
You must assign the values in terms of the for-loop index variable, for example, i.
The class has a method called printArrayValues that uses a for-loop and System.out.print() statement to print out the values of the elements of the array, as shown in the sample output.
This method has no parameters, and no return value.
I've tried creating a new variable in the constructor, and then calling it in the method, but it's not working.
public class ExerciseOne {
public int[] myArray;
public static void main(String[] args) {
ExerciseOne aExerciseOne = new ExerciseOne();
aExerciseOne.printArrayValues();
}
ExerciseOne() {
for (int i = 0; i < myArray.length; i++) {
this.myArray = new int[i];
}
}
public void printArrayValues() {
System.out.print("myArray = {");
for (int a = 0; a < myArray.length; a++) {
System.out.print((myArray[a] + 1));
if (a < 9) {
System.out.print(",");
}
else {
System.out.print("};");
}
}
}
//
//public void displayArrayProduct() {
// for (int : myArray) {
//
// }
//
//}
}
I got frustrated and just created the loop, to initialize it, in the method. This is incorrect for the assignment, but I wanted to move on. Honestly I'm very lost at this point and I'm sorry if that makes it more difficult to help me.
You can try this code.
public class ExerciseOne {
public int[] myArray = new int[10];
public static void main(String[] args) {
ExerciseOne aExerciseOne = new ExerciseOne();
aExerciseOne.printArrayValues();
}
ExerciseOne() {
for (int i = 0; i < myArray.length; i++) {
this.myArray[i] = i+1;
}
}
public void printArrayValues() {
System.out.print("myArray = {");
for (int a = 0; a < myArray.length; a++) {
System.out.print((myArray[a]));
if (a < 9) {
System.out.print(",");
}
else {
System.out.print("};");
}
}
}
}
Output: myArray = {1,2,3,4,5,6,7,8,9,10};
You are initializing the same array twice. Your program will work the same if you use any of below :
myArray = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9 , 10};
or
myArray = new int[10]; for (int i = 0; i < myArray.length; i++) { this.myArray[i]=i+1; }
as your array is not 2d array so you cant assign another array on elements of array.
this.myArray = new int[i]; // not correct
I've written and tested the below and it returns the output you need. Please note that it's been written in C# for a console application. If it helps then please remember to vote for me.
Create your ExerciseOne class like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test
{
public class ExerciseOne
{
int[] eo;
public ExerciseOne()
{
eo = new int[10];
for (int i = 0; i <= 9; i++)
{
eo[i] = i + 1;
}
printArrayValues();
}
public void printArrayValues()
{
foreach (var item in eo)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
}
}
Then call the class like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test
{
class Program
{
static void Main(string[] args)
{
ExerciseOne one = new ExerciseOne();
}
}
}

Error Handling in Java Task

public class SomeClass {
int[] table;
int size;
public SomeClass(int size) {
this.size = size;
table = new int[size];
}
public static void main(String[] args) {
int[] sizes = {5, 3, -2, 2, 6, -4};
SomeClass testInst;
for (int i = 0; i < 6; i++) {
testInst = new SomeClass(sizes[i]);
System.out.println("New example size " + testInst.size);
}
}
}
When the constructor SomeClass is called with an argument of -2, a run time error will be generated: NegativeArraySizeException.
I am looking to modify this code so that it behaves more robustly by using try, catch and throw. The constructor should throw an exception but otherwise do nothing when called with a non-positive argument. The main method should catch the exception and print a warning message then continue execution through all six iterations of the loop.
Somebody point me in the right direction ?
You need to throw an exception (preferably IllegalArgumentException) from your constructor of SomeClass whenever you get a negative number and handle it in your main method.
Your code should look like;
public class SomeClass
{
int[] table;
int size;
public SomeClass(int size)
{
if ( size < 0 )
{
throw new IllegalArgumentException("Negative numbers not allowed");
}
this.size = size;
table = new int[size];
}
public static void main(String[] args)
{
int[] sizes = { 5, 3, -2, 2, 6, -4 };
SomeClass testInst;
for (int i = 0; i < 6; i++)
{
try
{
testInst = new SomeClass(sizes[i]);
System.out.println("New example size " + testInst.size);
}
catch (IllegalArgumentException e)
{
System.out.println(e.getMessage());
}
}
}
}
There are operations, like connecting to a remote server using a Socket, which can throw exceptions like SocketException. You need to catch and deal with those exceptions because before you aptempt the connection there is no way to know if it is going to suceed or not.
NegativeArrayException is not like that. Before aptempting to create the array you can know for sure that it is going to fail if you use a negative size.
If the size comes from your code, as is the case, you should fix your code rather than catching that exception.
If it comes from any input you should verify that input and act acordingly before trying to create the array.
Assuming your array of sizes is actually a simplified example of input the way to deal with it would be :
public class SomeClass {
int[] table;
int size;
public SomeClass(int size) {
this.size = size;
table = new int[size];
}
public static void main(String[] args) {
int[] sizes = {5, 3, -2, 2, 6, -4};
SomeClass testInst;
for (int i = 0; i < 6; i++) {
if (sizes[i] < 0) {
System.out.println("Warning");
} else {
testInst = new SomeClass(sizes[i]);
System.out.println("New example size " + testInst.size);
}
}
}
}
Which gives as output :
New example size 5
New example size 3
Warning
New example size 2
New example size 6
Warning

Counting Repeated Elements in Given Array

How to count repeated elements in given array? Please give me any suggestion as an alternative for this problem.
public static void main(String[] args)
{
// TODO Auto-generated method stub
int a[]={1,2,3,1,2,4,4,4,5};
int c=0;
for(int i=0;i!='\0';i++)
{
c=1;
for(int k=i+1;k<9;k++)
{
if(a[i]==a[k] && a[i]!='\0')
{
c++;
// a[k]='\0';
}
}
if(a[i]!='\0')
{
System.out.println("value is"+a[i]+"repeated in"+c);
System.out.println("\n");
}
}
}
Here's another simple approach that does not require a separate data structure:
Sort the array using Arrays static method
Now you can iterate over the array knowing all duplicates will be grouped together. Shouldn't be hard to figure out....
Pilfering my code from another answer:
public static void main(String[] args) throws Exception {
int[] a = {1, 2, 3, 1, 2, 4, 4, 4, 5};
final Counter<Integer> counter = new Counter<>();
IntStream.of(a).forEach(counter::add);
IntStream.rangeClosed(1, 5).forEach(i -> {
System.out.printf("%s has a count of %s%n", i, counter.count(i));
});
}
public static class Counter<T> {
final Map<T, Integer> counts = new HashMap<>();
public void add(T t) {
counts.merge(t, 1, Integer::sum);
}
public int count(T t) {
return counts.getOrDefault(t, 0);
}
}
Output:
1 has a count of 2
2 has a count of 2
3 has a count of 1
4 has a count of 3
5 has a count of 1

comparing values of two arrays if exist or not

I have this code which is to check in the two arrays and print out the values that dont exist in the other array. I think the way i did it is not the most efficient way to do it hence can anyone offer a better OOP way to write this code in Java?
Thanks
public class Calculate {
static int [] x = {1,2,4,6,7};
static int [] y = {2,3,4,6,7};
static boolean xflag = true;
static boolean yflag = true;
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<x.length; i++)
{
for (int b=0; b<y.length; b++)
{
if(x[i]!= y[b])
{
xflag= false;
}
else
{
xflag = true;
break;
}
}
if(xflag==false)
{
System.out.println(x[i] +" does not exist in array 2");
}
}
for(int i = 0; i<x.length; i++)
{
for (int b=0; b<y.length; b++)
{
if(y[i]!= x[b])
{
yflag= false;
}
else
{
yflag = true;
break;
}
}
if(yflag==false)
{
System.out.println(y[i] +" does not exist in array1");
}
}
}
}
Using Collection class removeAll method
String original[] = { "1","2","3","4","6"};
String testStr[] = { "1","2","3","5","7" };
List origList = new ArrayList(Arrays.asList(original));
List testList = new ArrayList(Arrays.asList(testStr));
System.out.println(origList.removeAll(testList));
System.out.println(origList);
you can use java collection framework, Many function are there,
here is simple example check it.
public static void main(String a[]){
List<String> sl = new ArrayList<String>();
sl.add("apple");
sl.add("java");
sl.add("c++");
sl.add("unix");
sl.add("orange");
sl.add("airtel");
List<String> tl = new ArrayList<String>();
tl.add("job");
tl.add("oracle");
tl.add("jungle");
tl.add("cricket");
boolean isCommon = Collections.disjoint(sl,tl);
System.out.println("Does not found any common elements? "+isCommon);
tl.add("java");
isCommon = Collections.disjoint(sl,tl);
System.out.println("Does not found any common elements? "+isCommon);
}
You may use Apache's CollectionUtils for this purpose if you want an abstraction from the implementation logic.E.g:
public static void main(String[] args) {
List<Integer> list1=Arrays.asList(1,2,4,6,7);
List<Integer> list2=Arrays.asList(2,3,4,6,7);
System.out.println(CollectionUtils.disjunction(list1,list2));
}
You can code this way
List<Integer> array1 = Arrays.asList(1,2,4,6,7);
List<Integer> array2 = Arrays.asList(2,3,4,6,7);
List<Integer> disjointArray = new ArrayList<Integer>();
for (Integer value : array1) {
if (!array2.contains(value)) {
disjointArray.add(value);
}
}
And then you can print disjointArray or do whatever manipulation you want.
Here a running example using Javas Collection classes:
public class Disjunction {
public static void main(String args[]) throws UnsupportedEncodingException {
//Some data preparation
List<Integer> list1=Arrays.asList(1,2,4);
List<Integer> list2=Arrays.asList(5,2,8);
//Here calculating data1-data2 and data2-data1, collect all list items
//that are in data1 or in data2 but not in both.
List<Integer> data1 = new ArrayList<>(list1);
data1.removeAll(list2);
List<Integer> data2 = new ArrayList<>(list2);
data2.removeAll(list1);
//Merging both results. data1 contains now exclusive or of list1 and list2
data1.addAll(data2);
System.out.println("exclusive or is " + data1);
}
}
It prints out
exclusive or is [1, 4, 5, 8]
Try the following program that checks two arrays for numbers they both have and numbers they don't have:
package test;
import java.util.ArrayList;
public class ArrayDifferentiater {
public static void main(String[] args) {
int[] ori = { 1, 5, 4, 8, 6, 65, 16, 6, 575, 64, 561, 57, 57 };
int[] che = { 1, 4, 8, 6 };
sort(ori, che);
}
public static void sort(int[] a, int[] b) {
/**
* 'foundNum' contains the numbers which exists in both array.
* 'notFoundNum' contains the numbers which exists in only first array.
*/
ArrayList<Integer> foundNum = new ArrayList<>();
ArrayList<Integer> notFoundNum = new ArrayList<>();
// First for loop starts
for (int i = 0; i < a.length; i++) {
// Second for loop starts
for (int j = 0; j < b.length; j++) {
/**
* Check if array 1 contains value of array 2.
* If contains than add it to "foundNum" arraylist.
*/
if (a[i] == b[j]) {
foundNum.add(a[i]);
// Remove the number which exists in both arrays from "notFoundNum" arraylist.
if (notFoundNum.contains(a[i])) {
for (int k = 0; k < notFoundNum.size(); k++) {
if (notFoundNum.get(k) == a[i]) {
notFoundNum.remove(k);
}
}
}
break;
} // First if block ends
/**
* Checks if a not found number does not exists in 'notFoundNum' arraylist (to reduce redundancy)
* then adds a not found number to 'notFoundNum' arraylist
* */
if (!notFoundNum.contains(a[i]))
notFoundNum.add(a[i]);
} // Second for loop ends
} // First for loop ends
System.out.println("Found Numbers : " + foundNum);
System.out.println("Not Found Numbers : " + notFoundNum);
}
}
Here is the output for the above program:
Found Numbers : [1, 4, 8, 6, 6]
Not Found Numbers : [5, 65, 16, 575, 64, 561, 57]

Find the dimension of array

I know its a silly question but I want to know that Is it possible to find the array dimension? when we have the following code
public class ArrayDimentionCheck {
public static void main(String[] args) {
Integer[][] arr = { { 1, 2 }, { 2, 3 } };
printDimension(arr);
Integer[][] arr1 = { { 1, 2, 4 }, { 2, 3, 6 } };
printDimension(arr1);
}
private static void printDimension(Object arr) {
System.out.println("given object dimension:");
}
}
Can we write some generic code in printDimension method to identify the array dimension??
but I want result in following format for arr it should be 2x2 and arr1 3x2
You should know, that in java you can do this:
Integer[][] arr = { { 1, 2 }, { 1, 3, 4, 5 } };
So the code below doesn't work for jagged arrays.
Also it doesn't work for 0-length arrays such as:
new boolean[11][0][4]
Here the code is:
public static void printDimension(Object array) {
if (array == null) {
System.out.println("Object is null!");
return;
}
if (!array.getClass().isArray()) {
System.out.println("Object is not array!");
return;
}
String ans = "";
Object cur = array;
while (cur != null && cur.getClass().isArray()) {
ans += "x" + Array.getLength(cur);
if (!cur.getClass().getComponentType().isPrimitive()) {
cur = ((Object[]) cur)[0];
} else {
break;
}
}
System.out.println(ans.substring(1));
}
Example of usage:
printDimension(new boolean[1][11]);
printDimension(new boolean[1][11][4]);
printDimension(new Integer[14][88]);
Output:
1x11
1x11x4
14x88
2-D array is a array of arrays. So each array can have variable length (which represents columns in case of 2-D array). You can get length of individual arrays using
args[0].length;
args[1].length;
and so on
and length of whole 2-D array using
args.length
which is number of rows in 2-D array.
Related question: Multi-Dimension length array reflection java
you can use Array.lenght to know the lenght .. and by using this you can find the dimension . for example
int xx = arr.length; // will return the number of row
int yy = arr[0].length; // will return the number of column
N.B. assuming that every row has same number of columns
You can find the dimensions of an array using recursion and reflection.
Given the method dimensions:
private int dimensions(Class arrayType)
{
return arrayType.isArray() ? 1 + dimensions(arrayType.getComponentType()) : 0
}
When calling the dimensions method like this:
int[] oneDimensionalArray = new int[0];
int[][] twoDimensionalArray = new int[0][0];
int[][][] threeDimensionalArray = new int[0][0][0];
System.out.println(dimensions(oneDimensionalArray.getClass()));
System.out.println(dimensions(twoDimensionalArray.getClass()));
System.out.println(dimensions(threeDimensionalArray.getClass()));
Will print:
1
2
3
I think you are asking obj is single dimension or double dimension or ... of array type.
private static void printDimension(Object arr) {
final String className = arr.getClass().toString();
Pattern pattern = Pattern.compile("([\\[])");
Matcher matcher = pattern.matcher(className);
int count = 0;
while (matcher.find()) count++;
int length = count>1?((Object[][])arr)[0].length:0;
System.out.println("given object dimension:"+count+"x"+length);
}
...
Integer[][][] arr = new Integer[3][2][2];
printDimension(arr);
Integer[] arr1 = {};
printDimension(arr1);
printDimension(new Object());
result :
given object dimension:3x2
given object dimension:1x0
given object dimension:0x0

Categories

Resources