简体   繁体   中英

getting different outputs from the same object

I will call readInput() for the two different objects. But in the first i want to get output as "for the first line" , in the second i want to get output as "for the second line". How can i do? Thanks .

import java.util.*;

public class Nokta{

    Scanner keyboard = new Scanner(System.in);
    public void readInput()
    {
        System.out.println("for the first line ");
        String degerler = keyboard.nextLine();
    }

I will call like this:

Nokta dogru1 = new Nokta ();

dogru1.readInput();


Nokta dogru2 = new Nokta ();

dogru2.readInput();

try this :

Scanner keyboard = new Scanner(System.in);
public  static int counter = 1;
   public void readInput()
   {
       System.out.println("for the "+counter +"line ");
       String degerler = keyboard.nextLine();
       counter++;
   }

more information : Static variable's value is same for all the object(or instances) of the class

You need to use static int for this. In short terms static will be initialized only once in execution it will not be initialized every time you do new Nokta() For what is static and examples please read this link .

public class Nokta{
    private static int lineNumber=1;    
    Scanner keyboard = new Scanner(System.in);
    public void readInput()
    {
        System.out.println("for the "+ lineNumber++ +" line ");
        String degerler = keyboard.nextLine();
    }

EDIT :

As in the comments this will say "for the 1 line" and "for the 2 line" instead of "for the first line" and "for the second line".
If you want to have it as first you can follow How to convert number to words in java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM