My code is not Compiling - java

I have the following code, but is not compiling, any suggestions? It keeps giving an error on line 11.
import java.util.ArrayList;
public class ListArray {
public static ArrayList<Integer> getList(int a, int b, int[] array){
ArrayList<Integer> list = new ArrayList<Integer>();
if(a == b){
list = null;
}
if(a > b){
list = null;
}
for(int i = a; i <= b - 1; i++){
list =(i + 1);
}
return list;
}
}

From what I can tell you are trying to create a method which will create an
ArrayList<Integer> which is populated with the integers between a+1 and b ( as you have i+1 with i starting at a and ending at b-1, which shifts your values to a+1-b)
You are attempting to assign your ArrayList list to an int value, which is not allowed. I believe you meant to add each value instead.
You should use the add method from ArrayList
import java.util.ArrayList;
public class ListArray {
public static ArrayList<Integer> getList(int a, int b, int[] array){
ArrayList<Integer> list = new ArrayList<Integer>();
if(a == b){
list = null;
}
if(a > b){
list = null;
}
for(int i = a; i <= b - 1; i++){
list.add(i + 1);
}
return list;
}
}

You cannot assign an int to an ArrayList-typed variable, which you actually do at line list =(i+1);.
The compilation error message should be clear enough. What is it saying?

Related

Can't figure out how to return an array

Find all pairs with a given sum
Given two unsorted arrays A of size N and B of size M of distinct elements, the task is to find all pairs from both arrays whose sum is equal to X.
Code:
import java.util.*;
import java.lang.*;
import java.io.*;
class pair {
long first, second;
public pair(long first, long second)
{
this.first = first;
this.second = second;
}
}
class GFG {
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine().trim());
while(t-->0)
{
StringTokenizer stt = new StringTokenizer(br.readLine());
long N = Long.parseLong(stt.nextToken());
long M = Long.parseLong(stt.nextToken());
long X = Long.parseLong(stt.nextToken());
long A[] = new long[(int)(N)];
long B[] = new long[(int)(M)];
String inputLine[] = br.readLine().trim().split(" ");
for (int i = 0; i < N; i++) {
A[i] = Long.parseLong(inputLine[i]);
}
String inputLine1[] = br.readLine().trim().split(" ");
for (int i = 0; i < M; i++) {
B[i] = Long.parseLong(inputLine1[i]);
}
Solution obj = new Solution();
pair [] answer = obj.allPairs(A, B, N, M, X);
int sz = answer.length;
if(sz==0)
System.out.println(-1);
else{
StringBuilder output = new StringBuilder();
for(int i=0;i<sz;i++){
if(i<sz-1)
output.append(answer[i].first +" "+ answer[i].second + ", ");
else
output.append(answer[i].first +" "+ answer[i].second);
}
System.out.println(output);
}
}
}
}
// } Driver Code Ends
//User function Template for Java
/*
class pair {
long first, second;
public pair(long first, long second)
{
this.first = first;
this.second = second;
}
}
*/
class Solution {
public pair[] allPairs( long A[], long B[], long N, long M, long X) {
//MY CODE STARTS FROM HERE
ArrayList<Long> list = new ArrayList<>();
HashSet<Long> set = new HashSet<>();
for(long i : A){
set.add(i);
}
for(int i=0;i<M;i++){
if(set.contains(X-B[i])){
list.add(X-B[i]);
list.add(B[i]);
}
}
long arr[] = new long[list.size()];
for(int i=0;i<arr.length;i++){
arr[i] = list.get(i);
}
return arr;
}
}
I am getting this error:
prog.java:101: error: incompatible types: long[] cannot be converted to pair[]
return arr;
^
1 error
How can I correctly return the answer?
Before I get into the answer, it is very important to use descriptive variable names when writing your code. They might make sense to you, but people like me who aren't you, and possible even you in the future, have a hard time understanding what A, B, M, N, etc mean.
The reason you are getting this error is because your function allPairs() has a return type of pair[], but you're trying to return long[]. It's a bit hard to understand what you're trying to do because of your variable names, but it seems like when you find a result that you desire you are adding the first and second results separately into an array of longs, which also undermines the point of your pair class. Here's an idea of what it should probably look like instead:
class Solution {
public pair[] allPairs( long A[], long B[], long N, long M, long X) {
//MY CODE STARTS FROM HERE
ArrayList<pair> list = new ArrayList<>();
HashSet<Long> set = new HashSet<>();
for(long i : A){
set.add(i);
}
for(int i=0;i<M;i++){
if(set.contains(X-B[i])){
list.add(new pair(X-B[i], B[i]));
}
}
pair arr[] = new pair[list.size()];
arr = list.toArray(arr);
return list.toArray();
}
}
in your define method return type is pairs, but actually return a long[], it must be compile error
you should modify the Solution as follow
class Solution {
public pair[] allPairs( long A[], long B[], long N, long M, long X) {
//MY CODE STARTS FROM HERE
ArrayList<Long> list = new ArrayList<>();
HashSet<Long> set = new HashSet<>();
for(long i : A){
set.add(i);
}
for(int i=0;i<M;i++){
if(set.contains(X-B[i])){
list.add(X-B[i]);
list.add(B[i]);
}
}
pair arr[] = new pair[list.size()];
for(int i=0;i<arr.length;i++){
arr[i]=new pair(X-B[i], B[i]);
}
return arr;
}
}

