How to access var in outter class inside inner class

I've problem with this, how to access var number1 and number2 at outter class inside inner class? what statement do i have to use to access it ? i tried with " int number1 = Kalkulator1.this.number1; " but there no value at class option var y when the program was running...
import java.io.*;
public class Kalkulator1{
int number1,number2,x;
/* The short way to create instance object for input console*/
private static BufferedReader stdin =
new BufferedReader( new InputStreamReader( System.in ) );
public static void main(String[] args)throws IOException {
System.out.println("---------------------------------------");
System.out.println("Kalkulator Sayur by Cumi ");
System.out.println("---------------------------------------");
System.out.println("Tentukan jenis operasi bilangan [0-4] ");
System.out.println(" 1. Penjumlahan ");
System.out.println(" 2. Pengurangan ");
System.out.println(" 3. Perkalian ");
System.out.println(" 4. Pembagian ");
System.out.println("---------------------------------------");
System.out.print(" Masukan jenis operasi : ");
String ops = stdin.readLine();
     int numberops = Integer.parseInt( ops );
System.out.print("Masukan Bilangan ke-1 : ");
String input1 = stdin.readLine();
int number1 = Integer.parseInt( input1 );
System.out.print("Masukan Bilangan ke-2 : ");
String input2 = stdin.readLine();
int number2 = Integer.parseInt( input2 );     
     Kalkulator1 op = new Kalkulator1();
Kalkulator1.option b = op.new option();
     b.pilihan(numberops);
System.out.println("Bilangan yang dimasukkan adalah = " + number1 +" dan "+ number2 );
class option{
int x,y;
     int number1 = Kalkulator1.this.number1;
     int number2 = Kalkulator1.this.number2;
void pilihan(int x) {
if (x == 1)
{System.out.println("Operasi yang digunakan adalah Penjumlahan");
        int y = (number1+number2);
        System.out.println("Hasil dari operasi adalah = " + y);}
else
{if (x == 2) {System.out.println("Operasi yang digunakan adalah Pengurangan");
         int y = (number1-number2);
         System.out.println("Hasil dari operasi adalah = " + y);}
else
{if (x == 3) {System.out.println("Operasi yang digunakan adalah Perkalian");
         int y = (number1*number2);
         System.out.println("Hasil dari operasi adalah = " + y);}
else
{if (x == 4) {System.out.println("Operasi yang digunakan adalah Pembagian ");
         int y = (number1/number2);
         System.out.println("Hasil dari operasi adalah =" + y);}
else {System.out.println( "Operasi yang digunakan adalah Pembagian ");
}

Delete the variables number1 and number2 from your inner class. Your inner class can access the variables in the outer class directly. Unless you need the inner and outer class variables to hold different values then you can give them different names.
In future place code tags around your code to make it retain formatting. Highlight code and click code button.

Similar Messages

  • How To Access JSP Image file Path inside JavaBean Class

    In my Webapplication,i have jsp and javabeans files. i need to send one image file path contains in Image folder to JavaBean[MyBean.java].
    From MyBean i am trying to display that image using PdfGen Application[JAR] in a new PDF Document.
    The Web Application Structure is as
    MyWebApp
    Image
    \ mypic.gif
    JSP
    \myjsp.jsp
    WEB-INF
    classes
    \pack.MyBean.java
    My Question :
    Inside the webapplication[JSP] the image file is accessed as a URL.(like http://localhost:7001/mywebapp/Image/mypic.gif). but From JavaBean: How To access this file? becz inside javabean it needs a complete system path..How to solve this problem? plz send me any solutions related to my problem....Thank U.

    Dear Madruguinha!
    Thank you very much for your tips.
    but i find another one method for accessing the image.
    // Inside Servlet or JSP
    String realPath=getServletContext().getRealPath("Image"+"/pic1.gif");
    Now we can send this exact system path variable to any java beans or java class that needs the image path as "drivename:\foldername\filename" like "c:\myflolder\mypic.gif" and not web context path.

  • How to access the int variable in the inner class

    hi all,
    i can't access the int variable in the inner class. can any one help me
    int count = 0;
    MouseMoveListener mouseMove = new MouseMoveListener() {
         public void mouseMove(MouseEvent e) {
              count1++;
              System.out.println(count);
    };how to access count variable
    thanks

    for this how can i access the countIf the count variable is a local variable you can't access it from within the
    inner class. Make it a member variable of the outer class instead:public class Outer {
       private int count;
       MouseMoveListener mouseMove= new MouseMoveListener() {
          public void mouseMove(MouseEvent me) {
             count++;
             System.out.println(count);
    }Alternatively, if you don't need that count variable anywhere else, you
    could simply make it a member variable of the inner class itself:public class Outer {
       MouseMoveListener mouseMove= new MouseMoveListener() {
          private int count;
          public void mouseMove(MouseEvent me) {
             count++;
             System.out.println(count);
    }kind regards,
    Jos

  • What is the relation between main class and inner classes

    hi
    i want to make a UML design and o want to know how to draw the relation betwwen the main public class and inner classes?
    and what is the relation?

    BaffyOfDaffyA wrote:
    Please keep in mind that if you spell better you will get better answers and if you add duke stars you will get better answers and if you mark the thread as a question you will get better answers. That will make it look like you are paying attention and that you really want an answer.
    My best answer based on your rather vague question:
    A minimal public class in a file named "Minimal.java" in the directory named "minimal":
    package minimal;
    public class Minimal {
    private int variable;
    public Minimal(int var) {
    variable = var;
    public int getVariable() {
    return variable;
    }This would be an example of adding an inner class:
    package minimal;
    public class Minimal {
    private int variable;
    public Minimal(int var) {
    variable = var;
    public int getVariable() {
    return variable;
    public class Inner {
    private int innerVariable;
    public Inner(int var) {
    innerVariable = var;
    public int getInnerVariable() {
    return innerVariable;
    }The inner class is exactly like any other inner class except if you are accessing it from anything else other than Minimal then you would have to add Minimal. right before Inner for example, where the Minimal class could use
    Inner inner = new Inner(5);other classes would have to use
    Minimal.Inner inner = new Minimal.Inner(5);
    See [Inner Class Example|http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html] or [Nested Classes|http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html] for more information.
    He is probably not asking what an inner class is or how to declare one in raw source code. To me he is asking how do I
    explain this relationship in a UML diagram and as UML is not and exact science and expression can vary a lot
    between UML design applications I didn't want to stab in the dark.
    @OP I would say whatever seems most logical to you and your team, write something that reads.

  • Help: Factory Class using Inner Class and Private Constructor?

    The situation is as follows:
    I want a GamesCollection class that instantiates Game objects by looking up the information needed from a database. I would like to use Game outside of GamesCollection, but only have it instantiated by GamesCollection to ensure the game actually exist. Each Game object is linked to a database record. If a Game object exist, it must also exist in the database. Game objects can never be removed from the database.
    I thought about making the Game object an inner class of GamesCollection, but this means that Game class constructor is still visible outside. So what if I made Game constructor private? Well, now I can't create Game objects without a static method inside Game class (static Object factory).
    Basically what I need is a constructor for the inner Game class accessible to GamesCollection, but not to the rest of the world (including packages). Is there a way to do this?

    leesiulung wrote:
    As a second look, I was initially confused about your first implementation, but it now makes more sense.
    Let me make sure I understand this:
    - the interface is needed to make the class accessible outside the outer classBetter: it is necessary to have a type that is accessible outside of GameCollection -- what else could be the return type of instance?
    - the instance() method is the object factory
    - the private modifier for the inner class is to prevent outside classes to instantiate this objectRight.
    However, is a private inner class accessible in the outer class? Try it and see.
    How does this affect private/public modifiers on inner classes?Take about five minutes and write a few tests. That should answer any questions you may have.
    How do instantiate a GameImpl object? This basically goes back to the first question.Filling out the initial solution:
    public interface Game {
        String method();
    public class GameCollection {
        private static  class GameImpl implements Game {
            public String method() {
                return "GameImpl";
        public Game instance() {
            return new GameImpl();
        public static void main(String[] args) {
            GameCollection app = new GameCollection();
            Game game = app.instance();
            System.out.println(game.method());
    }Even if you were not interested in controlling game creation, defining interfaces for key concepts like Game is always going to be a good idea. Consider how you will write testing code, for example. How will you mock Game?

  • HELP : How to access a datasource rowset in the AM class ?

    Hi,
    i have an AM "TestAM" which contains the viewobject "ViewTest".
    in the class "TestAMImpl.java" i added a method called "verify()".
    in my JSP i have initialised the AM and a datasource based on the VO "ViewTest" :
    <jbo:ApplicationModule id="am" configname="TestAM.TestAMLocal" releasemode="Stateful" />
    <jbo:DataSource id="ds" appid="am" viewobject="ViewTest" />
    <%
    TestAM am = (TestAM) am.useApplicationModule();
    String Message = am.verify();
    %>
    My question is how to access to the rowset of the datasource "ds" in the code of the method
    "verify()" ?
    public class TestAMImpl extends ApplicationModuleImpl implements TestAM {
    public String verify()
    How to access the rowset initialised in the JSP???????????
    Thanks for your help

    This is correct. Think of the AM as having a hashtable of instances of view objects that you can lookup by instance name.
    The <jbo:DataSource> tag lets you lookup an instance by name in the AM and get a reference to it to use in the JSP page. Within your AMImpl class, you can either:
    [list]
    [*]Call findViewObject("YourViewInstanceName"), or
    [*]Just call the generated getYourViewInstanceName() method which is ok to call inside the Impl class to get hold of the same VO.
    [list]

  • How to access super of enclosing class from inner class?

    Hello,
    I'd like to access Base.foo() from inner class in overridden Improved.foo(), but seem unable:
    public class InnerSuper {
         public static class Base {
              protected int foo() {
                   return 1;
         public static class Improved extends Base {
              @Override
              protected int foo() {
                   return Integer.parseInt(new Object () {
                        public String toString() {
                             return "1"+foo() ;
                   }.toString());
         public static void main(String[] args) {
              System.out.println(new Improved().foo());
    }The code above does not work, as it recursively calls Improved.foo() where I'd like it to call Base.foo(). What syntax construct should I use? Improved.this would be the same thing, Improved.super does not exist.
    I came up with a work around: adding a method baseFoo() to Improved and call that in the inner class:
       int baseFoo() {
          return super.foo();
       } but remain wondering if that is necessary?

    Indeed, Improved.super.foo() is allowed. My Eclipse syntax highlighting seems to have the same opinion as you: "are you sure you want to write that kind of code?" and leaves the read underlining for a syntax error on for just a second longer.
    This is where I am now:
         public static class DeferredExecSubroutineCall extends SubroutineCall {
              RelayExecutor relay;
              public DeferredExecSubroutineCall(RelayExecutor relay) {
                   this.relay = relay;
              @Override
              protected String execute(final IFDSOC fd, final String commandText) {
                   Future<String> f = relay.submit(new Callable<String>() {
                        @Override
                        public String call() throws Exception {
                             return DeferredExecSubroutineCall.super.execute(fd, commandText);
                   try {
                        return f.get();
                   } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                   } catch (ExecutionException e) {
                        if (e.getCause() instanceof RuntimeException) {
                             throw (RuntimeException) e.getCause();
                        } else {
                             throw new RuntimeException(e.getCause());
         }which is my current effort of adding concurrency to an existing project. I find it quite elegant but I am interested to hear from you...

  • HELP: Cannot refer to non-final variable inside inner class

    Below is a function that WAS working beautifully. I had to restructure many things in my code base to suit a major change and I have to make this function static. Since I made this function static, I get some errors which are displayed in comments next to the line of code.
    Can anyone offer any advice how to fix this?
    static private void patchSource( final Target target, final TargetResolver resolver, final TexSheetCommand args ) throws Exception
         boolean bDone = false;
         Element e;
         SAXReader sax          = new SAXReader();
         FileInputStream fis     = new FileInputStream( args.getInputFile() );
         Document document     = sax.read( fis );
         Element root = document.getRootElement();
         if( root.getName().equals( "Sheet" ) )
              XMLParser.iterateElements( root,     new XMLElementCallback()
                                                      public void onElement( Element element )
                                                           XMLParser.iterateAttributes( element,     new XMLAttributeCallback()
                                                                                                   public void onAttribute( Element element, Attribute attribute )
                                                                                                        if( attribute.getName().equals( "guid" ) )
                                                                                                             e = element; // PROBLEM: Cannot refer to a non-final variable e inside an inner class defined in a different method
                                                                                                             // WARNING: Type safety: The expression of type Iterator needs unchecked conversion to conform to Iterator<Attribute>
                                                                                                             for( Iterator<Attribute> it = element.attributeIterator(); it.hasNext(); )
                                                                                                                  Attribute a = (Attribute)it.next();
                                                                                                                  if( a.getName().equals( "randOffset" ) )
                                                                                                                       Integer i = new Integer( resolver.getTotalPermutations() );
                                                                                                                       a.setValue( i.toString() );
                                                                                                                       bDone = true; // PROBLEM: Cannot refer to a non-final variable bDone inside an inner class defined in a different method
              if( ( !bDone ) && ( e != null ) )
                   Integer i = new Integer( resolver.getTotalPermutations() );
                   e.addAttribute( "randOffset", i.toString() );                                                                                                                                            
         FileOutputStream fileOut     = new FileOutputStream( args.getInputFile() );          
         OutputFormat format               = OutputFormat.createPrettyPrint();          
            XMLWriter xmlWriter               = new XMLWriter( fileOut, format );
            xmlWriter.write( document );
            fileOut.close();
    }PS.) on a side note there is a warning on one of the lines too. Can anyone offer help on that one too?!
    Thanks in advance.

    It is already set to that - it does look correct in Eclipse, honest.
    It's just the block that's gone crazy with the formatting. I've spent around 10 minutes trying to tweak it just so it displays correctly but it wasn't making sense.
    I'd rather not turn this conversation into a judgement of my code-style - I already understand that it doesn't conform to the 'Java way' and I've had Java programmers bash me about it for a long time.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Using classes inside of classes

    I have created a custom sound class called MySoundClass that
    extends the Sound class... it is declared as class
    com.stickyMatters.WineGlassPiano.MySoundClass. I also have another
    class called SongPlayer that is declared as
    com.stickyMatters.WineGlassPaino.SongPlayer... my question is.. how
    do i use the MySoundClass inside of the SongPlayer class... when I
    try to import it says I cannot use the import statement inside of a
    class file. I know in AS3 you can use the package keyword to create
    packages and do that... but as far as I can see there is no package
    keyword in AS2... because I tried, and it just tells me htere is a
    syntax error on the line with the package declaration... can you
    use one custom class inside another? and if so... how?
    P.S. just to be sure... i am using flash CS3 and writing AS2
    files. Thanks!

    ack!!! thank you...I actually tried that and it didn't
    work... but when I went back after you said it and tried it again,
    it did work... so I guess I just had a misspelling or something
    before. ugh! Thanks for the reply!

  • Swing - how to pass selected value out from actionPerformed() inner class?

    Hi all,
    I have a form with JcomboBox and textfields and I have to update the database
    with the submitted values. How can I pass the comboBox value out? I cannot defined boxValue as final outside the inner class.
    JComboBox list1 = new JComboBox (vector1);
    list1.addActionListener ( new ActionListener() {
    public void actionPerformed (ActionEvent ev) {
    boxValue = (String) ((JComboBox) ev.getSource()).getSelectedItem();
    thanks
    andrew

    OK, OK, my bad for not reading the whole post...
    1. Who needs to know the current JComboBox value? If the code that needs to know has access to the JComboBox, it can just get it from there. If the code is invoking the form, it is the responsibility of the form, not the listener, to return the values to the invoker.
    Please give us more information about what you are tryiug to do.

  • Accessing member variable within an anonymous inner class

    I'm getting a compiler error with the following snippet which resides in a constructor (error below):
            final String fullNamesArr[] = new String[ lafsArr.length ];
            String lafNamesArr[] = new String[ lafsArr.length ];
            JMenuItem namesMenuItemArr[] = new JMenuItem[ lafsArr.length ];
            for ( int i = 0 ; i < lafsArr.length ; i++ )
                StringTokenizer tokenizer;
                fullNamesArr[ i ] = lafsArr[ i ].getClassName();
                tokenizer = new StringTokenizer( fullNamesArr[ i ] );
                while ( tokenizer.hasMoreTokens() )
                    lafNamesArr[ i ] = tokenizer.nextToken( "." );
                namesMenuItemArr[ i ] = new JMenuItem( lafNamesArr[ i ] );
                lafMenu.add( namesMenuItemArr[ i ] );
                namesMenuItemArr[ i ].addActionListener(new ActionListener()
                        public final void actionPerformed(final ActionEvent e)
                            String actionCommand = e.getActionCommand();
                            int iCount = 0;
                            for ( int index = 0 ; index < fullNamesArr.length ; index++ )
                                if ( fullNamesArr[ index ].contains( actionCommand ))
                                    iCount = index;
                                    break;
                            System.out.println( "Setting LAF to '" +
                                                fullNamesArr[ iCount ] + "'" );
                            try
                                UIManager.setLookAndFeel( fullNamesArr[ iCount ] );
                            catch ( UnsupportedLookAndFeelException ulafe )
                                System.out.println( fullNamesArr[ iCount ] +
                                                    " : Not a valid LAF class." );
                            catch ( ClassNotFoundException cnfe )
                                System.out.println( fullNamesArr[ iCount ] +
                                                    " : Class not found." );
                            catch ( InstantiationException ie )
                                System.out.println( fullNamesArr[ iCount ] +
                                                    " : Can't instantiate class." );
                            catch ( IllegalAccessException iae )
                                System.out.println( fullNamesArr[ iCount ] +
                                                    " : Illegal access." );
    DBBuilder.java:1280: cannot resolve symbol
    symbol : method contains (java.lang.String)
    location: class java.lang.String
    if ( fullNamesArr[ index ].contains( actionCommand ))
    ^
    1 error
    BUILD FAILED
    My question: Why can I access fullNamesArr in other spots in the anon-inner class,but not with the String.contains() method? BTW, the carrot is under the left bracket '['.
    TIA,
    Jeff

    My question: Why can I access fullNamesArr in other
    spots in the anon-inner class,but not with the
    String.contains() method? BTW, the carrot is under
    the left bracket '['.You're misinterpreting the message. The problem is not your variable fullNamesArr, but rather the method contains(java.lang.String). Since that method was only added in Java 5 (aka 1.5) you might look if you're compiling with JDK 1.4 or earlier.

  • How to pass a variable value to an inner class?

    Hi there,
    Please have a look of the code below. It's a bit long, but my concern is I did have to declare the int "i" variable as static because it is used by an inner class (if "i" is not declare as static, the code cannot be compiled).
    Is there a more "clean" way to do the way work without declaring the "i" int as static? (because the scope of this variable is not the whole program).
    Thanks for your help.
    Denis
    import java.util.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Tools{
         static int i;
         static void longTask(){
              for (Tools.i=0; Tools.i<=100; Tools.i++) {
                   SwingUtilities.invokeLater( new Runnable(){
                        public void run(){
                             myApp.jpb.setValue(Tools.i);//--- static variable i
                   for (int j=0; j<200; j++)
                        System.out.println(Tools.i+" - "+j);
    class myListener implements ActionListener{
         public void actionPerformed(ActionEvent e){
              Thread t = new Thread() {
                   public void run(){
                        Tools.longTask();
              t.start();
    public class myApp {
         static JProgressBar jpb;
         public static void main(String[] args) {
              JFrame frame = new JFrame();
              JPanel panel = new JPanel(new FlowLayout());
              jpb = new JProgressBar();
              jpb.setValue(0);
              jpb.setStringPainted(true);
              JButton button = new JButton("go");
              button.addActionListener(new myListener());
              panel.add(jpb);
              panel.add(button);
              frame.getContentPane().add( panel, BorderLayout.CENTER);
              frame.setVisible(true);
              frame.pack();
    }

    Without compiling it, writing it in notepad, it would be something like this. You should also wonder if this longTask has to be static by the way. But I think this demonstrates the inner class stuff. You can also look in the tutorial on this site: http://java.sun.com/docs/books/tutorial/essential/threads/timer.html
    class Tools{
         static int i;
         static void longTask(){
              for (Tools.i=0; Tools.i<=100; Tools.i++) {
                   SwingUtilities.invokeLater( new Innerclass(i));
                   for (int j=0; j<200; j++) {
                        System.out.println(Tools.i+" - "+j);
         Class Innerclass implements Runnable(){
              int i;
              public Innerclass(int i) {
                   this.i = i;
              public void run(){
                   myApp.jpb.setValue(Tools.i);//--- static variable i
    }

  • Problems importing a class with inner class

    Why can't I import a class so that I can use an (inner) static member class without naming the enclosing class. Put simply, I have:
    file C:\MyJava\Test\A:
    public class A {
      public static class B { }
    }file C:\MyJava\Test\C
    import A.*;
    public class C { }When I try to compile C (javac -classpath C:\MyJava\Test;. C.java) it fails with C.java:1: package A does not exist

    Class A must be in a package if you wish to import it. If you want to use the inner class, just import somepackage.A. You could then refer to A.B...
    HTH :o)

  • How to access group content, or anything inside?

    Let's say I have this group:
    var myGroup = Group{
         var someNumber:Number;
            var stf = SwingTextField{
                 columns: 10,
                  text: "TextField",
                 editable: true
         content:[
              Text{
                   x: 100;
                   y: 100;
                   content: someNumber;
                   fill: Color.BLACK
                    stf
    }And let's say sometime when the program is running, the user changes the value of the SwingTextField. How do I access that? Like, I insert a rectangle inside the scene in the stage, and when the user moves the mouse it prints the content of the SwingTextField? And how do I access the variable "someNumber" as well? I tried things like println(myGroup.someNumber) or even println(myGroup) but nothing. Eclipse says it can't find "someNumber".
    Thanks. JavaFX is a lot trickier than what it made me thought at first. It doesn't help that the tutorials I've read taught some bad habits.
    _EDIT:_
    I figured out myGroup.content[], but it doesn't let me access the attributes of the node, like when I use
    myGroup.content[1].textIt can't find "text" even though it's already pointing to the SwingTextField (verified when I printed myGroup.content[1]), but the JavaFX documentation says it should have a text attribute.

    If you look at the javafx doc for Group you will see that content is declated as a Node[] (a sequence of Node instances) which means each node included within will show up as a Node. It is up to you to cast it to its real type afterwards.
    Alternatively, instead of direct access by index, you could set a unique id to each nodes and seach the content for a particular id. You will still need to cast afterward.

  • How to Access Total Number Of Pages inside code

    Hi All,
    I would like to get the total number of pages in the report,inside the trigger.
    How can i access this value inside code.
    Pls Help me
    Thanks and Regards
    Binu

    I think this is not possible inside the code, because this value is deteremined after the code is executed and during the formatting of the report.

Maybe you are looking for