Its part of codes.In the first part of code i wrote objects of class.This is fine i havent problem.My problem is on the second part of code
Paper[] pin = new Paper[N]; //N are given by keyboard .
for (int i=0; i < N, i++) //until the lenght N
{
pin[i] = new Paper();
}
pin[0].setpencil(3); // the number 3 i random chose it from my mind,i have done get and set methods
pin[0].getpencil(3);
i want to do it not for class and this is the second part of code down.If i want to create objects not using class this is right way?
int[] pin = new int[N];
for (int i=0; i < N, i++)
{
pin[i] = new int();
}
pin[0].setpencil(3);
pin[0].getpencil(3);
If you want to use an array of integers, just use int[N].
int[] pin = new int[N];
That's it. Java initializes primitives for you to 0 (zero) or false for boolean. You do not need a for loop to set the contents of the array, unless you want some value other than zero.
For example, to initialize all values of your array to 42:
int[] pin = new int[N];
for (int i=0; i < N, i++)
{
pin[i] = 42;
}
To read and write this array, you cannot use methods. Just treat the array deference like any other variable.
pin[0] = 3; // pin[0].setpencil(3);
System.out.println( pin[0] ); // pin[0].getpencil(3); prints "3"
However, classes must work differently (or at least they do in Java). If you have an object array instead of primitives:
Class Paper {
void getpencil(int n) {}
void setpencil(int n) {}
}
and an array
Paper[] myPaper = new Paper[N];
You must access this through methods; you cannot use the form above which is only for primitives.
myPaper[0].setpencil(3);
myPaper[0].getpencil(3);
Related
I am supposed to write a short program that takes 10 numbers, stores the values in an array, passes it to a method (eliminateDuplicates()) that creates a new array of only the unique values from the first array.
However, I am having trouble either initializing the output array, or making the eliminateDuplicates() method return the output array properly. The output array is always full of 0's and I cannot figure out why this is failing.
java.util.Arrays.parallelSort(inputNumbers); //sorts the array in ascending order
eliminateDuplicates(inputNumbers); //passes array to eliminateDuplicates method
//display each unique value in output array
System.out.print("The distinct numbers are ");
for(int i = 0; i < outputNumbers.length; i++)
System.out.print(outputNumbers[i] + " ");
}
public static int [] eliminateDuplicates(int[] list) {
int[] outputNumbers = new int [list.length];
int k = 0;
for (int i = 0; i < list.length; i++)
if(i == 0) //compares each array value against preceding value
outputNumbers[i] = list[i]; //only copies unique values to output array
else
if(list[i] != list [i-1]) {
outputNumbers[k] = list[i];
k++;
}
return outputNumbers;```
You have a local outputNumbers in eliminateDuplicates which you return. I assume you also have a redundant static outputNumbers. Option 1: Eliminate the local variable, change
int[] outputNumbers = new int [list.length];
to
outputNumbers = new int [list.length];
Option 2: Set outputNumbers on call (which is what I would likely do, and eliminate the static one)... Like,
int[] outputNumbers = eliminateDuplicates(inputNumbers);
Don't forget to remove the static one if you use option 2.
You are ignoring the array returned by your method.
Change
eliminateDuplicates(inputNumbers);
to
int[] outputNumbers = eliminateDuplicates(inputNumbers);
P.S. your output array has the same length as the input array. Therefore, since you are eliminating duplicates, it may have some 0s as its last elements. If that's not what you want, you should create the output array only after you find out how many unique numbers the input array has.
So I'm trying to make an two dimensional ArrayList which has a set amount of ArrayLists, then each of those ArrayLists can contain as much as needed. I'm aware that arrays dynamically change size, but I'm trying to guarantee that is has at least a certain size in this case.
ArrayList<ArrayList<Integer>> integers = new ArrayList<ArrayList<Integer>>(10);
This doesn't work. I want to be able to set the location of a new Integer to one of the first dimension's indices, like so:
integers.get(7).add(new Integer(42));
This just gives me an IndexOutOfBoundsException, as though there are no Integer ArrayLists within the ArrayList. Is there a way to do this? I'm sure it's something simple I'm not seeing.
Array lists do not work like this. They are not arrays.
The list you created is backed by array of at least 10 elements, but itself it does not contain any, so you cannot refer to 7th or actually any one element.
integers.size() would return 0
integers.isEmpty() would return true
integers.get(0) would throw
Moreover, the list you initialized needs to be filled with lists themselves:
for (int i = 0; i < 10; ++i) {
row = new ArrayList<Integer>()
integers.add(row);
}
// now integers is a 10-element list of empty lists
Alternatively you could use primitive arrays (if you want to have a fixed-size rectangle).
int integers[][] = new int[10][];
for (int i = 0; i < integers.length; ++i) {
integers[i] = new int[10]; // rows are initialized to 0, as int is primitive
}
for (final int[] arr : integers) {
System.out.println(Arrays.toString(arr));
}
You can use a nested loop for this. Here is a short example:
import java.util.ArrayList;
public class PopulateArray {
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> integers = new ArrayList<ArrayList<Integer>>();
int num_arrays_ to_populate = 10;
int num_indices_to_populate = 10;
for(int i = 0; i < num_arrays_to_populate; i++) {
integers.add(new ArrayList<Integer>());
for(int j = 0; j < num_indices_to_populate; j++) {
integers.get(i).add(0);
}
}
}
}
This would create an ArrayList of ArrayLists of ints and fill the top ArrayList with 10 ArrayLists and put a 0 in the first 10 cells of each. Obviously you can change any of those numbers to do what you want.
Note/Disclaimer: I wrote this on my phone, so if I missed a brace or semicolon, just comment and I’ll add it. The logic is there, though.
In this example, i want to add the contents of the two arrays, but I am not able to get how should the input be given. For example, in this case, "invalid assignment operator" error is showing up, for the line int[] a = new int[1,2]. I want to know how to call the function addarr, using the arrays a and b.
public class arradd {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = new int[1,2];
int[] b = new int[3,4];
new arradd.addarr(a,b);
}
public void addarr(int[] arr1, int[] arr2){
int total = 0;
for(int i = 0; i < arr1.length; i++){
total += arr1[i];
}
for(int i = 0; i < arr2.length; i++){
total += arr2[i];
}
System.out.println(total);
}
}
One of your problems why the "invalid assignment operator" error is showing up is because you can't do this in java
int[] a =new int[1,2]; // will give you a compiler error.
the parameter inside the square bracket actually means the size of the array.
int[] a=new int[2];
here 2 means the size of the array 'a'.
if you want to declare the contents for the array, do this
int[] a=new int[2]{1,2};
this is exactly what you need ...where the value inside the square bracket tells the compiler the size of the array 'a' and the values inside the curly braces tells the contents what those are the two contents of the given array 'a'.
And you dont need new operator to or the class name itself to call a method within the class. Just do a
addarr(a,b);
to call the function and your function would be invoked.
You are not declaring your arrays properly, try this way:
int[] a = new int[]{1, 2};
int[] b = new int[]{3,4};
I am trying to add integers into an int array, but Eclipse says:
cannot invoke add(int) on the array type int[]
Which is completely illogical to me. I also tried addElement() and addInt(), however they don't work either.
public static void main(String[] args) {
int[] num = new int[args.length];
for (String s : args){
int neki = Integer.parseInt(s);
num.add(neki);
}
To add an element to an array you need to use the format:
array[index] = element;
Where array is the array you declared, index is the position where the element will be stored, and element is the item you want to store in the array.
In your code, you'd want to do something like this:
int[] num = new int[args.length];
for (int i = 0; i < args.length; i++) {
int neki = Integer.parseInt(args[i]);
num[i] = neki;
}
The add() method is available for Collections like List and Set. You could use it if you were using an ArrayList (see the documentation), for example:
List<Integer> num = new ArrayList<>();
for (String s : args) {
int neki = Integer.parseInt(s);
num.add(neki);
}
An array doesn't have an add method. You assign a value to an element of the array with num[i]=value;.
public static void main(String[] args) {
int[] num = new int[args.length];
for (int i=0; i < num.length; i++){
int neki = Integer.parseInt(args[i]);
num[i]=neki;
}
}
An array has a fixed length. You cannot 'add' to it. You define at the start how long it will be.
int[] num = new int[5];
This creates an array of integers which has 5 'buckets'. Each bucket contains 1 integer. To begin with these will all be 0.
num[0] = 1;
num[1] = 2;
The two lines above set the first and second values of the array to 1 and 2. Now your array looks like this:
[1,2,0,0,0]
As you can see you set values in it, you don't add them to the end.
If you want to be able to create a list of numbers which you add to, you should use ArrayList.
You cannot use the add method on an array in Java.
To add things to the array do it like this
public static void main(String[] args) {
int[] num = new int[args.length];
for (int i = 0; i < args.length; i++){
int neki = Integer.parseInt(s);
num[i] = neki;
}
If you really want to use an add() method, then consider using an ArrayList<Integer> instead. This has several advantages - for instance it isn't restricted to a maximum size set upon creation. You can keep adding elements indefinitely. However it isn't quite as fast as an array, so if you really want performance stick with the array. Also it requires you to use Integer object instead of primitive int types, which can cause problems.
ArrayList Example
public static void main(String[] args) {
ArrayList<Integer> num = new ArrayList<Integer>();
for (String s : args){
Integer neki = new Integer(Integer.parseInt(s));
num.add(s);
}
Arrays are different than ArrayLists, on which you could call add. You'll need an index first. Declare i before the for loop. Then you can use an array access expression to assign the element to the array.
num[i] = s;
i++;
you have an array of int which is a primitive type, primitive type doesn't have the method add. You should look for Collections.
org.apache.commons.lang.ArrayUtils can do this
num = (int []) ArrayUtils.add(num, 12); // builds new array with 12 appended
Right, so I have a 2 part sorting algorithm. It's all based on an array of 14 random integers. For example:
int[] a = {9,2,4,8,9,4,3,2,8,1,2,7,2,5};
Now, the first thing I'm trying to figure out how to do is to count how many a certain number exists in the original array. So, we know that 1 exists once, and 2 exists four times in the original array. But as easy as it is to visually see this, what if we don't have access to the original array. So I need to craft a method that will count how many of each number 1-9 exists and put this in a new array called count. So that index 0 in count would represent the integer 1 and would have a value of 1. Index 1 will represent the integer 2 and have a value of 4. And so on and so forth. Here is what I've got so far but I'm stuck. Sorting is pretty challenging for me.
public static void main(String[] args)
{
// int[] countFinal = {1,4,1,2,1,0,1,2,2}; // The number of times a number 1-9 appears in a[].
// int[] sortedFinal = {1,2,2,2,2,3,4,4,5,7,8,8,9,9}; // What we need as a final product.
int[] a = {9,2,4,8,9,4,3,2,8,1,2,7,2,5};
//int[] count = {};
int[] sorted = {};
countHowMany(a, 1);
countHowMany(a, 2);
countHowMany(a, 3);
countHowMany(a, 4);
countHowMany(a, 5);
countHowMany(a, 6);
countHowMany(a, 7);
countHowMany(a, 8);
countHowMany(a, 9);
}
public static int countHowMany(int[] array, int value)
{
// Gathering a count for how many times a number 1-9 exists and adding it to count[];
int howManyCount = 0;
for (int i = 0; i < array.length; i++)
{
if (array[i] == value)
{
howManyCount++;
}
}
System.out.println(howManyCount);
count = new int[9];
count[howManyCount];
System.out.println(Arrays.toString(count); // Testing the input
return howManyCount;
}
It appears to count the number of times an item in the array exists properly. Now I just gotta figure out how I can add that value into a new array count[] and do it for each countHowMany(). This is the part I'm stuck on.
Once I have figured out count[] I can use it to create sorted[]. Now what sorted is supposed to do is take the data from the original array and count[] and create a new array that sorts it in ascending order and allows duplicates. So, since 1 occurs once and 2 occurs four times, the new array would be sorted[] = {1, 2, 2, 2, 2, ...}
It's a relatively small program and a small amount of integers, so it's ok that I create array's as necessary. The key being that I'm limited to using arrays and cannot use say ArrayLists for this.
You don't need to count each value individually. You can just iterate through the entire array and increment your counters for each element as you encounter it.
int counts = new int[20]; // Choose a value that's bigger than anything in your array.
int[] a = {9,2,4,8,9,4,3,2,8,1,2,7,2,5};
for (int value : a) {
counts[value]++;
}
If you don't know what the largest value in your array is likely to be, you're better to use either a Map to store the counts, or some kind of List that you increase the size of as needed.
You're better off just going through the array once and incrementing a counter for each value that might appear:
int counts[] = new int[10];
for (int n: array)
counts[n]++;
That's enough to put the count for each n in counts[n]. You can then read the values out of your count[] array.
You might not have come across this syntax for a for loop over an array, by the way. It's equivalent to
int counts[] = new int[10];
for (int i=0; i<array.length; i++) {
int n = array[i];
counts[n]++;
}
but it's less verbose.
Your method may as well be void, since you're not doing anything with the returned values of your countHowMany function. This will accomplish what you want:
public static void main(String[] args)
{
int[] a = {9,2,4,8,9,4,3,2,8,1,2,7,2,5};
//count the instances of each number in the array
int[] count = new int[9];
for(int i = 0; i < count.length; i++)
count[i] = countHowMany(a, i+1);
//put the values in the sorted array
int[] sorted = new int[a.length];
int position = 0; // stores the place in the array to put the new digit
for(int digit = 0; digit < 9; digit++)
{
for(int inst = 0; inst < count[digit]; inst++)
{
sorted[position] = digit + 1;
position++;
}
}
System.out.println(Arrays.toString(sorted));
}
The issue with your code is that you were trying to create the count array in each call of the countHowMany method, but this array is destroyed once the method finishes. The method calls should just return the counts, and then those returns should be put into the count array from outside the method. Note, however, that there are other ways to count the number of instances of each value, as noted by other answers.