I am working on a project and ran into a problem. I have the following code:
private void evaluateCurrentOperation() {
double token;
Object currentOperator = thisExprStack.pop();
double currentOperand;
double result = 0.0;
while (!thisOpStack.isEmpty()) {
currentOperand = thisOpStack.pop();
if (currentOperator.equals('+')) {
result += currentOperand;
}
if (currentOperator.equals('-')) {
result -= currentOperand;
}
if (currentOperator.equals('/')) {
result /= currentOperand;
}
if (currentOperator.equals('*')) {
result *= currentOperand;
}
}
thisExprStack.push(result);
}
I am using Eclipse and when I tried to use the local variable "result" inside the if blocks I had a warning saying that result was not being used. I am confused because I clearly used this variable but it acts like it doesn't exist. I am new to Java so I do not know how to debug my code.
When I push "result" onto "thisExprStack", it pushes 0.0. The value it was initialized to. How do I get it to push the "result" inside the if blocks?
Ignore the previous answer. Are the relevant thisExprStack and thisOpStack populated?
Related
I have this problem where I initialize a variable outside of a forloop. And then inside of the forloop try to update the value of this variable but everytime I "local variable not used". I tried a simple example (below) and the problem is still there. Ret is highlighted in my compiler and the error message is displayed. I don't understand why I can't access variables inside my loops anymore. Is this possibly due to me missing a bracket somewhere in my methods somewhere else in the class?
public static String test(String input) {
String ret = "";
for(int i=0;i<5; i++) {
ret += "m";
}
return "";
}
I was wondering if someone could help me with this. I would really appreciate it. Thanks!
You get this error message because you are building the ret variable but you are not using it. For example if you use the variable in an if statement you will not get the error anymore.
public static String test(String input) {
String ret = "";
for(int i=0;i<5; i++) {
ret += "m";
}
if (ret.equals("mmmmm")){
ret +="";
}
return "";
}
I suspect your IDE or compiler is noticing that you build up text in the local var ret but you never use that text. That built-up text is discarded, and you return an empty string. Your tools are alerting you to this nonsense.
Also, you make no use of the argument passed to your static method, more nonsense.
I am trying to write a method which does not take any arguments and then returns a double variable. It is a postcode identifier so when a cost code is entered certain post codes need to return a double.
In my example below i need post codes that start with either "GH6 TXX" or "NC4 LXX". (X stands for any random character or digit) to return 50.0.
If any other postcode is entered then return 100.0.
However i am not getting any results back and just finding errors. I'm sure i have gone massive wrong somewhere as im not great with If Else statements within methods. Any help or knowledge on this would be great!
public class multiPostcodeRange {
//Declaring Variables
String pcode;
public multiPostcodeRange()
{
pcode = "XXX XXX";
}
public void multiPostcodeRange()
{
if (pcode("GH6 TXX", "NC4 LXX")) {
return 100.0; }
else {
return 50.0;}
} }
public class MultiPostcodeRange {
private String pcode;
public MultiPostcodeRange() {
pcode = "XXX XXX";
}
public double multiPostcodeRange() {
if (pcode.equals("GH6 TXX") || pcode.equals("NC4 LXX")) {
return 100.0;
}
else {
return 50.0;
}
}
}
To return double from a function you need to define a return type for the function.
public double multiPostcodeRange
You created a class with his methods (which btw you shouldn't name as the class, but give them unique names).
Then you have to create a new instance object of that class and call the method on a main function.
For example, at the end of your code:
`public static void main(String args[]){
multiPostcodeRange Obj = new
multiPostcodeRange();
Obj.meth1();
Obj.meth2();}`
NB remember to give those methods unique names!
Also change 2nd method body and type as AndyMan's answer
I am writing a bot for trading. I need to get the price difference in time intervals. Let's say at 00:00:00:0000 GMT the price of a pair is 100.0000, and at 00:00:00:0005 GMT the price is 101.0000, I want to get this difference.
I am using Spring boot scheduler, when I run the app it always returns that the price isn't much. I want it to continually check nutil the price difference gets to the price.
This is to check every 5 minutes
#Scheduled(fixedRate = (10*60*1000))
private double getInitialPrice(){
try {
initialPrice = Double.parseDouble(String.valueOf(api.pricesMap().get("BTCUSDT")));
} catch (BinanceApiException e) {
e.printStackTrace();
}
return initialPrice;
}
This is to check every 5 milliseconds
#Scheduled(fixedRate = (5))
private double getInstancePrice(){
try {
instancePrice = Double.parseDouble(String.valueOf(api.pricesMap().get("BTCUSDT")));
} catch (BinanceApiException e) {
e.printStackTrace();
}
return instancePrice;
}
I'm now checking with the hope that the getInstancePrice() method will always check until it's true. It failed the test as it always returns that the price is not higher, whereas when manually checked it's higher. How do I make it continually check until it gives the time difference?
if( getInstancePrice() > getInitialPrice() ){
//do this
}
I think you don't need to have the attributes as static, because that means they have the same value for all the class instances.
Another point is returning a value from a method that use the #Scheduled annotation.
In your code:
if( getInstancePrice() > getInitialPrice() ){
//do this
}
You're just executing the api call and update your values, that will be pretty much the same if they get the same time provided from the API.
What you should do is just set up your initialPrice at the beginning, then compare it to the new value got from the api:
private Double initialPrice = null;
private double instancePrice;
...
#Scheduled(fixedRate = (5))
private double getInstancePrice(){
try {
instancePrice = Double.parseDouble(String.valueOf(api.pricesMap().get("BTCUSDT")));
if (initialPrice == null) {
initialPrice = instancePrice;
} else if (instancePrice > initialPrice) {
// do this
}
} catch (BinanceApiException e) {
e.printStackTrace();
}
return instancePrice;
}
You need initialPrice to be an object of Double to be able to set it to null and initialize it. If you are using Java 8 or greater thant you should use an Optional instead.
Is there a way to identify whether the following method executed completely or returned halfway through(i.e at line no 3)
static int a=0;
static void test(){
if(a>10){
return;
}
a++;
}
The method was invoked by another method.(a might have been changed by it)
I cannot change the method declaration. I am dealing with an object I created from a java file created by someone else. I am not allowed to change the original file
Your method does almost nothing and no there is no way in this example you gave to know if the method returned before complete execution but if you willing to change the function to a boolean type you can return true at complete execution and false at incomplete.
static boolean test()
{
if(a>10)
return false;
a++;
return true;
}
Run the code under debugger like jdb and set the breakpoint on the internal return statement. If the program stops at this breakpoint, this obviously means that it would return through that statement.
To make things more automated, you could try to launch the debugger and control the debugger from a Java program through Runtime. This would make the approach applicable for more use cases, while not for all.
You could use
void test(int a) {
if (a > 10) {
return;
}
a++;
System.out.println("test executed completely!");
}
Or if you want to use the information programmatically
private boolean executedCompletely;
void test(int a) {
executedCompletely = false;
if (a > 10) {
return;
}
a++;
executedCompletely = true;
}
When you use your test method, you can check whether it ran completely this way:
int initialA = a;
test();
int finalA = a;
if (finalA != initialA) {
//a has been changed, therefore the method ran completely
} else {
//a has not been changed, therefore it was not incremented, therefore the method did not run completely
}
I have the following method that normalises a given XML tag name:
public static String normaliseTagName(String tagName) {
// Return a given empty tag name.
if (tagName.length() == 0) {
return tagName;
}
// Replace invalid start.
if (isInvalidXMLStart(tagName.charAt(0))) {
tagName = XML_REPLACEMENT + tagName;
}
// Replace invalid characters.
StringBuilder normalised;
boolean invalidFound = false;
for (int i = 0; i < tagName.length(); i++) {
if (isInvalidXMLChar(tagName.charAt(i))) {
if (!invalidFound) {
normalised = new StringBuilder(tagName.substring(0, i));
invalidFound = true;
}
normalised.append(XML_REPLACEMENT); // COMPILER ERROR
} else if (invalidFound) {
normalised.append(tagName.charAt(i)); // COMPILER ERROR
}
}
return invalidFound ? normalised.toString() : tagName; // COMPILER ERROR
}
I don't want to initialise the StringBuilder normalised before I'm sure to use it. In other words, I want to only initialise it when an invalid XML character is found.
I get The local variable normalised may not have been initialized errors where indicated, and I'm puzzled as to why the compiler is telling me that when normalised is clearly never used uninitialised.
Am I missing something or is the compiler unable to determine the initialisation path of the StringBuilder normalised in this situation?
If this compilation error cannot be avoided, how can I modify this code so that I initialise the StringBuilder only when I need it?
Thanks!
You need to explicitly initialize your local variable:
StringBuilder normalised = null;
... or ...
StringBuilder normalised = new StringBuilder();
... before referencing it.
Some of the pathways in your code reference normalised prior to its initialization:
normalised.append(...
Local variables are not automatically initialized as would, instance fields.