How to declare an array element null? - java

I am trying to find out whats happening with my code, I kept getting nullexeptionpointer problem. So I decided to reduce my code and find out whats happening. I want to remove a particular element providing the index to be removed, afterwards, moving all element after it to fill up the space left.
After moving all element, I want to set the last element in the array to null, but i get error and wont compile.
public static void main(String[] args) {
int [] charSort = new int[] {12, 5, 7, 4 ,26 ,20 ,1, 6 ,3 ,14, 8, 11};
TextIO.putln("ArrayNum = [12, 5, 7, 4 ,26 ,20 ,1, 6 ,3 ,14, 8, 11]\n");
TextIO.put("Sorted ArrayNum is: \n");
//IntSelecttionSort(charSort);
TextIO.putln(Arrays.toString(charSort));
TextIO.put("Enter: "); RemoveShift (charSort, TextIO.getInt());
}
public static void RemoveShift (int[] move, int p){
for(int i = 0; i<move.length; i++){
TextIO.put(i+", ");
}
TextIO.putln();
for(int i = p; i<move.length-1; i++){
move[i]=move[i+1];
}
move[move.length-1]=null; // null seems not to work here
TextIO.putln(Arrays.toString(move));
}

int is a primitive, and can't be assigned the value null.
If you want to use null here, you can use the wrapper class Integer instead:
public static void RemoveShift (Integer[] move, int p){
Because of autoboxing, you can even initialize your array in the same way:
Integer[] charSort = new Integer[] {12, 5, 7, 4 ,26 ,20 ,1, 6 ,3 ,14, 8, 11};
As #JBNizet points out, a nice alternative if you want to modify an array of Integer is to use an ArrayList instead. That can make your life much easier.

Related

Generating an array of non-repeating integers

I'm trying to generate an array of 5 non-repeating integers in Java, but there are still repeats when I run it. Here's my code so far:
public int[] generateCode(){
code[0] = (int)Math.round(Math.random()*8+1); // initialize first number so it won't be compared against
for(int i=1; i<code.length; i++){
code[i] = (int)Math.round(Math.random()*8)+1;
for(int j=0; j<i; j++){
while(code[i]==code[j]){
code[i] = (int)Math.round(Math.random()*8)+1;
}
} // end inner for loop
} // end outer for loop
return code;
} // end generateCode method
Any help is very much appreciated!
So, your for-loop is checking for repeated characters, BUT each time you generate a new value (in the while-loop) you're not checking to see if the value exits before j.
There are a number of possible ways you might address this issue, I prefer ones which uses Collections.shuffle, but assuming that you can't use features like Arrays, Collections, List, Set or possibly even streams, we need to work with what we have, arrays.
Since you have a small range of acceptable values which need to fit into an even smaller range, a simple solution might be to generate a "master" list of allowed values and randomly select a value from the master list, tracking which values you've already picked.
Sounds more complicated then it actually is, for example...
public int[] generateCode() {
int[] masterValues = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] codes = new int[5];
Random rnd = new Random();
int index = 0;
while (index < codes.length) {
int lookupIndex = 0;
do {
lookupIndex = rnd.nextInt(masterValues.length);
} while (masterValues[lookupIndex] == 0);
codes[index] = masterValues[lookupIndex];
masterValues[lookupIndex] = 0;
index++;
}
return codes;
}
This creates a "master" list of values. It then randomly calculates a "lookup" index, checks to see if the value in the master list is 0 or not, if not, it assigns it to the next index in the codes array and sets the value in the master list to 0, otherwise it generates a new random index and tries again. This all repeats till it fills the codes array
So doing something like...
System.out.println(Arrays.toString(generateCode()));
System.out.println(Arrays.toString(generateCode()));
System.out.println(Arrays.toString(generateCode()));
System.out.println(Arrays.toString(generateCode()));
could print (because it's "random")...
[8, 1, 4, 7, 5]
[9, 6, 2, 1, 8]
[6, 5, 9, 4, 7]
[2, 5, 3, 1, 4]
There are much easier ways to do this. Using a Set<Integer> would be one. Here is another.
List<Integer> list = new ArrayList<>(List.of(1,2,3,4,5,6,7,8));
Collections.shuffle(list);
System.out.println(list.subList(0,5));
prints something like
[4, 5, 8, 2, 1]
As was pointed out to me, you may not be allowed to use or know about collections. But I would recommend you at least make a helper method to check for duplicates to reduce the clutter. Something like the following:
public boolean contains(int[] arr, int n) {
for (int v : arr) {
if (v == n) {
return true;
}
}
return false;
}
Then you can keep checking the current value to be false before you add it. Once it works it also lets you focus on other aspects of your code.

Java take range from array

Does Java have a method of Array drop? In Scala we have: Array.drop(10).take(16) or maybe to take a range of members of an array?
In Java I can only do array[10] for example.
There is Arrays::copyOfRange:
It has three parameters:
original: the source array
from: the starting index, inclusive
to: the end index, exclusive
Not that it returns a new array, meaning that if you change the values of the resulting array, the original array does not change.
The method is overloaded to work for all primitive types and for objects.
Here's an example use:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
final int[] source = IntStream.range(0, 10).toArray()
System.out.println(Arrays.toString(source));
final int[] result = Arrays.copyOfRange(source, 3, 8);
System.out.println(Arrays.toString(result));
}
}
Which prints:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[3, 4, 5, 6, 7]
For more information, see the docs
I think it's easiest to achieve such semantics by streaming the array:
SomeClass[] sourceArray = /* something */;
SomeClass[] result =
Arrays.stream(sourceArray).skip(10L).limit(16L).toArray(SomeClass[]::new);

