"Variable" cannot be resolved to a variable error [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 12 days ago.
Improve this question
I am getting this error in VSCode Java. One of my variables, DriveConstants keeps having the error saying that it cannot be resolved to a variable. DriveConstants is called in Constants and I do not know if I am doing it right. I am new to Java and don't know why this error is happening. Below is the code that I have for DriveSubsystem:
//DriveSubsystem
package frc.robot.subsystems;
import frc.robot.Constants;
import edu.wpi.first.math.geometry.Pose2d;
import edu.wpi.first.math.kinematics.DifferentialDriveOdometry;
import edu.wpi.first.math.kinematics.DifferentialDriveWheelSpeeds;
import edu.wpi.first.wpilibj.ADXRS450_Gyro;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.drive.DifferentialDrive;
import edu.wpi.first.wpilibj.examples.ramsetecommand.Constants.DriveConstants;
import edu.wpi.first.wpilibj.interfaces.Gyro;
import edu.wpi.first.wpilibj.motorcontrol.MotorControllerGroup;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.TimedRobot;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.motorcontrol.VictorSP;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public class DriveSubsystem extends SubsystemBase {
// The motors on the left side of the drive.
private VictorSP frontLeftDrive;
private VictorSP backLeftDrive;
private VictorSP frontRightDrive;
private VictorSP backRightDrive;
private final MotorControllerGroup m_leftMotors =
new MotorControllerGroup(
new VictorSP(DriveConstants.kLeftMotor1Port),
new VictorSP(DriveConstants.kLeftMotor2Port));
}
//Constants
package frc.robot;
import edu.wpi.first.math.kinematics.DifferentialDriveKinematics;
public class Constants {
public static final class DriveConstants{
public static final double kTrackwidthMeters=0.96;
public static final DifferentialDriveKinematics kDriveKinematics = new DifferentialDriveKinematics(kTrackwidthMeters);
//EXAMPLE VALUES WILL NEED TO CHANGE
public static final double ksVolts=0.22;
public static final double ksVoltsSecondPerMeter=1.98;
public static final double kaVoltSecondsSquaredPerMeter=0.2;
public static final double kPDriveVel=8.5;
}
public static final class AutoConstants {
//3mph= 1.34112 m/s
//5mph= 2.2352 m/s
public static final double kMaxSpeedMetersPerSecond= 1.34112;
public static final double kMaxSpeedMetersPerSecondSquared=1;
// Reasonable baseline values for a RAMSETE follower in units of meters and seconds
public static final double kRamseteB = 2;
public static final double kRamseteZeta = 0.7;
}
}

Need to import frc.robot.Constants.DriveConstants;

Related

Class Loop problem while calling method from other class [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to call a method from a other class but here is the problem:
The main class imports the second class with this:
Sc secondclass = new Sc();
The main class also contains this method:
public void home_open() {
for (int i = 0; i < buttons.length; i++) {
buttons[i].setVisible(false);
}
}
If I want to import this into the second class:
Mc mainclass = new Mc();
A loop will happen, if I want to import it in this way:
Mc mainclass;
This error will occur:
"this.this$0.mainclass" is null
My Goal is to call a method in the main class.
Change the constructor of the second class to
public class Sc {
private Mc mc;
/**
* Constructor
*/
public Sc(Mc mc) {
this.mc = mc;
}
}
and call the constructor like so
Mc mainclass = new Mc();
Sc secondclass = new Sc(mainclass);
Now you can call methods of class Mc via the mc member of class Sc.
EDIT
Based on the [pseudo] code linked to in this comment, consider the following.
Class Home
package homeshop;
import javax.swing.JButton;
public class Home {
private JButton[] buttons;
public Home() {
new Shop(this);
}
void homeOpen() {
for (int i = 0; i < buttons.length; i++) {
buttons[i].setVisible(true);
}
}
}
Class Shop
package homeshop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class Shop {
private Home home;
private JButton[] buttons;
public Shop(Home home) {
this.home = home;
buttons[0].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
home.homeOpen();
}
});
}
}
Method homeOpen, in class Home, has package access so that it can be called from class Shop since both classes are in the same package. Also note that I changed the method name so as to adhere to Java naming conventions.

Can't compile Oracle docs example

