This question already has answers here:
How do I declare and initialize an array in Java?
(31 answers)
Closed 2 years ago.
I'm pretty new to Java arrays and I'm having trouble creating and changing an array as such:
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] arr = new int[4];
int num = sc.nextInt();
if (num % 2 == 0) {
arr = {2, 4, 6, 8};
}
else {
arr = {1, 3, 5, 7};
}
for (int i:arr) {
System.out.print(i + ", ");
}
}
For some reason, it gives me these errors:
test.java:8: error: illegal start of expression
arr = {2, 4, 6, 8};
^
test.java:8: error: not a statement
arr = {2, 4, 6, 8};
^
test.java:8: error: ';' expected
arr = {2, 4, 6, 8};
^
test.java:11: error: illegal start of expression
arr = {1, 3, 5, 7};
^
test.java:11: error: not a statement
arr = {1, 3, 5, 7};
^
test.java:11: error: ';' expected
arr = {1, 3, 5, 7};
^
6 errors
I've tried replacing 'int[] arr = new int[4];' with just 'int[] arr;', and to remove the statement and using int[] before 'arr' in the if/else blocks, that doesn't work either.
What is causing these errors, and is there a way to work around them?
You can only assigned like that to an array during its initialization, try this instead:
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] arr;
int num = sc.nextInt();
if (num % 2 == 0) {
arr = new int[] {2, 4, 6, 8};
}
else {
arr = new int[] {1, 3, 5, 7};
}
for (int i:arr) {
System.out.print(i + ", ");
}
}
Unrelated, but you can simplified your code into :
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int[] arr = (num % 2 == 0) ? new int[]{2, 4, 6, 8} : new int[] {1, 3, 5, 7};
Arrays.stream(arr).forEach(i -> System.out.print(i + ", "));
}
}
Try this:
Scanner sc = new Scanner(System.in);
int[] arr;
int num = sc.nextInt();
if (num % 2 == 0) {
arr = new int[]{2, 4, 6, 8};
} else {
arr = new int[]{1, 3, 5, 7};
}
for (int i:arr) {
System.out.print(i + ", ");
}
Related
I am a bit confused and I would need some clarification. Not too sure if I'm on the right track, hence this thread.
Here is my code that I want to decipher into advanced foreach loop.
int[] arrayA = {3, 35, 2, 1, 45, 92, 83, 114};
int[] arrayB = {4, 83, 5, 9, 114, 3, 7, 1};
int n = arrayA.length;
int m = arrayB.length;
int[] arrayC = new int[n + m];
int k = 0;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
if(arrayB[j] == arrayA[i])
{
arrayC[k++] = arrayA[i];
}
}
}
for(int i=0; i<l;i++)
System.out.print(arrayC[i] + " ");
System.out.println();
So far this is the point where I am stuck at:
int[] a = {3, 8, 2, 4, 5, 1, 6};
int[] b = {4, 7, 9, 8, 2};
int[] c = new int[a.length + b.length];
int k = 0;
for(int i : a)
{
for(int j : b)
{
if(a[i] == b[j])
{
c[k++] = a[i];
}
}
//System.out.println(c[i]);
}
for(int i=0; i<c.length;i++)
System.out.print(c[i] + " ");
System.out.println();
}
You are almost there
for(int i : a)
{
for(int j : b)
{
if(i == j)
{
c[k++] = i;
}
}
}
With for(int i : a) access the elements in the array a using i.
If a is {3, 8, 2, 4, 5, 1, 6}, then i would be 3,8,2,.. on each iteration and you shouldn't use that to index into the original array. If you do, you would get either a wrong number or a ArrayIndexOutOfBoundsException
Since you want to pick the numbers that are present in both the arrays, the length of array c can be max(a.length, b.length). So, int[] c = new int[Math.max(a.length, b.length)]; will suffice.
If you want to truncate the 0s at the end, you can do
c = Arrays.copyOf(c, k);
This will return a new array containing only the first k elements of c.
I would use a List and retainAll. And in Java 8+ you can make an int[] into a List<Integer> with something like,
int[] arrayA = { 3, 35, 2, 1, 45, 92, 83, 114 };
int[] arrayB = { 4, 83, 5, 9, 114, 3, 7, 1 };
List<Integer> al = Arrays.stream(arrayA).boxed().collect(Collectors.toList());
al.retainAll(Arrays.stream(arrayB).boxed().collect(Collectors.toList()));
System.out.println(al.stream().map(String::valueOf).collect(Collectors.joining(" ")));
Outputs
3 1 83 114
Alternatively, if you don't actually need the values besides displaying them, and you want to use the for-each loop (and less efficiently) like
int[] arrayA = { 3, 35, 2, 1, 45, 92, 83, 114 };
int[] arrayB = { 4, 83, 5, 9, 114, 3, 7, 1 };
for (int i : arrayA) {
for (int j : arrayB) {
if (i == j) {
System.out.print(i + " ");
}
}
}
System.out.println();
Temporary variables aren't indices in an array in foreach Loop. So in 0th iteration, i contains the 0th element of a, j contains the 0th element in b. Your attempt should be like this:
int[] a = {3, 8, 2, 4, 5, 1, 6};
int[] b = {4, 7, 9, 8, 2};
int[] c = new int[a.length + b.length];
int k = 0;
for(int i : a) {
for(int j : b) {
if(i == j) {
c[k++] = i;
}
} //System.out.println(c[i]);
}
Please note your c[] array will contain the order maintained in a[].
I need to find a way to remove duplicates from a combination like this:
Input: 3 and 2, where 3 is the range (from 1 to 3) and 2 is the length of each combination
Output: {1, 1} {1, 2} {1, 3} {2, 1} {2, 2} {2, 3} {3, 1} {3, 2} {3, 3}
Expected output: {1, 1} {1, 2} {1, 3} {2, 2} {2, 3} {3, 3}
So we start with {1, 1} -> {1, 2} -> {1, 3} -> but {2, 1} is a duplicate of {1, 2} so we ignore it and so on.
Here's my code:
import java.util.Scanner;
public class Main {
private static int[] result;
private static int n;
private static void printArray() {
String str = "( ";
for (int number : result) {
str += number + " ";
}
System.out.print(str + ") ");
}
private static void gen(int index) {
if (index == result.length) {
printArray();
return;
}
for (int i = 1; i <= n; i++) {
result[index] = i;
gen(index + 1);
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("From 1 to: ");
n = input.nextInt();
System.out.print("Length: ");
int k = input.nextInt();
result = new int[k];
gen(0);
}
}
You can pass the last max value used into gen:
private static void gen(int index, int minI) {
if (index == result.length) {
printArray();
return;
}
for (int i = minI; i <= n; i++) {
result[index] = i;
gen(index + 1, i);
}
}
And call it starting with 1: gen(0, 1);
I'm new to Java. I would like to get the index of the last occurrence in an array using loop. However, I don't understand why I can't.
This is the array:
{2, 3, 4, 5, 4, 5, 3}
I would like to get the index of the last 4 in it.
My code is:
public static void main(String args[]){
int[] nums = {2, 3, 4, 5, 4, 5, 3};
int pos4 = 0;
for (int k = nums.length -1; k >= 0; k--){
if (nums[k] == 4){
pos4 = k;
break;
}
System.out.print(pos4);
}
}
The result is: 00 ??
When I change to:
public static void main(String args[]){
int[] nums = {2, 3, 4, 5, 4, 5, 3};
int pos4 = 0;
for (int k = nums.length -1; k >= 0; k--){
if (nums[k] == 4){
break;
}
System.out.print(k);
}
}
I got 65 ???
However, when I print directly from the loop I get the index correctly:
public static void main(String args[]){
int[] nums = {2, 3, 4, 5, 4, 5, 3};
int pos4 = 0;
for (int k = nums.length -1; k >= 0; k--){
if (nums[k] == 4){
System.out.print(k);
break;
}
}
}
Can anyone tell me why? Thanks a lot!
Your first example is printing from within the loop. Once the condition was met you exited the loop and never printed out the final value.
public static void main(String args[]){
int[] nums = {2, 3, 4, 5, 4, 5, 3};
int pos4 = 0;
for (int k = nums.length -1; k >= 0; k--) {
if (nums[k] == 4){
pos4 = k;
break;
}
}
System.out.print(pos4); // moved outside of loop to print final value
}
How about using existing methods, and not reinventing the wheel? this one-liner solves the problem:
Integer[] array = { 2, 3, 4, 5, 4, 5, 3 };
int idx = Arrays.asList(array).lastIndexOf(4);
Your print statement is inside the loop. So it prints 0 twice, then when the result is found the break; skips over it. Try this...
int pos4 = 0;
for (int k = nums.length - 1; k >= 0; k--) {
if (nums[k] == 4) {
pos4 = k;
break;
}
}
System.out.print(pos4); // <== after loop
The question is Define a cluster in an integer array to be a maximum sequence of elements that are all the same value. For example, in the array {3, 3, 3, 4, 4, 3, 2, 2, 2, 2, 4} there are 5 clusters, {3, 3, 3}, {4, 4}, {3}, {2, 2, 2, 2} and {4}. A cluster-compression of an array replaces each cluster with the number that is repeated in the cluster. So, the cluster compression of the previous array would be {3, 4, 3, 2, 4}. The first cluster {3, 3, 3} is replaced by a single 3, and so on.
public static void main(String[] args) {
int[] givenArray = {1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1};
System.out.println("Clustered Array = " + Arrays.toString(isTrivalent(givenArray)));
}
public static int[] isTrivalent (int[] a){
List<Integer> cluster = new ArrayList<Integer>();
for (int i=0; i<a.length ; i++ ) {
if(i == 0){
cluster.add(a[i]);
}else{
if(cluster.get(i-1) != a[i]) cluster.add(a[i]);
}
}
int[] arr = new int[cluster.size()];
for (int j =0; j<cluster.size() ; j++) {
arr[j] = cluster.get(j);
}
return arr;
}
But I am getting an ArrayOutOfBoundException. What am I doing wrong?
Change
if(cluster.get(i-1) != a[i]) cluster.add(a[i]);
to
if(a[i-1] != a[i]) cluster.add(a[i]);
cluster.get(i-1) may not exist.
This is happening because when you check
if(cluster.get(i-1) != a[i])
it is not necessary that the cluster arraylist will actually have size of atleast i-1 since you are skipping a lot of array elements. You need to change your condition to
if(cluster.get(cluster.size()-1) != a[i])
or equivalently (as suggested in previous answer)
if(a[i-1] != a[i])
for this code to work as intended.
public static void main(String[] args) {
int[] givenArray = {1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1};
System.out.println("Clustered Array = " + Arrays.toString(isTrivalent(givenArray)));
}
public static int[] isTrivalent(int[] a) {
List<Integer> cluster = new ArrayList<Integer>();
for (int i = 0; i < a.length; i++) {
if (i == 0) {
cluster.add(a[i]);
} else {
if (cluster.get(cluster.size() - 1) != a[i]) {
cluster.add(a[i]);
}
}
}
int[] arr = new int[cluster.size()];
for (int j = 0; j < cluster.size(); j++) {
arr[j] = cluster.get(j);
}
return arr;
}
I'm working on a problem in Java to find all possible combinations given an arbitrary starting array, by decrementing the values one at a time of each item in the array until the value 1 is reached at each index.
I've started on the below test case but haven't got very far.
I would like some help in solving my problem please.
import org.junit.Assert;
import org.junit.Test;
public class ComboTest
{
#Test
public void test()
{
int[][] answers = {
{4, 3, 2}, {3, 3, 2}, {2, 3, 2}, {1, 3, 2},
{4, 2, 2}, {3, 2, 2}, {2, 2, 2}, {1, 2, 2},
{4, 1, 2}, {3, 1, 2}, {2, 1, 2}, {1, 1, 2},
{4, 3, 1}, {3, 3, 1}, {2, 3, 1}, {1, 3, 1},
{4, 2, 1}, {3, 2, 1}, {2, 2, 1}, {1, 2, 1},
{4, 1, 1}, {3, 1, 1}, {2, 1, 1}, {1, 1, 1},
};
int[] start = {4, 3, 2};
int dim = 1;
for (int i = 0; i < start.length; i++)
{
dim *= start[i];
}
int[][] combos = new int[dim][start.length];
for (int i = 0; i < combos[0].length; i++)
{
combos[0][i] = start[i];
}
for (int i = 1; i < combos.length; i++)
{
for (int j = 0; j < combos[i].length; j++)
{
int k = combos[i - 1][j] - 1;
if (k < 1)
{
k = start[j];
}
combos[i][j] = k;
}
}
for (int i = 0; i < combos.length; i++)
{
for (int j = 0; j < combos[i].length; j++)
{
Assert.assertEquals(answers[i][j], combos[i][j]);
}
}
}
}
This is a simple state search problem. You have a starting state, and you can expand it (create its children) following some criteria. In your case, by decrementing one of the values, but not below some lower bound.
If you're not familiar with DFS or BFS, I suggest reading on those. In the meantime, here's the code (perhaps the solution is not in the format you're expecting, but you can work on it :D):
public class ComboTest {
public static class Combo {
private Integer[] values;
public Combo(Integer[] values) {
this.values = values;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(values);
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Combo)) {
return false;
}
Combo other = (Combo) obj;
if (!Arrays.equals(values, other.values)) {
return false;
}
return true;
}
#Override
public String toString() {
return Arrays.toString(values);
}
}
public static Set<Combo> combos(Combo start, int lowerBound) {
Set<Combo> answers = new HashSet<Combo>();
compute(start, lowerBound, answers);
return answers;
}
private static void compute(Combo start, int lowerBound, Set<Combo> answers) {
Deque<Combo> dfsStack = new ArrayDeque<Combo>();
dfsStack.push(start);
while (!dfsStack.isEmpty()) {
Combo current = dfsStack.pop();
answers.add(current);
for (Combo next : expand(current, lowerBound)) {
if (!answers.contains(next)) {
dfsStack.push(next);
}
}
}
}
private static List<Combo> expand(Combo current, int lowerBound) {
List<Combo> nexts = new ArrayList<Combo>();
for (int i = 0; i < current.values.length; i++) {
if (current.values[i] > lowerBound) {
Integer[] copyCurrent = Arrays.copyOf(current.values, current.values.length);
copyCurrent[i]--;
nexts.add(new Combo(copyCurrent));
}
}
return nexts;
}
public static void main(String[] args) {
Combo start = new Combo(new Integer[] { 4, 3, 2 });
Set<Combo> combos = combos(start, 1);
for (Combo combo : combos) {
System.out.println(combo);
}
System.out.println(combos.size());
}
}
Output:
[4, 3, 1]
[2, 1, 1]
[3, 2, 1]
[1, 1, 2]
[2, 2, 2]
[3, 3, 2]
[4, 3, 2]
[4, 2, 1]
[3, 1, 1]
[2, 1, 2]
[3, 2, 2]
[4, 1, 1]
[4, 2, 2]
[3, 1, 2]
[4, 1, 2]
[1, 3, 1]
[1, 2, 1]
[2, 3, 1]
[1, 3, 2]
[1, 1, 1]
[2, 2, 1]
[3, 3, 1]
[1, 2, 2]
[2, 3, 2]
24
you Seaching all permutation of an Array with n elements so this is Already asked here
Permutation algorithm for array of integers in Java
This is not my Answer im Only Refering to it
static ArrayList<int[]> permutations(int[] a) {
ArrayList<int[]> ret = new ArrayList<int[]>();
permutation(a, 0, ret);
return ret;
}
public static void permutation(int[] arr, int pos, ArrayList<int[]> list){
if(arr.length - pos == 1)
list.add(arr.clone());
else
for(int i = pos; i < arr.length; i++){
swap(arr, pos, i);
permutation(arr, pos+1, list);
swap(arr, pos, i);
}
}
public static void swap(int[] arr, int pos1, int pos2){
int h = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = h;
}
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class New{
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("ENTER THE ARRAY SIZE");
int n=in.nextInt();
System.out.println("ENTER THE ARRAY VALUES");
int[] a=new int[n];
String s="";
for(int i=0;i<n;i++)
{
a[i]=in.nextInt();
s=s+(char)a[i];
}
List<String> hs=mac(s);
System.out.println("THE COMBINATIONS ARE");
for(String str:hs)
{
char[] ch=str.toCharArray();
for(int i=0;i<ch.length;i++)
{
System.out.print((int)ch[i]);
}
System.out.println();
}
}
public static List<String> mac(String s)
{
List<String> ss=new ArrayList<String>();
if(s==null)
{
return null;
}
else if(s.length()==0)
{
ss.add("");
}
else
{
String str=s.substring(1);
char c=s.charAt(0);
List<String> hs=mac(str);
for(String st:hs)
{
for(int i=0;i<=st.length();i++)
{
ss.add(sru(st,c,i));
}
}
}
return ss;
}
public static String sru(String s,char c,int i)
{
String start=s.substring(0,i);
String end=s.substring(i);
return start+c+end;
}
}
Easier method:
There's a library called Google Guava, that will do this thing for you.
You can find it here: https://github.com/google/guava
Idk if this code fits for you but anyway here's the code. Hope it helps :) ...
Collection<List<String>> permutations = null;
String[] foo = //your array in here
permutations = Collections2.permutations(Lists.newArrayList(foo));
//use for each loop to read
for (List<String> permutation : permutations) {
//Output here
}