Variable declaration not allowed here, used in if statement [duplicate] - java

This question already has answers here:
JAVA Variable declaration not allowed here
(5 answers)
Closed 5 years ago.
After typing that first part of the if statement, I was going to use the next line to declare a variable (costPerCD) but I'm told "Variable declaration is not allowed here." I'm not sure how else to calculate the costPerCD without using this method. This is an example of what I'm trying to do. Any help would be appreciated.
if ((numCDs>=1 && (numCDs<=4))
double costPerCD= 20.99;

You should declare that variable as a class variable. Then you can access the variable throughout your class.
You need to add an additional ")" to your code after your first condition. This should prevent the error you are getting.
public class CDCal {
//Class Variable can be accessed in this class
private costPerCD;
public CDCal(){
//Assign value when object created
costPerCD = 20.99
}
public double calculateCost(int numCDs){
double total = 0;
if((numCDs >= 1) && (numCDs <= 4))
{
//Calculate total cost of CD's based on number and price
total = costPerCD * numCDs;
}
//Return the total at the end of the method.
Return total;
}
If you have an example I will be happy to review it to help you out.

Related

Unable to change the value of variable inside for-loop & if-else statement in Java [duplicate]

This question already has answers here:
Why does the Java compiler not understand this variable is always initialized?
(3 answers)
Closed 1 year ago.
I'm working on a java function involving for-loop and if-else statement. and I have a need to change the value of a flag variable according to the conditions in multiple iterations. I declared a variable named flag and wants to change according to the condition in each iteration. And I need to print the value of the flag variable at the end of each iteration. But while I printing the variable it shows an error that the variable isn't initialized. If I gives it an initial value, it prints the initial value all the time, not the value manipulated inside the if-else statement. I can't initialize the flag variable inside the for-loop according to my requirement. Below is my code:
int flag;
for(int i=0; i< fileOneLines.length; i++){
diffs = diffMatchPatch.diffMain(fileOneLines[i],fileTwoLines[i]);
diffMatchPatch.diffCleanupSemantic(diffs);
for (DiffMatchPatch.Diff aDiff : diffs) {
if(aDiff.operation.equals(DiffMatchPatch.Operation.INSERT)){
flag = 1;
}
else if(aDiff.operation.equals(DiffMatchPatch.Operation.DELETE)){
flag = 2;
}
else if(aDiff.operation.equals(DiffMatchPatch.Operation.EQUAL)) {
flag = 0;
}
}
System.out.println(flag);
}
It's the error shown:
java: variable flag might not have been initialized
You need to initialize your flag object with any sort of value since there is a possibility it is not initialized when you try to print it leading to your error.
If fileOneLines.length returns 0 or your diffs collection is empty or if your if-elses aren't met then flag won't be initialized.

What's wrong with my code for the toString() method? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
please note that I'm a complete beginner to programming and have found learning Java quite hard. I have a school task that requires me to write a code for a toString() method and I've blindly followed what my teacher has been writing/teaching in class but for some reason my code doesn't seem to work when I run the test file? I've included my code below.
I do get an error that says the following- "Null pointer access: The variable coef can only be null at this location" but when I change all my coef[] variables, then my code becomes moot because it just equates to null.
Any pointers greatly appreciated!
EDIT 1: Thank you for your responses - I thought I needed to intialise coef[] as a variable inside my toString() method (big oops!!). Also thank you for providing the link to the NullPointer question - it had some really thorough explanations and now I understand that I dereferenced the coeff[] variable.
QUERY a: I've removed my first line but now it seems that my code fails on this line return coef[1]+ "x + " + coef[0];
QUERY b: curious to know why it's a bad sign if the class is plural?
public class Polynomials {
public Double coefficient;
public Integer exponent;
private int[] coef;
public String toString() {
String[] coef = null;
if (exponent <= -1)
return "0";
else if (exponent == 0)
return "" + coef[0];
else if (exponent == 1)
return coef[1]+ "x + " + coef[0];
String s = coef[exponent] + "x^" + exponent;
return s;
}
Your Polynomials class has 3 fields, and one is called coef. In your toString method you then declare a local variable, also called coef.
In java, that means the local variable 'shadows' the field - in other words, for that entire method, coef refers to the String[] coef = null; and not the int[] coef.
And that local field is always null - you create it, initialize it to null, and never change it. Thus, choef[0] will guaranteed throw a NullPointerException at runtime.
The fix seems to be to .... just remove that String[] coef = null; line entirely. I have no idea why you wrote that or what it's trying to accomplish.
NB: Shouldn't the class be named Polynomial? Naming a class a plural is usually a bad sign.

How to find Max value of a int tag in a java text file [duplicate]

This question already has answers here:
How to open a txt file and read numbers in Java
(6 answers)
Closed 6 years ago.
I am trying to make a method that finds the max value of an integer in a vector. I want a method such as
/**
* The method returns an integer.
* The integer is the greatest value of all tagValues of the lab devices
*/
public int findMaximumValueTag()
The tag values will be the integer beside a device in a text file, on every line, such as
Android,53
Blackberry2,-95
iPhone,45
So, with the above, the method should return the 53.
The start of the class that contains the method is as follows:
public class Lab implements MaxTagValue {
String labName;
Vector<MobileDevice> devices;
Any help at all with pseudo code or anything would be greatly appreciated to get this started, thank you very much!
Also the beginning of the MobileDevice class is as follows:
public class MobileDevice {
String deviceName; // the device name
int valueTag; // an integer between -100 and 100
Lab lab; // the lab having this device it its inventory
you can iterate through your vector with a for-each-loop and save the int value in a variable called max or something like that. and every time you go through the loop you check if the current int value is bigger than max or not. if yes you set max to the current int value if not you ignore it
code:
Vector<MobileDevice> devices;
int max=0;
for(MobileDevice md:devices){
if(md.getValueTag()>max){
max=md.getValueTag();
}
}

Beginner Java Scope Issue [duplicate]

This question already has an answer here:
Beginner Java: Variable Scope Issue
(1 answer)
Closed 7 years ago.
I'm new to programming and seem to be running into issues with when a variable, class, etc can and can't be referenced. Below is an example, hoping one of you can fix the specific issue but also help me understand it more broadly so I don't run into it again and again.
to try and avoid posting a bunch of code please note that a Question class is defined as well as a setText, setAnswer, checkAnswer, and display method are all defined elsewhere (all public).
The relevant code is below and I have two questions:
Why is the variable first not recognized in the method presentQuestion()?
At the very end there, why can't I just call the method checkAnswer() on first, i.e. why can't I just do first.checkAnswer(response);? Why do I have to define it in a new variable: boolean outcome = first.checkAnswer(response);?
Code:
/**
* This program shows a simple quiz with two questions.
*/
public class QuestionDemo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Question first = new Question();
first.setText("Who was the inventor of Java?");
first.setAnswer("James Gosling");
Question second = new Question();
second.setText("Who was the founder of Udacity?");
second.setAnswer("Sebastian Thrun");
int score = 0;
score = score + presentQuestion(first, in);
// Present the second question
score = score + presentQuestion(second, in);
System.out.println("Your score: " + score);
}
/**
* Presents a question to the user and obtains a response.
* #param q the question to present
* #param in the scanner from which to read the user input
* #return the score (1 if correct, 0 if incorrect);
*/
public static int presentQuestion(Question q, Scanner in) {
// Display the first question
first.display();
System.out.println("Your answer:");
String response = in.nextLine();
// Check whether the response was correct
// If so, print "true" and return 1
// Otherwise, print "false" and return 0
boolean outcome = first.checkAnswer(response);
System.out.println(outcome);
if (outcome) {
return 1;
}
else {
return 0;
}
}
}
The reason you can't use the variable first inside presentQuestion is because it's defined in main, and therefore not visible outside of main. Isn't this precisely why you gave presentQuestion its Question q parameter, however?
It seems to me that this is what you want to do:
public static int presentQuestion(Question q, Scanner in)
{
// Display the first question
q.display();
System.out.println("Your answer:");
String response = in.nextLine();
// Check whether the response was correct
// If so, print "true" and return 1
// Otherwise, print "false" and return 0
boolean outcome = q.checkAnswer(response);
System.out.println(outcome);
if (outcome) {
return 1;
} else {
return 0;
}
}
Note that references to first have been replaced by references to q.
To try and clear up what I imagine your confusion may consist in, imagine if presentQuestion were called from another method than main, in which case no first variable would be declared at all. What would then happen to the references to first inside of presentQuestion, now not referring to anything at all? This is why you need to explicitly pass the data you want as parameters. Different methods are independent blocks of code, and you can't intermingle variable references between them even if they happen to call each other.
As for question 2, there should indeed be no problem with checking if(q.checkAnswer(response)) directly, without using the outcome variable. I'm guessing you were simply confused by the error emitted by the compiler when first wasn't recognized again.
first is a local variable, that means it can only be accessed inside the method in which it is defined.
You don't have to put the result of checkAnswer() into a boolean before using it. Actually, if (checkAnswer(response)) { ... } is valid.
presentQuestion takes a question as a parameter. In main, you're calling it on the first question, and then on the second question; it looks like the intent is that you use presentQuestion on the first question, and then on the second question. So far, so good.
The problem is that in presentQuestion, you're referring to the question (which could be the first or the second question) as q in the parameter list. All you need to do is use q instead of first in the rest of the method.
When I was new to programming, I had this problem as well! Then I found out it is very simple.
For your first question, first is declared in the main method and you want to use it in presentQuestion method. But presentQuestion and main are different methods! So you can't get to first in presentQuestion. As you can see, there is a Question-typed parameter in the presentQuestion method. This is like you telling first, "Come here, man! And then change your name to q." When you do pass the argument first to presentQuestion,
presentQuestion (first, in);
first comes to the pressentQuestion method with its name being as q. So you should use q instead of first in the presentQuestion method.
Now the second question, using a variable in this context is not needed. But to increase efficiency, use a boolean variable to store the result of checkAnswer. Let's imagine what happens if you don't use a boolean variable.
System.out.println(q.checkAnswer(response));
if (q.checkAnswer(response)) {
return 1;
} else {
return 0;
}
See? you called q.checkAnswer twice! This would slow down your program so you should use a boolean variable.

"Cannot resolve symbol" of my declared variable? [duplicate]

This question already has answers here:
Scope of variable declared inside a for loop
(5 answers)
Closed 8 years ago.
The solution to my problem is probably something really obvious, but I have yet to find it. If you're at all wondering what this code is suppose to do, it's suppose to take 10 user-inputted numbers, add them together, and output the average. My only error thus far is that where I have double average = sum / 10;
it doesn't read the variable sum and I'm at a total loss as to why.
import java.io.*;
class Average
{
public static void main (String args[]) throws IOException
{
// declare some variables
int count = 0;
String inInput;
// declare array constructer
double[] userInput = new double[9];
// declare a reader
InputStreamReader inStream = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(inStream);
// print out the array
while (count >= 9)
{
if (count != 10)
{
System.out.println ("Please enter a value");
}
else
{
System.out.println ("Please enter another value");
}
inInput = reader.readLine();
double inInputDouble = Double.parseDouble(inInput);
userInput[count] = inInputDouble;
double sum = sum + userInput[count];
count++;
}
double average = sum / 10;
System.out.println ("The average of all the numbers you have entered is" + average);
}
}
A variable can only be used inside the scope of which it is declared. Your sum variable is declared inside the while body and can thus only be used inside that scope.
Move the declaration of sum outside of the while loop as follows:
double sum = 0;
// print out the array
while (count >= 9)
{
...
sum = sum + userInput[count];
...
}
...
You probably also want to change count >= 9 to count < 9 to avoid ArrayIndexOutOfBounds.
int count is always 0, so it never goes into while(count >= 9) and when sum is called it won't be defined at all, change it for while(count <= 9)
You are declaring you variable sum inside the while loop block. Once that block finishes the variable goes out of scope and is no longer defined.
Put your double sum declaration before the while and you should be fine.
The scope of sum is the block it's declared in which is the block of the while loop.
Declare sum outside the while loop.
It doesn't make too much sense to redeclare this variable over and over again, because you want to sum up all numbers.
Take a look at this question:
Scope of variable declared inside a for loop
As said above, the sum must be declared befor the for loop.
Scopes are like brackets in programs,
int a ..
{
int b ...
{
int c ...
}
}
if the instruction evaluated is on line with a, it cannot know about the state of b and c, since they are not declared yet.
if instuction pointer evaluates line with int c , it know about all the variables because it allready got into the 3rd level of scoping. but since c is declared on 3rd level, after the instuction pointer goes outer from the brackets, if you did not saved the value of c in an upper leveled variable, the value gets lost, since c gets cleaned, and it is not accessible(outer scope). It is the same like you would want to read a variable from another file... you cant, scopes are like sticky notes which start from outer and append new smaller stickynotes, which after iot has been worked with , they get removed
scope: class definitions > method definitions > block definitions(for, while, if)
visible everywhere - visible under the method > visible in the block only
after it exits method all (eg: for (int i;..)
is gone i is not visible outer the for / brackets
another bug:
new double[9]; ?
you said it is supposed to take 10 ints...
at initialistion you dont count 0... 0 is used at 0 based indexing (a[0],a[1],a[2] needs a new int[3])... set it to new double[10];

Categories

Resources