1

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();
M A
  • 71,713
  • 13
  • 134
  • 174

2 Answers2

1

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

1

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

Community
  • 1
  • 1
StackFlowed
  • 6,664
  • 1
  • 29
  • 45
  • Of course, this will output "for the 1 line" and "for the 2 line" instead of "for the first line" and "for the second line". – GriffeyDog Nov 06 '14 at 21:22
  • @GriffeyDog Yes you are correct made an edit to notify that and added info how can you get it as word. – StackFlowed Nov 06 '14 at 21:27