Problem with Java code

Thread Starter

krow

Joined May 25, 2010
49
I guess this is pretty easy to spot but I don't know how to fix it, can anyone tell me what's wrong in the code? how can I get the scanner to run inside the read() method ???


import java.util.*;


public class NewClass {

Scanner ms = new Scanner (System.in);
public static boolean printComma = false;

public static void main(String[] args) {

read();
}


public static void read(){

int x;
System.out.println("-----");
x= ms.nextInt();
if(x!=0){
read();
if(printComma)System.out.println(" , ");
System.out.print(x);
printComma=true;
}
}
}
 

kavli

Joined Aug 1, 2011
23
To get your program to compile, rewrite it like this:

Rich (BB code):
import java.util.*;

public class NewClass {

  static Scanner ms = new Scanner (System.in);
  public static boolean printComma = false;

  public static void read(){
    int x;
    System.out.println("-----");
    x = ms.nextInt();
    if(x != 0) {
      read();
      if(printComma)
        System.out.println(" , ");
      System.out.print(x);
      printComma=true;
    }
  }

  public static void main(String[] args) {

    read();
  }
}
Your scanner needs to be declared static, since you're referencing it from a static context.

-- K
 

Thread Starter

krow

Joined May 25, 2010
49
Thanks man!

To get your program to compile, rewrite it like this:

Rich (BB code):
import java.util.*;

public class NewClass {

  static Scanner ms = new Scanner (System.in);
  public static boolean printComma = false;

  public static void read(){
    int x;
    System.out.println("-----");
    x = ms.nextInt();
    if(x != 0) {
      read();
      if(printComma)
        System.out.println(" , ");
      System.out.print(x);
      printComma=true;
    }
  }

  public static void main(String[] args) {

    read();
  }
}
Your scanner needs to be declared static, since you're referencing it from a static context.

-- K
 
Top