Write a program that determines if two groups of numbers can be formed in such a way that their sums are equal

Example:
Input: 3, 6, 3
Output: True (since 3 + 3 = 6)
Input: 3, 2, 6, 4
Output: False (since no combination will result in equality)
Input: 4, 7, 3, 6
Output: True (since 4 + 6 = 7 + 3)
can you guys give me an idea on how to code this?
i've started on how to code this but i'm confused on how I can add the numbers and compair them
I'll explain how a person could work on this without knowing magic words (like "partition problem", "dynamic programming", etc.) with which to consult some big book of answers (like Wikipedia).
If you take one instance of the largest not-yet-used number from the input and assign it to one of your two groups, then you have reduced the problem to a smaller instance of (a generalized version of) the same problem.
The generalized problem is, can you divide the input numbers into two groups such that the difference between the two groups' sums is a particular non-negative integer?
Let's say our input numbers are 4, 3, 2, 1 and we need to make two groups so that the difference between the groups' sums is 0.
We assign 4 to one of the groups, and in this particular case it doesn't matter which group.
Now our remaining input numbers are 3, 2, 1 and, ignoring the 4 that we already dealt with, we need to make these three numbers into two groups so that the difference between the groups' sums is 4. (That will balance out the difference between the two groups that we created by assigning the 4 to one of the groups.) As promised, this is a smaller instance of the original type of problem.
The difficulty is that sometimes, such as with 5, 5, 4, 3, 3 (example found in Wikipedia "Partition problem"), it's not obvious which group the next number needs to go into. If you keep track of what you've done, then when you find out your latest attempt didn't work, you can come back ("backtrack") and try the other way.
5, 5, 4, 3, 3 {} {}
5, 4, 3, 3 {5} {}
4, 3, 3 {5} {5}
3, 3 {5, 4} {5}
3 {5, 4} {5, 3}
{5, 4} {5, 3, 3} NO - backtrack
{5, 4, 3} {5, 3} NO - backtrack
3 {5, 4, 3} {5}
{5, 4, 3} {5, 3} NO - already tried - backtrack
{5, 4, 3, 3} {3} NO - backtrack
3, 3 {5} {5, 4} NO - symmetric to what we already tried - backtrack
4, 3, 3 {5, 5} {}
3, 3 {5, 5} {4}
3 {5, 5} {4, 3}
{5, 5} {4, 3, 3} YES
Will we be able to get the answer quickly? Well, this isn't the question that was asked, but in light of the complexity of backtracking, it's natural to ask. And the answer turns out to be, no, not even if we have the smartest person in the history of the world working for us. No one has ever found a method that is guaranteed to perform quickly no matter what instance of this kind of problem we give it. Maybe we can do pretty well for many instances of these problems, but in general and on average, a program to do this sort of thing is destined to be slow.
This is the partition problem, which is NP-complete. Despite that, there's a dynamic programming solution that you can use. See the Wikipedia article.
http://en.wikipedia.org/wiki/Partition_problem
public class Weirdie {
private boolean calculate(int[] array) {
boolean match = false;
List<Integer> list = new ArrayList<Integer>();
int length = array.length;
for(int i=0;i<length;i++) {
for(int j=i+1;j<length;j++) {
int sum = array[i] + array[j];
if(list.contains(sum)) {
match = true;
break;
} else {
list.add(sum);
}
}
if(match) {
break;
}
}
return match;
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] array = { 3, 6, 3, 4, 8};
int[] array2 = { 3, 2, 6, 4};
int[] array3 = { 4, 7, 3, 6 };
Weirdie w = new Weirdie();
System.out.println(w.calculate(array));
System.out.println(w.calculate(array2));
System.out.println(w.calculate(array3));
}
}
Actually I still confusing with your requirement.As your description,number group 1 {3,6,3} will output true because of 3+3=6.And you said number group 2 {3,2,6,4} will output false,but appearently 2+4=6 is also match your condition.With your third number group,I think the reason why number group 1 output true is 3+6=6+3.
To determine is a array can be divided into two equal summed arrays, we can also find a subset which has half the sum of the whole array.
For e.g: Input: 4, 7, 3, 6
We should find a sub set whose sum == 10, which is a simple DP prob.
public static boolean isSubset(int[] a, int sum, int n) {
if(sum == 0)
return true;
if(n<0)
return false;
return isSubset(a, sum-a[n], n-1) || isSubset(a, sum, n-1);
}
OK! just use brute force calculation, my checking every possible option
int[] numbersArray = new int[10];
int sum = 0;
for(int j = 0; j < numbersArray.lenght;j++) // sum
sum += numbersArray[j];
for(int i = 0; i < numbersArray.lenght;i++)
{
int numChecking = numbersArray[i]; // right half ..
if((sum-numChecking) == numChecking)
return true;
}
return false;
// i haven't tested it but, this will check all possibility's for 1 value..

