I am a new learner of Java. I learned some of the Java core concepts. I got the identifier expected error when run my following code:
class Sekar {
public static int i,j,k;
i = 900;
static void max()
{
j = 100;
if(i>j)
{
k=i;
}
else {
k=j;
}
System.out.println("The maxmimum vale between"+i+"and"+j+"is :"+k);
}
public static void main(String[] args) {
max();
}
}
When I compile my code, I get the following error:
error: identifier expected
i = 900;
^
Can any one explain why this error happens here?
When I google about identifier expected error, I found that this error happens when variables are declared without datatype, but I declared that for all my variables i,j,k.
When I redeclare the data type again while setting value to "i" like int i = 900 it works. Why does it?
i = 900;
This is a statement in Java, it can be inside Constructor or method, or initialization block.
In your case, you may move that inside the max() method
When I re declare the data type again while setting value to "i" like
int i = 900 it works. Why does it?
Here, you are declaring and assigning the value to the variable in the same time, same line.
Check here for more details and here about java statements, expressions
Statements
Statements are roughly equivalent to sentences in natural languages. A
statement forms a complete unit of execution. The following types of
expressions can be made into a statement by terminating the expression
with a semicolon (;).
Assignment expressions
Any use of ++ or --
Method invocations
Object creation expressions
Hava a look at Java: Identifier expected :
i = 900;
is a statement as any other. You can't write statement anywhere. It must be in methods/constructors body. Initializing variable in declaration is called definition and is exception to this rule.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html
If you want to initialize static variable you can do it 2 (sane) ways:
Initialize variable right where you are declaring it:
class Sekar {
public static int i = 900, j,k;
static void max()
{
j = 100;
if(i>j)
{
k=i;
}
else {
k=j;
}
System.out.println("The maxmimum vale between"+i+"and"+j+"is :"+k);
}
public static void main(String[] args) {
max();
}
}
or do it in static constructor:
class Sekar {
public static int i, j,k;
static {
i = 900;
}
static void max()
{
j = 100;
if(i>j)
{
k=i;
}
else {
k=j;
}
System.out.println("The maxmimum vale between"+i+"and"+j+"is :"+k);
}
public static void main(String[] args) {
max();
}
}
Also, if you want to define a constant I recommend using final keyword.
j could be converted to local variable.
class Sekar {
public static final int I = 900;
static void max()
{
int k;
int j = 100;
if(I>j)
{
k=I;
}
else {
k=j;
}
System.out.println("The maxmimum vale between"+I+"and"+j+"is :"+k);
}
public static void main(String[] args) {
max();
}
}
What you probably want to do is this:
class Sekar {
public static int i=900,j=100,k;
static void max()
{
if(i>j)
{
k=i;
}
else {
k=j;
}
System.out.println("The maxmimum vale between"+i+"and"+j+"is :"+k);
}
public static void main(String[] args) {
max();
}
}
However I would discourage you from using static fields in this case. I would suggest you to make i, j and k parameters to your method. And give them descriptive names while you're at it.
Also note that k is not initialised explicitly and is therefore set to 0 by default, so your else clause is never reached.
Related
When I pass the array "bucky" to the change function and in the change function if I use an enhanced for loop, the variable counter gives the error "The value of the local variable counter is not used"
But if I put the body of the for loop in an System.out.println(counter+=5) the error does not appear
class apples{
public static void main(String[] args) {
int bucky[]={3,4,5,6,7};
change(bucky);
}
public static void change(int x[]){
for(int counter: x){
counter+=5;
}
}
}
Why does this code give the error I mentioned above since I'm using the counter variable in the enhanced for loop?
Edit - my objective is to change values of the array inside the "change" function and return it back to main.
Question is about updating original array values, then you have to use normal for loop so that each index values can be updated:
class apples{
public static void main(String[] args) {
int bucky[]={3,4,5,6,7};
bucky = change(bucky);
for(int b:bucky) {
System.out.println(b);
}
}
public static void change(int x[]){
for (int i = 0; i < x.length; i++) {
x[i]=x[i]+5;
}
return x;
}
}
How do i print the value of variable which is defined inside another method?
This might be a dumb question but please help me out as i am just a beginner in programming
public class XVariable {
int c = 10; //instance variable
void read() {
int b = 5;
//System.out.println(b);
}
public static void main(String[] args) {
XVariable d = new XVariable();
System.out.println(d.c);
System.out.println("How to print value of b here? ");
//d.read();
}
}
You can't. b is a local variable. It only exists while read is executing, and if read executes multiple times (e.g. in multiple threads, or via recursive calls) each execution of read has its own separate variable.
You might want to consider returning the value from the method, or potentially using a field instead - it depends on what your real-world use case is.
The Java tutorial section on variables has more information on the various kinds of variables.
You need to return value from your read() methods.
public class XVariable {
int c = 10; //instance variable
int read() {
int b = 5;
return b;
}
public static void main(String[] args) {
XVariable d = new XVariable();
System.out.println(d.c);
System.out.println(read());
//d.read();
}
}
Return b from the read method and print it
public class XVariable {
int c = 10; //instance variable
int read() {
int b = 5;
return b;
}
public static void main(String[] args) {
XVariable d = new XVariable();
System.out.println(d.c);
System.out.println(d.read());
}
}
I just started with java and I create a class Range() inside my superclass with a method inside makeRange but when I tried to access to that method throws an error. Whats wrong here?
Here is my code...
public class iAmRichard {
class Range{
int[] makeRange(int upper, int lower){
int[] ary = new int[(upper - lower)+1];
for(int i = 0; i > ary.length; i++ ){
ary[i] = lower++;
}
return ary;
}
}
public static void main(String[] args) {
int foo[];
Range fui = new Range();
foo = Range.(here do not apear makeRange method)
You're creating an inner class here called Range. I don't believe that's what you intended to do, but I'll answer it as stated.
You're referring to this class in a static context, and the inner class can't be referenced with a static context. To address that, you need to make the change to Range: make it static.
public class iAmRichard {
static class Range {
}
}
Further, you're already getting an instance of Range, so all you need to do is use it.
foo = fui.makeRange(1, 10);
If you elected to only create a class called Range, you wouldn't have to deal with any inner classes at all, which I think would be the cleaner approach here.
public class Range {
int[] makeRange(int upper, int lower) {
int[] ary = new int[(upper - lower) + 1];
for (int i = 0; i > ary.length; i++) {
ary[i] = lower++;
}
return ary;
}
public static void main(String[] args) {
int foo[];
Range fui = new Range();
foo = fui.makeRange(1, 10);
}
}
To access a method without creating an instance you have to declare it static. In your case you have also to declare the class Range as static.
Or you can just use the instance you already have with a few changes:
iAmRichard richard=new iAmRichard();
Range fui=richard.new Range();
foo = fui.makeRange(...);
Note tha you need an instance of iAmRichard to create a Range.
Since the call is made from a static block in a static way(No instance is used for calling makeRange method) we need to have the called method to be either static or we need the object of the class to call instance methods.
statically you can use this example to access your method. Here is a link for more information on static methods.
public class IAmRichard {
public static void main(String[] args) {
int foo[];
foo = Range.makeRange(10,1);
}
static class Range{
static int[] makeRange(int upper, int lower){
int[] ary = new int[(upper - lower)+1];
for(int i = 0; i > ary.length; i++ ){
ary[i] = lower++;
}
return ary;
}
}
}
Can I pass the return value from a method into the main method then utilize that value in another method? That sounds confusing but let me try to explain it better with some code...
public static void main(String[] args){
ArrayList<GeometricObject> geoList = new ArrayList<GeometricObject>();
findPositionLargestObject(geoList);
System.out.println("BIGGEST OBJECT AT "+ maxIndex +" AREA =
"+geoList.get(maxIndex).getArea());
showObjects(geoList.get(maxIndex));
}
//METHOD RETRIEVING INT OF ARRAYLIST
private static int findPositionLargestObject(
ArrayList<GeometricObject> geoList) {
int maxIndex = 0;
for (int i = 1; i < geoList.size(); i++) {
// AREA OF I COMPARES MAX INDEX
if (geoList.get(i).getArea() > geoList.get(maxIndex).getArea()) {
maxIndex = i;
}
}
return maxIndex;
}
// METHOD FOR PRINTING SINGLE OBJECT OF ARRAYLIST
private static void showObjects(GeometricObject geometricObject) {
System.out.println(geometricObject.toString());
}
Lets say I even instantiate the index in the main method such as
int maxIndex = 0;
I want the first method called to return the value, assign that value to the variable maxIndex then utilize that value for the showObjects method. Thanks for any insight that can be given to a coding novice like myself. Is instantiating the variable in the main method no good? What is the logic behind the JAVAC execution here?? The curriculum covered in my course feels like this is an enormous hole that needs to be filled. Basically, How do I utilize a value returned from a method then implement into another method?
Variables are only containers for a value bound to its type. If a method is returning a type, you can place it's return value in a variable located in another block of code. To provide a very basic example for an easier understanding of how this can work:
private String getString(int number) {
if (number == 2) {
return "Not One";
}
return "One";
}
private void printValue(String number) {
if (number.equals("One")) {
System.out.println("i is 1");
} else {
System.out.println("i is not one");
}
}
public static void main(String[] args) {
int i = 1;
String testNum = getString(i);//returns "One"
printValue(testNum);//output: i is 1
}
With this example in mind,
int maxIndex = findPositionLargestObject(geoList);
showObjects(geoList.get(maxIndex));
is valid.
Unless I'm missing something, assign the result of your function call. I suggest you program to the List interface. Also, if using Java 7+ you could use the diamond operator <> like
List<GeometricObject> geoList = new ArrayList<>(); // <-- diamond operator
// ... populate your List.
int maxIndex = findPositionLargestObject(geoList);
and then yes you can use the variable maxIndex
you can obtain the return value in main method like this,
int maxIndex=findPositionLargestObject(geoList);
Code:
public static void main(String[] args){
ArrayList<GeometricObject> geoList = new ArrayList<GeometricObject>();
int maxIndex=findPositionLargestObject(geoList);
System.out.println("BIGGEST OBJECT AT "+ maxIndex +" AREA =
"+geoList.get(maxIndex).getArea());
showObjects(geoList.get(maxIndex));
}
//METHOD RETRIEVING INT OF ARRAYLIST
private static int findPositionLargestObject(
ArrayList<GeometricObject> geoList) {
int maxIndex = 0;
for (int i = 1; i < geoList.size(); i++) {
// AREA OF I COMPARES MAX INDEX
if (geoList.get(i).getArea() > geoList.get(maxIndex).getArea()) {
maxIndex = i;
}
}
return maxIndex;
}
// METHOD FOR PRINTING SINGLE OBJECT OF ARRAYLIST
private static void showObjects(GeometricObject geometricObject) {
System.out.println(geometricObject.toString());
}
It's a requirement of my school assignment that I use "this" in the following program. However, I can't quite figure out where I could put this. I keep getting a "non-static variable this cannot be referenced from a static context" error.
import java.util.Scanner;
public class PrimeNumber
{
public static void main(String args[])
{
System.out.println("Enter the upper limit for the prime numbers computation: ");
int upperLimit = new Scanner(System.in).nextInt();
int count = 0;
for(int number = 2; number<=upperLimit; number++)
{
if(isPrime(number))
{
System.out.println(number);
count++;
}
}
System.out.println("Number of primes generated: " + count);
}
public static boolean isPrime(int number)
{
for(int i=2; i<number; i++)
{
if(number%i == 0)
{
return false;
}
}
return true;
}
}
The Java keyword this refers to the instance of your class that invoked an instance method. A static method is general to its class, and so you cannot reference any instance (non-static) variables from within it. You can only access instance variables like this from within an instance method, that is, a method that is not defined as static.
So, you would need to create an instance method (of which there are none in your class), in order to use this.
This is nothing more than a reference to the object on which the method was called. Static methods on the other hand can operate without any instance of the class even exisiting, therefore they can't have reference to any object. That's why you can't use this in static method. If you really need this, you have to remove static keywords from your functions and use instance variables in those functions anyhow.
public class PrimeNumber
{
public int count = 0;
public int upperLimit;
public static void main(String args[])
{
PrimeNumber pn = new PrimeNumber();
System.out.println("Enter the upper limit for the prime numbers computation: ");
pn.upperLimit = new Scanner(System.in).nextInt();
pn.doCheck();
System.out.println("Number of primes generated: " + pn.count);
}
public void doCheck() {
for (int number = 2; number <= this.upperLimit; number++)
{
if (this.isPrime(number))
{
System.out.println(number);
count++;
}
}
}
public boolean isPrime(int number)
{
for (int i = 2; i < number; i++)
{
if (number % i == 0)
{
return false;
}
}
return true;
}
}