this is my first question here so bear with me please.
I'm trying to use the Oracle Java docs, but when I try to compile example 6 on this page it doesn't work. I've tried everything I can think of. It's an old example, so that may be the issue, but it's disheartening that I can't figure out what should be a minor problem.
Example 6 Using an InvalidationListener
package bindingdemo;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.binding.NumberBinding;
import javafx.beans.binding.Bindings;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
class Bill {
// Define the property
private DoubleProperty amountDue = new SimpleDoubleProperty();
// Define a getter for the property's value
public final double getAmountDue(){return amountDue.get();}
// Define a setter for the property's value
public final void setAmountDue(double value){amountDue.set(value);}
// Define a getter for the property itself
public DoubleProperty amountDueProperty() {return amountDue;}
}
public class Main {
public static void main(String[] args) {
Bill bill1 = new Bill();
Bill bill2 = new Bill();
Bill bill3 = new Bill();
NumberBinding total = Bindings.add(bill1.amountDueProperty().add(bill2.amountDueProperty()),
bill3.amountDueProperty());
total.addListener(new InvalidationListener() {
#Override public void invalidated(Observable o) {
System.out.println("The binding is now invalid.");
}
});
// First call makes the binding invalid
bill1.setAmountDue(200.00);
// The binding is now invalid
bill2.setAmountDue(100.00);
bill3.setAmountDue(75.00);
// Make the binding valid...
System.out.println(total.getValue());
// Make invalid...
bill3.setAmountDue(150.00);
// Make valid...
System.out.println(total.getValue());
}
}
Thanks

Deeplearning on Spark pipeline: How to predict using a neural network model in a pipeline?

I am trying to add sentiment analysis program to Spark pipeline. When doing it, I have class which extends org.apache.spark.ml.PredictionModel. When extending this PredictionModel class, I have to override predict() method which predicts the label for given feature. But, I get either 0 or 1 all the time when I execute this code.For example, if there are 10 movie reviews, five are negative reviews and other five are negative, it classifies all reviews as negative. I have attached the code below.
import org.apache.spark.ml.PredictionModel;
import org.apache.spark.ml.param.ParamMap;
import org.apache.spark.mllib.linalg.DenseVector;
import org.apache.spark.mllib.linalg.Vector;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.nd4j.linalg.api.buffer.DataBuffer;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import java.io.*;
//Model produced by a ProbabilisticClassifier
public class MovieReviewClassifierModel extends PredictionModel<Object, MovieReviewClassifierModel> implements Serializable{
private static final long serialVersionUID = 1L;
private MultiLayerNetwork net;
MovieReviewClassifierModel (MultiLayerNetwork net) throws Exception {
this.net=net;
}
#Override
public MovieReviewClassifierModel copy(ParamMap args0) {
return null;
}
#Override
public String uid() {
return "MovieReviewClassifierModel";
}
public double raw2prediction(Vector rawPrediction) {//Given a vector of raw predictions, select the predicted label
return rawPrediction.toArray()[0];
}
#Override
public double predict(Object o) {
int prediction=0;
DenseVector v=(DenseVector)o;
double[] a=v.toArray();
INDArray arr=Nd4j.create(a);
INDArray array= net.output(arr,false);
DataBuffer ob = array.data();
double[] d=ob.asDouble();
double zeroProbability=d[0];
double oneProbability=d[1];
if (zeroProbability > oneProbability) {
prediction=0;
}
else{
prediction=1;
}
return prediction;
}
}
Can you give me reasons for the wrong predictions?
In public double predict(Object o) you have a following if statement:
if (zeroProbability > oneProbability) {
prediction=0;
}
else{
prediction=1;
}
which causes the return of 0 or 1. Change this method in order to have some other prediction values.

Junit-Quickcheck: Generate String matching a pattern

