Reputation:
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();
Upvotes: 1
Views: 60
Reputation: 936
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
Upvotes: 1
Reputation: 6816
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();
}
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
Upvotes: 1