Error compiling this code

Could you tell me what i'm doing wrong with this code? I posted earlier for inputting char into a variable, but the post just got too long.
I've tried below with code, but I can't get it right. Can you help me..?
import java.io.*;
public class Goals {
public static void main (String args[]) {
System.out.println("Enter time and tide:");
InputStreamReader reader = new InputStreamReader (System.in);
char ch = reader.read(char); // trying to read character from keyboard
System.out.println("the character" +ch);
This is my error here:
Goals.java:13: '.class' expec
char ch = reader.read(char);
^
Goals.java:13: ')' expected
char ch = reader.read(char);
^
thank you...
yash

The read method that you want to use does not accept any argument, so the syntax you want is char ch = reader.read();
The first error is caused because the compiler is not expecting to see the reserved word "char" at that point. It knows that the only way the code would be valid is that char was followed by .class, so it suggests it. The second error seems to be a ripple effect of the first one and gets fixed when you fix the first one.
Once you fix that error you get another, warning you about loss of precision. This is because the read() method returns an int and you are trying to assign an int in a char, while it's well known that there are plenty of integer values that don't fit in a char. Why does Reader.read() return an int instead of char? Because it needs a way to signal the end of the stream. In a normal case the read method returns the character that was read, but -1 if the end of the stream has been reached.
One way to fix this would be casting the int value to char, which erroneously interpretes the end of the stream as a char too:
char ch = (char) reader.read();

Similar Messages

  • RUN TIME ERROR IN THIS CODE

    HELLO EVERY ONE ...
    I AM GETTING run time error in this code.....can u send me the corrected code....
    START-OF-SELECTION.
    SELECT T1~MATNR
           T1~MEINS
           T1~ERSDA
           T1~ERNAM
           T1~SPART
           T2~MAKTX
           T3~LVORM
           T3~EKGRP
           T3~WERKS
           T4~LABST
           T4~SPEME
           T4~LGORT
           INTO CORRESPONDING FIELDS OF TABLE ITAB
           FROM MARA AS T1
           INNER JOIN MAKT AS T2
           ON T1MATNR = T2MATNR
           INNER JOIN MARC AS T3
           ON T2MATNR = T3NFMAT
           INNER JOIN MARD AS T4
           ON T3MATNR = T4MATNR
           WHERE T1~MATNR IN SMATNR.
    Thanx & Regards,
    PHANINDER

    ok i am sending u the full code.....
    REPORT  Z_SB_RP_MATERIAL.
    TABLES: MARA,
            MARD,
            MAKT,
            MARC,
            EINA,
            EINE.
    DATA: BEGIN OF ITAB OCCURS 15,
          MATNR LIKE MARA-MATNR,
          MEINS LIKE MARA-MEINS,
          ERSDA LIKE MARA-ERSDA,
          ERNAM LIKE MARA-ERNAM,
          SPART LIKE MARA-SPART,
          MAKTX LIKE MAKT-MAKTX,
          LVORM LIKE MARC-LVORM,
          EKGRP LIKE MARC-EKGRP,
          WERKS LIKE MARC-WERKS,
          LABST LIKE MARD-LABST,
          SPEME LIKE MARD-SPEME,
          LGORT LIKE MARD-SPEME,
          END OF ITAB.
    SELECTION-SCREEN BEGIN OF BLOCK BLK WITH FRAME TITLE TEXT-T01.
    SELECT-OPTIONS: SMATNR FOR MARA-MATNR,
                    SERSDA FOR MARA-ERSDA,
                    SWERKS FOR MARC-WERKS,
                    SLGORT FOR MARD-LGORT.
    SELECTION-SCREEN END OF BLOCK BLK.
    TOP-OF-PAGE.
    WRITE:/ SY-VLINE,
          02 'S.NO',
          06 SY-VLINE,
          08 'MATNR',
          20 SY-VLINE,
          22 'MEINS',
          32 SY-VLINE,
          34 'ERSDA',
          44 SY-VLINE,
          46 'ERNAM',
          56 SY-VLINE,
          58 'SPART',
          68 SY-VLINE,
          70 'MAKTX',
          80 SY-VLINE,
          82 'LVORM',
          92 SY-VLINE,
          94 'EKGRP',
         104 SY-VLINE,
         106 'WERKS',
         116 SY-VLINE,
         118 'LABST',
         128 SY-VLINE,
         130 'SPEME',
         140 SY-VLINE,
         142 'LGORT',
         152 SY-VLINE.
    START-OF-SELECTION.
    SELECT T1~MATNR
           T1~MEINS
           T1~ERSDA
           T1~ERNAM
           T1~SPART
           T2~MAKTX
           T3~LVORM
           T3~EKGRP
           T3~WERKS
           T4~LABST
           T4~SPEME
           T4~LGORT
           INTO CORRESPONDING FIELDS OF TABLE ITAB
           FROM MARA AS T1
           INNER JOIN MAKT AS T2
           ON T1MATNR = T2MATNR
           INNER JOIN MARC AS T3
           ON T2MATNR = T3NFMAT
           INNER JOIN MARD AS T4
           ON T3MATNR = T4MATNR
           WHERE T1~MATNR IN SMATNR.
    END-OF-SELECTION.
    DATA: COUNT(4) TYPE N.
    LOOP AT ITAB.
    COUNT = COUNT + 1.
      WRITE:/ SY-VLINE,
          02 COUNT,
          06 SY-VLINE,
          08 ITAB-MATNR,
          20 SY-VLINE,
          22 ITAB-MEINS,
          32 SY-VLINE,
          34 ITAB-ERSDA,
          44 SY-VLINE,
          46 ITAB-ERNAM,
          56 SY-VLINE,
          58 ITAB-SPART,
          68 SY-VLINE,
          70 ITAB-MAKTX,
          80 SY-VLINE,
          82 ITAB-LVORM,
          92 SY-VLINE,
          94 ITAB-EKGRP,
         104 SY-VLINE,
         106 ITAB-WERKS,
         116 SY-VLINE,
         118 ITAB-LABST,
         128 SY-VLINE,
         130 ITAB-SPEME,
         140 SY-VLINE,
         142 ITAB-LGORT,
         152 SY-VLINE.
    ENDLOOP.
    THANX & REGARDS,
    PHANINDER

  • Is there a error with this code

    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    public class ClickMe extends Applet implements MouseListener {
    private Spot spot = null;
    private static final int RADIUS = 7;
    public void init() {
    addMouseListener(this);
    public void paint(Graphics g) {
    //draw a black border and a white background
    g.setColor(Color.white);
    g.fillRect(0, 0, getSize().width - 1, getSize().height - 1);
    g.setColor(Color.black);
    g.drawRect(0, 0, getSize().width - 1, getSize().height - 1);
    //draw the spot
    g.setColor(Color.red);
    if (spot != null) {
    g.fillOval(spot.x - RADIUS, spot.y - RADIUS, RADIUS * 2, RADIUS * 2);
    public void mousePressed(MouseEvent event) {
    if (spot == null) {
    spot = new Spot(RADIUS);
    spot.x = event.getX();
    spot.y = event.getY();
    repaint();
    public void mouseClicked(MouseEvent event) {}
    public void mouseReleased(MouseEvent event) {}
    public void mouseEntered(MouseEvent event) {}
    public void mouseExited(MouseEvent event) {}
    When I compile the the code I get a "cannot resolve symbol"
    private Spot spot = null;
    spot = new Spot(RADIUS);
    I don't know if these are errors in the code

    'cannot resolve symbol' errors usually mean a problem with the declarations and initialisations at the start of your class. This is specifically to do with your line private Spot spot = null;
    i haven`t much time to look at your code, but i would suggest getting rid of the null initialisation here, and do you ever actually change this value? after a quick look it seems that you only query it to see if the variable spot is null. if you never affect this value, then it will always be null and only one if statement will ever be executed.
    but as i said i haven`t any time, so could be off here
    boutye - boss is coming bak argh!

  • See my error against this code jasperPrint = JasperFillManager.fillReport(s

    sir i use this code for without database report
    jasperPrint = JasperFillManager.fillReport(stream, new HashMap(), new JREmptyDataSource());
    and comple then output window give me this error
    C:Documents and SettingsAdministratorMy DocumentsCreatorProjectswithoutdatasourceireportsrcwithoutdatasourceireportPage1.java:390: unreported exception net.sf.jasperreports.engine.JRException; must be caught or declared to be thrown
    jasperPrint = JasperFillManager.fillReport(stream, new HashMap(), new JREmptyDataSource());
    1 error
    C:Documents and SettingsAdministratorMy DocumentsCreatorProjectswithoutdatasourceireportnbprojectbuild-impl.xml:233: The following error occurred while executing this line:
    C:Documents and SettingsAdministratorMy DocumentsCreatorProjectswithoutdatasourceireportnbprojectbuild-impl.xml:122: Compile failed; see the compiler error output for details.
    BUILD FAILED (total time: 13 seconds)
    see all error and
    plese give me idea
    thank's
    aamir

    See your other thread on the same topic
    Re: jsp give me this error javax.servlet.ServletException: oracle.jdbc.driv

  • Errors compiling AS3 code - seeking advice please

    Hi,
    I am trying to run this AS code from wonderfl.net:
    http://wonderfl.net/c/9Lit/
    I have downloaded the right files to ensure this works:
    import net.wonderfl.utils.FontLoader;
    import com.bit101.components.*;
    But when I compile the code in an AS3 project in Flash CS4, I get a tonne of errors shown in the image below.
    I can't find much info on the wonderfl site, and the author is japanese, and I can't get through to his site to ask for advice.
    Might the errors be because the code is for Flash Player 11?
    I'm really keen to work on this code, but have hit a big brick wall.
    Any help much appreciated.
    Thanks

    Hi,
    The code creates the effect shown here:
    http://wonderfl.net/c/9Lit/
    It doesn't do anything "useful" - it's just a nice effect, where it loops through the letters in some text and generates a pretty swirly pattern for each one.
    On the page above, click on the play button in the right-hand window, and that will run the SWF that is generated by the AS on the left hand side.
    I guess it means that the AS on the left hand side isn't actually correct, since when running it in flash, it doesn't work.
    I zipped up the source files I used when working on the code in case you want a peek:
    http://jimpix.co.uk/typography.zip
    Thanks

  • Error in this code - javafx

    Sorry for the question but I'm a newbie
    I have this code:
    http://weblogs.java.net/blog/brunogh/archive/2007/09/my_first_fx_blu_1.html
    Button {
                                 text: "Inquiry"
                                 enabled : bind model.inquiryBtnEnabled
                                 action: operation() {
                                    DeviceDiscoverer.getInstance().startInquiry(DiscoveryAgent.GIAC, model.inquiryListener);
                                    model.foundDevices = null;
                                    model.inquiryBtnEnabled = false;
                                    model.cancelBtnEnabled = true;
                                 }what is the error?
    Thanks.
    And sorry for my english, too.

    Hi Gigi_One,
    this code was posted in 2007.. If you're using the Preview version, you must switch "operation" to "function"...
    Are there an error message?
    Bruno Grossi

  • Error in this code?

    hi friends,
    when I run this code it is giving error as
    Cause: FDPSTP failed due to ORA-01427: single-row subquery returns more than one row
    ORA-06512: at "APPS.UPD_VAC", line 18
    ORA-06512: at line 1
    can some one suggest a solution pls
    the table vac_table has a single column... and it has only 1 record right now
    CREATE OR REPLACE package body APPS.upd_vac is
    procedure upd_prc(p_err_buf out VARCHAR2
    ,p_ret_code out NUMBER)
    is
    l_attr varchar2(100);
    l_attr1 varchar2(100);
    l_attr2 varchar2(100);
    l_attr3 varchar2(100);
    l_attr4 varchar2(100);
    begin
    SELECT MAX(ATTRIBUTE18) INTO L_ATTR FROM PER_VACANCIES;
    select (regexp_substr (l_attr, '.*C')) into l_attr1 from dual;
    select regexp_replace(l_attr,'^.*C(.+)$','\1') into l_attr2 from dual;
    select to_number(l_attr2)+1 into l_attr3 from dual;
    select l_attr1||l_attr3 into l_attr4 from dual;
    insert into vac_table
    (select l_attr4 from dual);
    UPDATE PER_VACANCIES SET ATTRIBUTE18 =(select attribute from kdd_vacancy)
    where vacancy_id =(select max(vacancy_id) from per_vacancies);
    commit;
    end;
    end;

    CREATE OR replace PACKAGE BODY apps.upd_vac
    IS
      PROCEDURE Upd_prc(p_err_buf  OUT VARCHAR2,
                        p_ret_code OUT NUMBER)
      IS
        l_attr  VARCHAR2(100);
        l_attr1 VARCHAR2(100);
        l_attr2 VARCHAR2(100);
        l_attr3 VARCHAR2(100);
        l_attr4 VARCHAR2(100);
      BEGIN
        SELECT MAX(attribute18)
        INTO   l_attr
        FROM   per_vacancies;
        SELECT ( Regexp_substr (l_attr, '.*C') )
        INTO   l_attr1
        FROM   dual;
        SELECT Regexp_replace(l_attr, '^.*C(.+)$', '\1')
        INTO   l_attr2
        FROM   dual;
        SELECT To_number(l_attr2) + 1
        INTO   l_attr3
        FROM   dual;
        SELECT l_attr1
               ||l_attr3
        INTO   l_attr4
        FROM   dual;
        INSERT INTO vac_table
        (SELECT l_attr4
         FROM   dual);
        UPDATE per_vacancies
        SET    attribute18 = (SELECT attribute FROM   kdd_vacancy)
        WHERE  vacancy_id = (SELECT MAX(vacancy_id)
                             FROM   per_vacancies);
        COMMIT;
      END;
    END; 
    (SELECT attribute FROM kdd_vacancy)must return only a single row
    ATTRIBUTE18 is a scalar & can only accept one value; which is correct value FROM KDD_VACANCY?

  • ABAP Syntax error in this code - Could anyone help?

    Hi,
    I have this code which runs fine in our non-unicode SAP system.
    REPORT  ECC5_OFFSETS.
    DATA: W_KONV TYPE KONV.
    DATA: TKOMK LIKE STANDARD TABLE OF KOMK
                     WITH KEY KEY_UC
                     INITIAL SIZE 2
                     WITH HEADER LINE.
    DATA: TKOMK2 type STANDARD TABLE OF KOMK
                     WITH KEY KEY_UC
                     INITIAL SIZE 2.
    * Get some test data
    SELECT SINGLE * INTO W_KONV FROM  KONV
           WHERE  KNUMV  = '0000000061'.
    MOVE-CORRESPONDING W_KONV TO TKOMK.
    APPEND TKOMK.
    tkomk2[] = TKOMK[].
    * Original non-Unicode compliant code
    DATA: LENGTH_KEY_TKOMK(3) TYPE P.
    FIELD-SYMBOLS: <TKOMK_KEY> like TKOMK2.
    DESCRIBE DISTANCE BETWEEN TKOMK-MANDT AND TKOMK-SUPOS
              INTO LENGTH_KEY_TKOMK
    * ( Original Unicode syntax fix! )
              IN BYTE MODE.
    * Copy all the fields between these two into TKOMK_KEY field-symbol.
    * ( In Unicode this assignment fails, causing short dump at read )
    ASSIGN TKOMK2(LENGTH_KEY_TKOMK) TO <TKOMK_KEY>.
    * Read the current record.
    READ TABLE TKOMK2 WITH KEY <TKOMK_KEY>.
    But I get the following error message in our UNICODE complaint SAP system:
    <b>"<TKOMK_KEY>" cannot be a table, a reference, a string, or contain any of these objects.</b>     
    Does anyone know how I could get around this/suggest a solution?
    Thanks in advance!

    Hi,
    Sorry if I'm being unclear.
    My requirements are twofold:
    1)the line of code:
    ASSIGN TKOMK2(LENGTH_KEY_TKOMK) TO <TKOMK_KEY>
    does not assign anything to the fields symbol <TKOMK_KEY>
    2)The read statement does not like the fields symbol <TKOMK_KEY> being used as a key.
    Both these bits of code worked in our 4.6b system but now in the ECC5 environemtn I get syntax errors.
    Let me know if you need anything else!

  • Problem Compiling this code

    Hi all:-
    I know this question seems very basic, but i am really pissed out, so please help me out
    package somepackage;
    public class aClass {
            public static void method(){
                    System.out.println("Inside the aClass and method");
    }I have saved this file in aClass.java and its compiling and placed the class file in the somepackage directory.
    import somepackage.*;
    public class pTest {
            public static void main(String args[]){
                    System.out.println("Inside the main method");
                    aClass.method();
    }this class is saved in the pTest.java file and saved in the parent directory of somepackage. But when i compile this its giving me error such as:-
    pTest.java:7: cannot access aClass
    bad class file: ./aClass.java
    file does not contain class aClass
    Please remove or make sure it appears in the correct subdirectory of the classpath.
    aClass.method();
    ^
    1 error
    When i replace the import statement with this one this one import somepackage.aClass; its compiling and running.
    Am i missing out something ???
    Thanks in advance.
    Rajesh s

    Cross-post
    http://forum.java.sun.com/thread.jspa?threadID=618703

  • What is the error in this code

    hi everone
    I write this code in push button
         declare
              x varchar2(222);
         begin
              x:=get_application_property(:system.mode);
              message(x);
              end;
    to know the system mode
    but the resullt was exeception ora-06502

    simple write
    x := :system.mode;
    or
    message(:system.mode);
    message(:system.mode);Best way to resolve the issue is always check Forms online help first

  • Error compiling this example code of libcurl

    Its an example code to download a file and show gtk window..
    http://curl.haxx.se/libcurl/c/curlgtk.html
    I get this error:-
    shadyabhi@ArchLinux /tmp $ gcc curlgtk.c `pkg-config --libs --cflags libcurl`
    curlgtk.c:13:21: fatal error: gtk/gtk.h: No such file or directory
    compilation terminated.
    shadyabhi@ArchLinux /tmp $
    Then I tried :-
    shadyabhi@ArchLinux /tmp $ gcc curlgtk.c `pkg-config --libs --cflags libcurl` -I /usr/include/gtk-2.0/
    In file included from /usr/include/gtk-2.0/gdk/gdk.h:32:0,
    from /usr/include/gtk-2.0/gtk/gtk.h:32,
    from curlgtk.c:13:
    /usr/include/gtk-2.0/gdk/gdkapplaunchcontext.h:30:21: fatal error: gio/gio.h: No such file or directory
    compilation terminated.
    shadyabhi@ArchLinux /tmp $
    Whats the issue?
    The complete code:-
    /* Copyright (c) 2000 David Odin (aka DindinX) for MandrakeSoft */
    /* an attempt to use the curl library in concert with a gtk-threaded application */
    #include <stdio.h>
    #include <gtk/gtk.h>
    #include <curl/curl.h>
    #include <curl/types.h> /* new for v7 */
    #include <curl/easy.h> /* new for v7 */
    GtkWidget *Bar;
    size_t my_write_func(void *ptr, size_t size, size_t nmemb, FILE *stream)
    return fwrite(ptr, size, nmemb, stream);
    size_t my_read_func(void *ptr, size_t size, size_t nmemb, FILE *stream)
    return fread(ptr, size, nmemb, stream);
    int my_progress_func(GtkWidget *bar,
    double t, /* dltotal */
    double d, /* dlnow */
    double ultotal,
    double ulnow)
    /* printf("%d / %d (%g %%)\n", d, t, d*100.0/t);*/
    gdk_threads_enter();
    gtk_progress_set_value(GTK_PROGRESS(bar), d*100.0/t);
    gdk_threads_leave();
    return 0;
    void *my_thread(void *ptr)
    CURL *curl;
    CURLcode res;
    FILE *outfile;
    gchar *url = ptr;
    curl = curl_easy_init();
    if(curl)
    outfile = fopen("test.curl", "w");
    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, outfile);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_write_func);
    curl_easy_setopt(curl, CURLOPT_READFUNCTION, my_read_func);
    curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
    curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, my_progress_func);
    curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, Bar);
    res = curl_easy_perform(curl);
    fclose(outfile);
    /* always cleanup */
    curl_easy_cleanup(curl);
    return NULL;
    int main(int argc, char **argv)
    GtkWidget *Window, *Frame, *Frame2;
    GtkAdjustment *adj;
    /* Must initialize libcurl before any threads are started */
    curl_global_init(CURL_GLOBAL_ALL);
    /* Init thread */
    g_thread_init(NULL);
    gtk_init(&argc, &argv);
    Window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    Frame = gtk_frame_new(NULL);
    gtk_frame_set_shadow_type(GTK_FRAME(Frame), GTK_SHADOW_OUT);
    gtk_container_add(GTK_CONTAINER(Window), Frame);
    Frame2 = gtk_frame_new(NULL);
    gtk_frame_set_shadow_type(GTK_FRAME(Frame2), GTK_SHADOW_IN);
    gtk_container_add(GTK_CONTAINER(Frame), Frame2);
    gtk_container_set_border_width(GTK_CONTAINER(Frame2), 5);
    adj = (GtkAdjustment*)gtk_adjustment_new(0, 0, 100, 0, 0, 0);
    Bar = gtk_progress_bar_new_with_adjustment(adj);
    gtk_container_add(GTK_CONTAINER(Frame2), Bar);
    gtk_widget_show_all(Window);
    if (!g_thread_create(&my_thread, argv[1], FALSE, NULL) != 0)
    g_warning("can't create the thread");
    gdk_threads_enter();
    gtk_main();
    gdk_threads_leave();
    return 0;

    Your error is unrelated to curl. You're not properly linking against gtk
    gcc curlgtk.c $(pkg-config --libs --cflags gtk+-2.0 libcurl)

  • Why no compile  error in this code ?

    strings are immutable... we can not alter it... so why the below does not create compile error ? it is an attempt to alter the string.
    class test
    public static void main(String args[])
        String s1 = new String("amit");
        s1.concat("Poddar");    // why no error ?
        System.out.println(s1);
    }

    strings are immutable... we can not alter it... so
    why the below does not create compile error ? First of all, Strings are immuatable because the String class is coded that way - there willnever be a compiler error to stop you from altering a String's value (which is actually possible via reflection). This is similar to you writing your own class that has a private field and not providing any methods that can alter the field's value. Your new class would be considered immutable in the same way that Strings are considered immutable, and nobody can even attempt (except reflectively), to "alter" an instance of it, so there will never be a compiler error that is due to such an attempt.
    it is an attempt to alter the string.No it isn't. The following is a quote from the Javadoc for String.concat:
    "If the length of the argument string is 0, then this String object is returned. Otherwise, a new String object is created, representing a character sequence that is the concatenation of the character sequence represented by this String object and the character sequence represented by the argument string."

  • Can't compile this code! can't tell why. Error message is below. Thanks

    import java.util.*;
    public class Library {
            private Collection books;                                               //Defining a collection of books here
            private Iterator bookIter;                                              //We want to iterate the collection of books here
            //Constructor to help us initialize our collection to hold elements of a newly created collection
            public Library() {
                    books = new ArrayList();                                        //Our collection holds a the newly created collection of type ArrayList (providing storage for books)
                    books.add(new Book("War and Crime"));
                    books.add(new Book("The Redeemers"));
            public void display() {
                    bookIter = books.iterator();
                    while (bookIter.hasNext()) {
                            Book aBook = (Book)bookIter.next();
                            System.out.println("Title : " + aBook.ret_title());
            public static void main(String args[]) {
                    display();
    class Book {
            private String title;
            Book(String b_title) {
                    this.title = b_title;
            public String ret_title() {
                    return this.title;
    }THIS IS THE ERROR:
    "Library.java" 105 lines, 3597 characters
    clio:~/javamachine/learning/topics/utils/Collection (Lord G.) % javac Library.java
    Library.java:91: non-static method display() cannot be referenced from a static context
    display();
    ^
    1 error
    Thanks for helping!
    BR,
    G-Afric

    Hi folkenf,
    I tried what you recommended already but the result was even more timidating.
    public static void display()ERROR OUTPUT NOW IS:
    Library.java:83: non-static variable bookIter cannot be referenced from a static context
    bookIter = books.iterator();
    ^
    Library.java:83: non-static variable books cannot be referenced from a static context
    bookIter = books.iterator();
    ^
    Library.java:84: non-static variable bookIter cannot be referenced from a static context
    while (bookIter.hasNext()) {
    ^
    Library.java:85: non-static variable bookIter cannot be referenced from a static context
    Book aBook = (Book)bookIter.next();
    ^
    4 errors
    I fixed this error by making books and bookIter static but now main() complains
    of null pointer as shown below:
    Runtime error:
    Exception in thread "main" java.lang.NullPointerException
    at Library.main(Library.java:89)
    Thanks!
    BR,
    G-Afric

  • HELP! Run-time Error with this code.

    I'm having problem with the code below. But if I were to remove the writer class and instances of it (writeman), then there are no problems. Can some1 pls tell me why the writer class is giving problems. Btw, no compilation errors, only errors at run-time..........
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.MouseListener;
    import java.awt.event.*;
    public class HelloWorld extends Applet
    public static String MyString = new String("Hello");
    Graphics f;
    public void init()
    Changer Changer1 = new Changer();
    writer writeman = new writer();
    setBackground(Color.red);
    setForeground(Color.green);
    addMouseListener(Changer1);
    writeman.paintit(f);
    public void paint(Graphics g)
    g.drawString(MyString,10 ,10);
    public class Changer implements MouseListener
    public void mouseEntered(MouseEvent e)
    setBackground(Color.blue);
    MyString = "HI";
    paint(f);
    repaint();
    public void mouseExited(MouseEvent e)
    setBackground(Color.red);
    repaint();
    public void mousePressed(MouseEvent e){};
    public void mouseReleased(MouseEvent e){};
    public void mouseClicked(MouseEvent e){};
    public class writer
    public void paintit(Graphics brush)
    brush.drawString("can u see me", 20, 20);

    I assume the exception you are getting is a NullPointerException...
    When you applet is loaded, it is initialised with a call to init... the following will then occur...
    HelloWorld.init()
    writeman.paintit(f)
    // f has not been initialised, so is null
    brush.drawString("can u see me", 20, 20)
    // brush == f == null, accessing a null object causes a NullPointerException!
    The simplest way to rectify this is to not maintain your own reference to the Graphics object. Move the writer.paintit(f) method to the HelloWorld.paint(g) method, and pass in the given Graphics object. Also, change the paint(f) call in Changer to repaint(), which will cause the paint method to be called with a valid Graphics object - which will then be passed correctly to writer.
    Hope this helps,
    -Troy

  • There and error in this code

    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    public class ClickMe extends Applet implements MouseListener {
    private Spot spot = null;
    private static final int RADIUS = 7;
    public void init() {
         addMouseListener(this);
    public void paint(Graphics g) {
         //draw a black border and a white background
    g.setColor(Color.white);
         g.fillRect(0, 0, getSize().width - 1, getSize().height - 1);
    g.setColor(Color.black);
         g.drawRect(0, 0, getSize().width - 1, getSize().height - 1);
         //draw the spot
    g.setColor(Color.red);
         if (spot != null) {
         g.fillOval(spot.x - RADIUS, spot.y - RADIUS, RADIUS * 2, RADIUS * 2);
    public void mousePressed(MouseEvent event) {     
    if (spot == null) {
    spot = new Spot(RADIUS);
         spot.x = event.getX();
         spot.y = event.getY();
         repaint();
    public void mouseClicked(MouseEvent event) {}
    public void mouseReleased(MouseEvent event) {}
    public void mouseEntered(MouseEvent event) {}
    public void mouseExited(MouseEvent event) {}
    When I compile the the code I get a "cannot resolve symbol"
    private Spot spot = null;
    spot = new Spot(RADIUS);
    I'm new to programming and I don't know if these are errors in the code

    The compiler doesn't know what "Spot" is. It isn't in any of the packages you imported (java.awt.*, etc), so I'm assuming it's another class you wrote. At compile time, the compiler must be able to find that class, so it's looking for a file named Spot.class in your CLASSPATH. I think you just have a simple classpath problem that all beginners run into. If you don't have a Spot class, then it's a different problem. Maybe you meant to declare the "spot" variable as a different thing?

Maybe you are looking for