From a linked list to an array (Function)

I'm trying to give a function a list and make an array which contains the value of the nodes of the list (Not complicated). There it is:
public class MainClass {
public static int[] makeListIntoArray(Node<Integer> n) {
int[] arr1 = new int [countSizeOfList(n)];
for(int i = 0; i < countSizeOfList(n); i++) {
arr1[i] = n.getValue();
n = n.getNext();
}
return arr1;
}//EndOfFunction
public static int[] finalFunction2(Node<Integer> n) {
if(n == null) return ifListIsEmpty(n);
return makeListIntoArray(n);
}
public static int[] ifListIsEmpty(Node<Integer> n) {
Node<Integer> n2 = new Node<Integer>(999);
int[] arr1 = new int [countSizeOfList(n2)];
int i = 0;
arr1[i] = n2.getValue();
return arr1;
}
public static void main(String[] args) {
Node<Integer> n1 = new Node<Integer>(5);
Node<Integer> n2 = new Node<Integer>(4);
Node<Integer> n3 = new Node<Integer>(3);
Node<Integer> n4 = new Node<Integer>(5);
Node<Integer> n5 = new Node<Integer>(1);
n1.setNext(n2);
n2.setNext(n3);
n3.setNext(n4);
n4.setNext(n5);
System.out.println(finalFunction2(n1));
}//Main
}//Class
Thing is that it prints "[I#7960847b" beside of the actual array... fixes?
Any fixes?
If you want to insert a value into array then there should be an index especially a static one. You cannot simply assign it to arr1 like your do for primitive types.
For example, arr1[0] = n.getValue() is valid but not arr1 = n.getValue();
public static int[] makeListIntoArray(Node<Integer> n) {
int[] arr1 = new int [countSizeOfList(n)];
int idx=0;
while(n != null) {
arr1[idx++] = n.getValue();
n = n.getNext();
}
return arr1;
}//EndOfFunction
If you're using Java's built-in LinkedList data structure you can simply use the following to convert from LinkedList to array:
Integer[] array = list.toArray(new Integer[list.size()]);
So for the situation you're describing all you would need for the function is:
import java.util.LinkedList;
public class MainClass {
public static int[] makeListIntoArray(LinkedList<Integer> list) {
Integer[] arr = list.toArray(new Integer[list.size()]);
int[] intArr = Arrays.stream(array).mapToInt(Integer::intValue).toArray();
// Above line converts the wrapper Integer[] to int[] if you need that
return intArr;
}
}
You can find more info about LinkedList's toArray() method here.
If you want to keep the linked list but also want to access the elements in O(1), you can create an array of Nodes.
public class MainClass {
public static Node<Integer>[] makeListIntoArray(Node<Integer> n) {
Node<Integer>[] arr1 = new Node<Integer> [countSizeOfList(n)];
int i=0;
while(n != null) {
arr1[i] = n;
n = n.getNext();
++i;
}
return arr1;
}//EndOfFunction
}//Class

Why is my Java function returning null?

