简体   繁体   English

从同一个对象获得不同的输出

[英]getting different outputs from the same object

I will call readInput() for the two different objects. 我将为两个不同的对象调用readInput()。 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. 您需要为此使用static int。 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 . 简而言之,static只会在执行时初始化一次,不会在每次执行new Nokta()时初始化。有关什么是static和示例,请阅读此链接

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 如果要首先使用它,可以按照如何在Java中将数字转换为单词的方法进行操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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