Problem with Java code

Discussion in 'Programmer's Corner' started by krow, Aug 4, 2011.

  1. krow

    Thread Starter Member

    May 25, 2010
    49
    0
    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;
    }
    }
    }
     
  2. kavli

    New Member

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

    Code ( (Unknown Language)):
    1.  
    2. import java.util.*;
    3.  
    4. public class NewClass {
    5.  
    6.   static Scanner ms = new Scanner (System.in);
    7.   public static boolean printComma = false;
    8.  
    9.   public static void read(){
    10.     int x;
    11.     System.out.println("-----");
    12.     x = ms.nextInt();
    13.     if(x != 0) {
    14.       read();
    15.       if(printComma)
    16.         System.out.println(" , ");
    17.       System.out.print(x);
    18.       printComma=true;
    19.     }
    20.   }
    21.  
    22.   public static void main(String[] args) {
    23.  
    24.     read();
    25.   }
    26. }
    27.  
    Your scanner needs to be declared static, since you're referencing it from a static context.

    -- K
     
  3. krow

    Thread Starter Member

    May 25, 2010
    49
    0
    Thanks man!

     
Loading...