Print multi-dimensional array using foreach [duplicate]

This question already has answers here:
The best way to print a Java 2D array? [closed]
(14 answers)
Closed 6 years ago.
How to print multi-dimensional array using for-each loop in java? I tried, foreach works for normal array but not work in multi-dimensional array, how can I do that? My code is:
class Test
{
public static void main(String[] args)
{
int[][] array1 = {{1, 2, 3, 4}, {5, 6, 7, 8}};
for(int[] val: array1)
{
System.out.print(val);
}
}
}
Your loop will print each of the sub-arrays, by printing their address. Given that inner array, use an inner loop:
for(int[] arr2: array1)
{
for(int val: arr2)
System.out.print(val);
}
Arrays don't have a String representation that would, e.g. print all the elements. You need to print them explicitly:
int oneD[] = new int[5];
oneD[0] = 7;
// ...
System.out.println(oneD);
The output is an address:
[I#148cc8c
However, the libs do supply the method deepToString for this purpose, so this may also suit your purposes:
System.out.println(Arrays.deepToString(array1));
If you just want to print the data contained in the int array to a log, you can use
Arrays.deepToString
which does not use any for loops.
Working Code.
import java.util.*;
public class Main
{
public static void main(String[] args)
{
int[][] array = {{1, 2, 3, 4}, {5, 6, 7, 8}};
System.out.println(Arrays.deepToString(array));
}
}
Output
[[1, 2, 3, 4], [5, 6, 7, 8]]
This is a very general approach that works in most languages. You will have to use nested loops. The outer loop accesses the rows of the array, while the inner loop accesses the elements within that row. Then, just print it out and start a new line for every row (or choose whatever format you want it to be printed in).
for (int[] arr : array1) {
for (int v : arr) {
System.out.print(" " + v);
}
System.out.println();
}
The current output would look something like:
[I#1e63e3d
...
which shows the string representation for an integer array.
You could use Arrays.toString to display the array content:
for (int[] val : array1) {
System.out.println(Arrays.toString(val));
}

How to use java.util.Arrays

I'm trying to use the java.util.Arrays class in JavaSE 6 but not sure how i would implement it? on an array that I have generated?
before the start of the class i have
import java.util.Arrays
Java Arrays
To declare an array of integers, you start with:
int[] myArray;
To instantiate an array of ten integers, you can try:
myArray = new int[10];
To set values in that array, try:
myArray[0] = 1; // arrays indices are 0 based in Java
Or at instantiation:
int[] myArray2 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
To get values from the array, try:
System.out.println(myArray[0]);
To print all the values in an array, try:
// go from 0 to one less than the array length, based on 0 indexing
for(int i = 0; i < myArray2.length; i++) {
System.out.println(myArray2[i]);
}
For more information, the tutorial from Sun/Oracle will be of great help. You can also check out the Java language specification on Arrays.
Using the Arrays Utility Class
java.util.Arrays contains a bunch of static methods. Static methods belong to the class and do not require an instance of the class in order to be called. Instead they are called with the class name as a prefix.
So you can do things like the following:
// print a string representation of an array
int[] myArray = {1, 2, 3, 4};
System.out.println(Arrays.toString(myArray));
Or
// sort a list
int[] unsorted = {3, 4, 1, 2, 5, 7, 6};
Arrays.sort(unsorted);
Well let's say you have an array
int[] myArray = new int[] { 3, 4, 6, 8, 2, 1, 9};
And you want to sort it. You do this:
// assumes you imported at the top
Arrays.sort(myArray);
Here's the whole shebang:
import java.util.Arrays;
class ArrayTest {
public static void main(String[] args) {
int[] myArray = new int[] { 3, 4, 6, 8, 2, 1, 9};
Arrays.sort(myArray);
System.out.println(Arrays.toString(myArray));
}
}
And that results in
C:\Documents and Settings\glow\My Documents>java ArrayTest
[1, 2, 3, 4, 6, 8, 9]
C:\Documents and Settings\glow\My Documents>
You have not provided enough information about what you are trying to do. java.util.Arrays only exposes static methods, so you simply pass in your array and whatever other params are necessary for the particular method you are calling. For instance Arrays.fill(myarray,true) would fill a boolean array with the value true.
Here is the javadoc for java.util.Arrays
You can use a static import
import static java.util.Arrays.*;
int[] ints = {3, 4, 1, 2, 5, 7, 6};
sort(ints);
public static void main(String[] args) {
double array[] = {1.1,2.3,5.6,7.5, 12.2, 44.7,4.25, 2.12};
Arrays.sort(array,1,3);
for(int i =0;i <array.length;i++){
System.out.println(array[i]);
}
}
result:
"1.1,2.3,5.6,7.5,12.2,44.7,4.25,2.12"

Categories