I am using pholser's port. I have to generate strings matching a given pattern like \[a-zA-Z0-9\\.\\-\\\\;\\:\\_\\#\\[\\]\\^/\\|\\}\\{]* Length 40.
I extend the Generator class as:
public class InputGenerator extends Generator<TestData> {...}
It overloads a function:
publicTestData generate(SourceOfRandomness random, GenerationStatus status) {...}
Now, random has functions like nextDouble(), nextInt() but there is nothing for strings! How can I generate random strings matching the above pattern?
Find below snippet for a custom generator which implement the generate(..) method to return a random string matching your posted pattern.
public class MyCharacterGenerator extends Generator<String> {
private static final String LOWERCASE_CHARS = "abcdefghijklmnopqrstuvwxyz";
private static final String UPPERCASE_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String NUMBERS = "0123456789";
private static final String SPECIAL_CHARS = ".-\\;:_#[]^/|}{";
private static final String ALL_MY_CHARS = LOWERCASE_CHARS
+ UPPERCASE_CHARS + NUMBERS + SPECIAL_CHARS;
public static final int CAPACITY = 40;
public MyCharacterGenerator () {
super(String.class);
}
#Override
public String generate(SourceOfRandomness random, GenerationStatus status) {
StringBuilder sb = new StringBuilder(CAPACITY);
for (int i = 0; i < CAPACITY; i++) {
int randomIndex = random.nextInt(ALL_MY_CHARS.length());
sb.append(ALL_MY_CHARS.charAt(randomIndex));
}
return sb.toString();
}
}
edit A simple unit test to demonstrate the usage of the MyCharacterGenerator class.
import com.pholser.junit.quickcheck.ForAll;
import com.pholser.junit.quickcheck.From;
import static org.junit.Assert.assertTrue;
import org.junit.contrib.theories.Theories;
import org.junit.contrib.theories.Theory;
import org.junit.runner.RunWith;
#RunWith(Theories.class)
public class MyCharacterGeneratorTest {
#Theory
public void shouldHold(#ForAll #From(MyCharacterGenerator.class) String s) {
// here you should add your unit test which uses the generated output
//
// assertTrue(doMyUnitTest(s) == expectedResult);
// the below lines only for demonstration and currently
// check that the generated random has the expected
// length and matches the expected pattern
System.out.println("shouldHold(): " + s);
assertTrue(s.length() == MyCharacterGenerator.CAPACITY);
assertTrue(s.matches("[a-zA-Z0-9.\\-\\\\;:_#\\[\\]^/|}{]*"));
}
}
sample output generated by shouldHold
shouldHold(): MD}o/LAkW/hbJVWPGdI;:RHpwo_T.lGs^DOFwu2.
shouldHold(): IT_O{8Umhkz{#PY:pmK6}Cb[Wc19GqGZjWVa#4li
shouldHold(): KQwpEz.CW28vy_/WJR3Lx2.tRC6uLIjOTQtYP/VR
shouldHold(): pc2_T4hLdZpK78UfcVmU\RTe9WaJBSGJ}5v#z[Z\
...
There is no random.nextString(), but there is a way to generate random strings within junit-quickcheck-generators library. You can access it when creating new generators using gen().type(String.class). However, it seems we don't have much control over it.
Here is a silly example of a StringBuilder generator to demonstrate how to use the String generator:
import com.pholser.junit.quickcheck.generator.GenerationStatus;
import com.pholser.junit.quickcheck.generator.Generator;
import com.pholser.junit.quickcheck.random.SourceOfRandomness;
public class StringBuilderGenerator extends Generator<StringBuilder> {
public StringBuilderGenerator() {
super(StringBuilder.class);
}
#Override
public StringBuilder generate(SourceOfRandomness random, GenerationStatus status) {
String s = gen().type(String.class).generate(random, status);
return new StringBuilder(s);
}
}
I just made a library that suppose to do what you want in a generic way: https://github.com/SimY4/coregex
Simple usage example:
import com.pholser.junit.quickcheck.Property;
import com.pholser.junit.quickcheck.runner.JUnitQuickcheck;
import org.junit.runner.RunWith;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
#RunWith(JUnitQuickcheck.class)
public class CoregexGeneratorTest {
#Property
public void shouldGenerateMatchingUUIDString(
#Regex("[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}")
String uuid) {
assertEquals(uuid, UUID.fromString(uuid).toString());
}
}

Loading same value in inner HashMap [duplicate]

This question already has answers here:
Why is a ConcurrentModificationException thrown and how to debug it
(8 answers)
Closed 8 years ago.
I am trying to enter the below statement into HashMap
Input Line: Rainy#No:2 Sunny#No:3 Rainy#Yes:3 Sunny#Yes:2 Overcast#Yes:4
Expected Output:{Rainy={No=2,Yes=3},Rainy={No=3,Yes=2},Overcast={Yes=4}}
What I did so far is
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class StackHash{
/**
*#paramargs
*/
staticConcurrentMap<String,HashMap<String,Integer>>map=newConcurrentHashMap<>();
public static final String TAB="\t";
public static final String SPACE=" ";
public static final String HASH="#";
public static final String COLON=":";
public static void main(String[]args){
//TODOAuto-generatedmethodstub
Stringline="Rainy#No:2 Sunny#No:3 Rainy#Yes:3 Sunny#Yes:2 Overcast#Yes:4";
StringTokenizerst=newStringTokenizer(line,SPACE);
HashMap<String,Integer>attibuteCollect=newHashMap<String,Integer>();
while(st.hasMoreTokens()){
Stringtoken1=st.nextToken();
String[]parts=token1.split(HASH);
String[]parts1=parts[1].split(COLON);
attibuteCollect.put(parts1[0],Integer.parseInt(parts1[1]));
if(map.isEmpty()){
map.put(parts[0],attibuteCollect);
}
else{
for(Map.Entry<String,HashMap<String,Integer>>entry:map.entrySet()){
StringkeyMap=entry.getKey();
if(keyMap.equals(parts[0])){
map.put(keyMap,attibuteCollect);
}
else{
map.put(parts[0],attibuteCollect);
}
}
}
}
System.out.println("finalmap"+map);
}
}
Output
map {Rainy={Yes=4, No=3}, Sunny={Yes=4, No=3}, Overcast={Yes=4, No=3}}
Am I doing anything wrong.
Please Suggest.
Reason:
You got ConcurrentModificationException because, you have modified inner attibuteCollect map using put method while iterating over outer map.
Solution:
Use ConcurrentHashMap insted of HashMap to solve ConcurrentModificationException.
ConcurrentMap<String, HashMap<String,Integer>> map = new ConcurrentHashMap<>();

Categories