class Solution {
Map<List<Integer>, Integer> map = new HashMap<>();
List<List<Integer>> ret = new ArrayList<>();//Created An ArrayList
public void dfs(int index, int target, List<Integer> choosen, int[] nums)
{
if(choosen.size()==3 && target==0 && !map.containsKey(choosen)){
ret.add(choosen);
map.put(choosen,0);
for(int j=0;j<list.size();j++)
System.out.print(list.get(j)+" ");
System.out.println();
//map.put(choosen,0);
return;
}
for(int i=index;i<nums.length;i++)
{
int x = nums[i];
choosen.add(x);
target-=x;
dfs(i+1,target,choosen,nums);
target+=nums[i];
choosen.remove(choosen.size()-1);
}
}
public List<List<Integer>> threeSum(int[] nums) {
List<Integer> choosen = new ArrayList<>();
Arrays.sort(nums);
dfs(0,0,choosen,nums);
return ret; //Returning Null
}
}
Why am i not able to add in "ret"? It's returning null.
I just want to add my choosen list into ret when the condition is true and return ret List.
I think the problem is that the if statement is checked before 'choosen' value change (when it is empty).
Try to have the if statement inside the for loop.

Missing Return Statement in Java Recursive Function

I'm trying to generate a list of 25 non-repeating random numbers in Java, and I keep getting the Missing Return Statement error. As can be seen, I tried putting return before calling the method within itself. Not sure what's missing. It also didn't work with just the return (rando)
import java.util.*;
public class arrayList{
ArrayList<Integer> checkRandom;
ArrayList<Integer> array4;
ArrayList<Integer> array2;
ArrayList<Integer> array3;
public int addRandom(){
Random rnd = new Random();
int b=0;
for (int i=0; i<26; i++){
int rando = rnd.nextInt(101);
if (checkRandom.indexOf(rando) != -1){
return addRandom();
}
else{
checkRandom.add(rando);
array4.add(rando);
return (rando);
}
}
for (int j=0;j<26;j++){
int right;
right = checkRandom.get(j);
System.out.println(right);
}
return -1;
}
public static void main(String args[]){
arrayList randomGen = new arrayList();
randomGen.addRandom();
}
}
Exception in thread "main" java.lang.NullPointerException
at arrayList.addRandom(arrayList.java:14)
at arrayList.main(arrayList.java:37)
I'd suggest you use a much simpler method using Java 8 streams. For example, to create an array of 26 distinct random integers betweeen 0 and 100:
int[] randomArray = new Random().ints(0, 101).distinct().limit(26).toArray();
To explain in a bit more detail, this statement can be interpreted as: create a random number generator, use it to generate an endless stream of random numbers between 0 and 100, remove any duplicates, get the first 26 numbers in the stream and convert them to an int array.
Streams are incredibly powerful. Once your generator is in this form it's trivial to add a sorted operator or a filter, or to collect them into a List or Map.
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
Random rand = new Random();
while (list.size() < 25) {
int index = rand.nextInt(101);
if (!list.contains(index)) {
list.add(index);
}
}
System.out.println(list);
}
}
Initialize a method local variable b inside your addRandom method and reassign it in your for loop finally return variable b.
public int addRandom(){
Random rnd = new Random();
int b=0;
for (int i=0; i<26; i++){
int rando = rnd.nextInt(101);
if (checkRandom.indexOf(rando) != -1){
b= addRandom();
}
else{
checkRandom.add(rando);
array4.add(rando);
b=rando;
}
}
return b;
}
Your method
public int addRandom(){
Random rnd = new Random();
for (int i=0; i<26; i++){
int rando = rnd.nextInt(101);
if (checkRandom.indexOf(rando) != -1){
return addRandom();
}
else{
checkRandom.add(rando);
array4.add(rando);
return (rando);
}
}
}
does not have a return statement at the end. The method signature states you must return an integer. The compiler does not know that the for statement will be executed until runtime. Thus, you have to handle the case where the for loop is not executed. Since you can tell it will be executed every time, adding a return -1; before the end of the method will solve your problem.
i.e.
public int addRandom(){
Random rnd = new Random();
for (int i=0; i<26; i++){
int rando = rnd.nextInt(101);
if (checkRandom.indexOf(rando) != -1){
return addRandom();
}
else{
checkRandom.add(rando);
array4.add(rando);
return (rando);
}
}
return -1;
}
You can call the method by creating an instance of the class i.e.
arrayList randomGen = new arrayList();
randomGen.addRandom();
Btw, its standard in java to name your classes CamelCased. i.e. ArrayList. Although, you may want to rename it something else so you don't confuse your class with java.util.ArrayList (a popular java class)
If you want use recursion, you don't need loops. for example:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Test {
List<Integer> randomList = new ArrayList<Integer>();
Random rnd = new Random(); // do not create new Random object in each function call.
final static int LIST_SIZE = 25;
public void addRandom(List someList) {
if (randomList.size() < LIST_SIZE) {
int random = rnd.nextInt(101); // LIST_SIZE must be lesser than 101 otherwise you will got infinite recursion.
if (!randomList.contains(random)) {
randomList.add(random);
someList.add(random);
}
addRandom(someList);
}
}
public static void main(String args[]) {
Test test = new Test();
List<Integer> array4 = new ArrayList<Integer>();
test.addRandom(array4);
for (Integer value : array4) {
System.out.println(value);
}
}
}

