I'm trying to create some kind of list to store values from the array 'table'. (I'm using a arraylist here, but should I be using a list instead?) However, every time I try to compile, it throws the following error:
cannot find symbol
symbol : class ArrayList
location: class players.TablePlayer
The code is below.
public class TablePlayer extends Player {
int[][] table;
ArrayList goodMoves;
public TablePlayer(String name) {
super(name);
}
#Override
public int move() {
int oppLast = opponentLastMove();
int myLast = myLastMove();
if (!isLegalMove(oppLast)) {
return 0; // temporary
}
if (wonLast()) {
table[oppLast][myLast] = 1;
table[myLast][oppLast] = -1;
}
if ((wonLast() == false) && (oppLast != myLast)) {
table[oppLast][myLast] = -1;
table[myLast][oppLast] = 1;
}
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table.length; j++) {
if (table[i][j] == 1) {
goodMoves.add(table[i][j]);
}
}
}
return oppLast; // temporary
}
#Override
public void start() {
int[][] table = new int[7][7];
ArrayList<int> goodMoves = new ArrayList<int>();
}
}
Any help would be great, thanks!
Do you have an import statement in the top of the file?
import java.util.ArrayList;
While doing any java program just
import java.util.*;
Because * will import all the packages from util.
And all the basic package are present in that java.util like Scanner, ArrayList, etc...
So to avoid errors first check you have imported that.
Before use a class, you need to import it into you class file definition.
Add it on top of your file:
import java.util.ArrayList;
For more info about imports, look it up here
It is recommended to learn how to use a IDE, like Eclipse, Netbeans. It will help you with these common mistakes when we are programming in Java (in this case) outside a integrated environment.
I am new to the community and on a path of learning now.
But I think the main problem is of int
Wrong
ArrayList <int> goodMoves = new ArrayList <int>();
Right
ArrayList <Integer> goodMoves = new ArrayList <Integer>();
Related
I am new to scala and I need to write a java code that passes an array of scala.collection.immutable.List to a scala function. More specifically, I use a scala function in my java code that needs as an argument a scala.collection.immutable.List<Tuple2<Object, Object>>[]. The objects need to be <Integer, Double>. In java this is quite simple:
java.util.List<Tuple2<Integer, Double>>[] javaList = new ArrayList[335];
for (int i = 0; i < 335; i++) {
javaList[i] = new ArrayList<Tuple2<Integer, Double>>();
}
for(int i=0; i<100;i++)
{
for(int j=0; j<50;j++)
{
javaList[i].add(new Tuple2<Integer, Double>(j, value(j)));
}
}
I need or to convert it from java to scala or to create a scala.collection.immutable.List<Tuple2<Object, Object>>[] and use it directly in my java code, but i have a hard time to find it. I use Java 8, scala 2.12.2 in a maven project.
I can't tell what order of abomination I just committed, but:
class Target {
#annotation.varargs
def f(lists: List[(Int, Double)]*): Int = lists.map(_.map(_._1).sum).sum
}
then
$ javap Target
Compiled from "scalafunc.scala"
public class Target {
public int f(scala.collection.immutable.List<scala.Tuple2<java.lang.Object, java.lang.Object>>...);
public int f(scala.collection.immutable.Seq<scala.collection.immutable.List<scala.Tuple2<java.lang.Object, java.lang.Object>>>);
public static final int $anonfun$f$2(scala.Tuple2);
public static final int $anonfun$f$1(scala.collection.immutable.List);
public Target();
public static final java.lang.Object $anonfun$f$1$adapted(scala.collection.immutable.List);
public static final java.lang.Object $anonfun$f$2$adapted(scala.Tuple2);
}
And interop with Scala 2.13:
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import scala.Tuple2;
import static scala.jdk.javaapi.CollectionConverters.asScala;
public class j {
public static void main(String... args) {
// populate an array list of lists
var javaList = new ArrayList<ArrayList<Tuple2<Integer, Double>>>();
for (int i = 0; i < 335; i++) {
javaList.add(new ArrayList<Tuple2<Integer, Double>>());
}
for(int i=0; i<100;i++) {
for(int j=0; j<50;j++) {
javaList.get(i).add(new Tuple2<Integer, Double>(j, Double.valueOf(j)));
}
}
// convert the elements to scala lists; the result happens to be an arraylist
var arg = (ArrayList<scala.collection.immutable.List<Tuple2<Integer, Double>>>) javaList.stream().map(vs -> asScala(vs).toList()).collect(Collectors.toList());
// we need an array of scala lists
#SuppressWarnings("unchecked")
var template = (scala.collection.immutable.List<Tuple2<Object, Object>>[]) Array.newInstance(scala.collection.immutable.List.class, arg.size());
// extract the target array
var fargs = arg.toArray(template);
Target t = new Target();
// call the varargs f
var res = t.f(fargs);
System.out.println(res);
}
}
and I could
$ scalac scalafunc.scala
$ javac -Xlint -cp .:/home/me/scala-2.13.1/lib/scala-library.jar j.java && java -cp .:/home/me/scala-2.13.1/lib/scala-library.jar j
122500
I didn't verify that result; I'm not entirely confident just because it compiled in Java.
I'm trying to use RandomGrid rGrid in the compareGrids method of my project, however I can't seem to figure out how to do so. I origionally had the RandomGrid constructor outside the main method, but I got a stack overflow error whenever I tried to run it. I have another class very similar to this one with a ButtonGrid constructor outside of the main method and it works fine. Thanks for any help!
public static void main(String[] args) {
new ButtonGrid(WIDTH, LENGTH);
RandomGrid rGrid = new RandomGrid(WIDTH, LENGTH);
}
public int compareGrids() {
String[] args = {};
ButtonGrid.main(args);
int numCorrect = 0;
for (int i = 0; i < WIDTH; i++) {
for (int j = 0; j < LENGTH; j++) {
if (grid[i][j].getBackground() == ButtonGrid.main(rGrid).grid[i][j].getBackground()) {
numCorrect++;
}
}
}
System.out.println(numCorrect);
return numCorrect;
}
Simple answer:
Make compareGrids() static and add arguments
public static int compareGrids(Grid grid1, Grid grid2) {
...
}
This is an entry level question, You may want to consult a simple java tutorial to understand basic class elements and modifiers
To use rGrid in compareGrids it has to be class level variable .
Declare
RandomGrid rGrid = new RandomGrid(WIDTH, LENGTH);
outside main.
It should solve your issue.
Presently scope of rgrid ends as soon as main method finishes
Please paste stack overflow error that you mentioned
ive been working on a java compiler assignment that is asking to find the First of a grammar. I have it all ready and done. all the work has been done , but i have one problem. my first is producing duplicates. for example part of my output is this
NonTerminal First
P int void
L int void
D int void
Vd int void
Ts int void
Fn int void
Ps int void void
Ps int void void , the 2nd void is a duplicate. how would i go about removing these duplicates? ill paste my main compiler code were everything happens below.
i suspect i would have to make a change somewere in the findFirst method, since thats were all the action happens , but im not sure what to do.
package compilerproject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.security.KeyStore.Entry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Compiler {
public static void main(String[] args) {
List<Grammar> gList = getGrammar();
Map<String, List<String>> fList = firstList(gList);
//firstlist returns a hash map LHS and RHS
//save it into fList which is a map of Strings and List so u can use it in findFirst method
printFirstList(fList, gList);
ParserLibrary idList = new ParserLibrary();
}
public static List<String> findFirst(String v, List<Grammar> l)
{
List<String> First = new ArrayList<String>();
for(int i = 0; i < l.size(); i++)
{
if(v.equals(l.get(i).term))
{
String [] s = l.get(i).prod.split(" ");
if(!isNonTerm(s[0]))// is a terminal
{
First.add(s[0]);
}
// if the rhs is a terminal
It would save some troubles using a Set instead of a List.
I kept List as return type, but changed the rest.
public static List<String> findFirst(String v, List<Grammar> l) {
Set<String> first = new TreeSet<>();
Set<String> done = new HashSet<>();
done.add(v);
Grammer previous = null;
for (Grammar gr : l) {
if (v.equals(gr.term)) {
String s = gr.prod.split(" ")[0];
if (!isNonTerm(s)) { // is a terminal
first.add(s);
}
// if the rhs is a terminal
if (s.equalsIgnoreCase("empty") && previous != null) {
String[] stemp = previous.prod.split(" ");
if (v.equalsIgnoreCase(stemp[0]) && stemp.length > 1
&& done.add(stemp[1])) {
first.addAll(findFirst(stemp[1], l)); // <--------- Here it happened
}
//if the rhs is empty , then get the previous grammar
//split it.
//find the first of it and ad it to the first list
}
if (!v.equals(s) && isNonTerm(s) && done.add(s)) {
first.addAll(findFirst(s, l));
}
}
previous = gr;
}
return new ArrayList<String>(first);
}
I still do not find the code entirely clear. So maybe with Set at your disposal, you may find a simpler formulation. To remove the scroll bar I place the open brace on the same line.
To prevent endless recursion I added the set done which "evidently" is not needed.
I am doing coding in android studio. I want to access the variable totalCuisine++ outside this method. Also totalCuisines is declared globally in claass i.e int totalCuisines = 0;
It is a part of big program but main problem is here in front of u, rest of all programs are executing successfully
public class CuisinesFilterDialog extends DialogFragment{
int totalCuisines = 0;
ArrayList<CuisinesModel> data = new ArrayList<>();
{
private void updateFilterStats() {
ArrayList allData = new ArrayList();
if(data != null && data.size() > 0){
for(int i=0; i<data.size(); i++){
if(data.get(i).isSelected()) {
allData.add(data.get(i).getName());
totalCuisines++;// I want to access it outside this method
}
}
DataStore.putString(getContext(), ZConstants.SortFilter.KEY_EXTRAS_FILTER_CUISINES,
TextUtils.join(",",allData));
}else{
DataStore.putString(getContext(), ZConstants.SortFilter.KEY_EXTRAS_FILTER_CUISINES,
ZConstants.EMPTY_STRING);
}
dismiss();
}
}
totalCuisines++ is not a variable. It means totalCuisines+1. However, You can access totalCuisines by several ways. The easiest way to declare totalCuisines as public variable. Like,
public int totalCuisines = 0;
I was implementing Graph data structure in Java.
Here is my implementation:
package Graph;
import java.util.*;
import java.io.*;
public class Graphs
{
int size;
LinkedList<Integer>[] ll;
Graphs(int size)
{
this.size = size;
ll = new LinkedList[size];
for(int i=0; i<size; i++)
ll[i] = new LinkedList<Integer>();
}
public static void print(LinkedList lli)
{
for(Integer i: lli)
System.out.println(i);
//for(int i=0; i<lli.size(); i++)
// System.out.println(lli.get(i));
}
public static void addEdge(Graphs graph, int up, int to)
{
graph.ll[to].add(up);
}
public static void main(String args[])
{
int V=5;
Graphs graph = new Graphs(V);
addEdge(graph,1,2);
addEdge(graph,1,3);
addEdge(graph,2,3);
addEdge(graph,3,1);
addEdge(graph,3,2);
addEdge(graph,3,4);
addEdge(graph,4,3);
print(graph.ll[3]);
}
}
Basically I am creating an array of LinkedLists for the graph with each linked list for a vertex of the graph.
However, I am getting a java.lang.Object cannot be converted to java.lang.Integer at line number 24. Clueless as to why am I getting this error. Any suggestions as to what am I missing?
The specific issue you're having is with your print function:
public static void print(LinkedList lli){
for(Integer i: lli)
System.out.println(i);
}
LinkedList is a raw type, meaning you lose type information about what kinds of objects are stored in the list. As a general rule, raw types are a bad idea. I'm very surprised your code compiled, but suffice to say that by saying Integer i : lli you're assumming that every object within lli is an Integer when the parameter LinkedList provides no such guarantee.
To ensure that this will work, change LinkedList lli to LinkedList<Integer> lli. This means that every object in lli is an instance of Integer, thus the iteration won't fail.
When I try to run your code, my IDE warns me about the line
ll = new LinkedList[size]
Saying:
Unchecked assignment: 'java.util.LinkedList[]' to 'java.util.LinkedList< java.lang.Integer >[]'
Which indicates that something fishy is going on here.
Mixing Lists and Arrays gets a bit messy with generic typing - it's a lot easier and cleaner to just do lists of lists if you need size mutability, or a multi-dimension array if not. For your case, that argues for a ArrayList<LinkedList<Integer>> or the like.
We can fix the issues by resolving the generic issues:
import java.util.*;
import java.io.*;
public class Graphs
{
int size;
ArrayList<LinkedList<Integer>> ll;
Graphs(int size)
{
this.size = size;
ll = new ArrayList<LinkedList<Integer>>();
for(int i=0; i<size; i++)
ll.add(new LinkedList<Integer>());
}
public static void print(LinkedList<Integer> lli)
{
for(Integer i: lli)
System.out.println(i);
//for(int i=0; i<lli.size(); i++)
// System.out.println(lli.get(i));
}
public static void addEdge(Graphs graph, int up, int to)
{
graph.ll.get(to).add(up);
}
public static void main(String args[])
{
int V=5;
Graphs graph = new Graphs(V);
addEdge(graph,1,2);
addEdge(graph,1,3);
addEdge(graph,2,3);
addEdge(graph,3,1);
addEdge(graph,3,2);
addEdge(graph,3,4);
addEdge(graph,4,3);
print(graph.ll.get(3));
}
}
Declare the print method like this:
public static void print(LinkedList<Integer> lli)
Then it will know that the contents of lli are integers.
I copied your code and it didn't compile until I changed
public static void print(LinkedList lli)
to:
public static void print(LinkedList<Integer> lli)
From where it worked without problems
Also giving variables a name which starts with an upper case letter is against the naming convention. Have a look at this oracle tutorial. The last bullet point on the page states:
If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. The names gearRatio and currentGear are prime examples of this convention.