Problems with calling a member of array of strings

With the help of the community i managed to get this problem solved: How to convert String to the name of the Array?
But now i get 'nullPointerExceptions'. Here is the code i use:
public class IroncladsAdder
{
public static String weaponId = null;
public static String ship = null;
public static String wing = null;
//map code
private static Map<String, List<Integer>> arrays = new HashMap<String, List<Integer>>();
public void Holder(String... names) {
for (String name : names) {
arrays.put(name, new ArrayList<Integer>());
}
}
//adds weapons to fleets and stations
public static void AddWeapons(CargoAPI cargo, String fac, int count, int type) {
String arrayName = null;
int quantity = (int) (Math.random()*5f + count/2) + 1;
if (count == 1) {quantity = 1;}
if (type == 0) {arrayName = fac+"_mil_weps";}
else if (type == 1) {arrayName = fac+"_civ_weps";}
else {arrayName = fac+"_tech_weps";}
List<Integer> array = arrays.get(arrayName);
for (int j = 0; j <= count; j++)
{
weaponId = valueOf(arrays.get(arrayName).get((int) (Math.random() * arrays.get(arrayName).size())));
cargo.addWeapons(weaponId, quantity);
}
}
Here is an example of the array:
//high-tech UIN weapons
private static String [] uin_tech_weps =
{
"med-en-uin-partpulse",
"lrg-en-uin-partacc",
"med-bal-uin-driver",
"lrg-bal-uin-terminator",
"lrg-bal-uin-hvydriver",
"lrg-bal-uin-shotgundriver",
"lrg-en-uin-empbeam",
};
Error indicates that something is wrong with this construction:
weaponId = valueOf(arrays.get(arrayName).get((int) (Math.random() * arrays.get(arrayName).size())));
NOTE: i`m using Intellij IDEA and Java 6. Application most of the time has advices/fixes for some errors and in this case shows that everything is ok.
What i need is to get a String out of the specific array (that is using a code-generated name) and assign it to 'weaponId'.
When your application start the map with the arrays is empty, then when you try to get the array with name X you get back a null value.
First solution: at startup/construction time fill the map with empty arrays/List for all the arrays names.
Second solution: use this method in order to obtain the array.
protected List<Integer> getArray(String arrayName) {
List<Integer> array = map.get(arrayName);
if (array == null) {
array = new ArrayList<Integer>();
map.put(arrayName, array);
}
return array;
}
P.s.
You can change this code:
weaponId = valueOf(arrays.get(arrayName).get((int) (Math.random() * arrays.get(arrayName).size())));
into
weaponId = valueOf(array.get((int) (Math.random() * array.size())));
Ok. Now there is a different error - 'java.lang.IndexOutOfBoundsException: Index: 0, Size: 0'
Made the code look like this:
private static Map <String, List<Integer>> arrays = new HashMap<String, List<Integer>>();
public static List<Integer> getArray(String arrayName) {
List<Integer> array = arrays.get(arrayName);
if (array == null) {
array = new ArrayList<Integer>();
arrays.put("rsf_civ_weps", array);
arrays.put("rsf_mil_weps", array);
arrays.put("rsf_tech_weps", array);
arrays.put("isa_civ_weps", array);
arrays.put("isa_mil_weps", array);
arrays.put("isa_tech_weps", array);
arrays.put("uin_mil_weps", array);
arrays.put("uin_tech_weps", array);
arrays.put("uin_civ_weps", array);
arrays.put("xle_civ_weps", array);
arrays.put("xle_mil_weps", array);
arrays.put("xle_tech_weps", array);
}
return array;
}
This is how i now call the array and weaponId:
List<Integer> array = arrays.get(arrayName);
for (int j = 0; j <= count; j++)
{
weaponId = valueOf(array.get((int) (Math.random() * array.size())));
cargo.addWeapons(weaponId, quantity);
}
What`s wrong?

Categories

Resources