如何在java中的其他地方使用计数
是否存在可以将count放入变量中的方法。我得数数行数。之后,我想使用计数提供的数字,然后将该数字添加到可在其他地方使用的变量中,例如,使用另一个数字进行添加,或查找百分比,或使用该数字创建饼图如何在java中的其他地方使用计数,java,Java,是否存在可以将count放入变量中的方法。我得数数行数。之后,我想使用计数提供的数字,然后将该数字添加到可在其他地方使用的变量中,例如,使用另一个数字进行添加,或查找百分比,或使用该数字创建饼图 public void TotalCount12() throws FileNotFoundException { Scanner file = new Scanner(new File("read.txt")); int count = 0; whil
public void TotalCount12() throws FileNotFoundException {
Scanner file = new Scanner(new File("read.txt"));
int count = 0;
while(file.hasNext()){
count++;
file.nextLine();
}
System.out.println(count);
file.close();
我想使用我将在计数中得到的数字,并在其他地方使用它(例如另一种方法),但我不知道如何做到这一点
多谢各位 编辑
为count
变量创建一个getter方法
例如
首先,我建议如果你是编程新手,你应该完成这个 如果在类中将其定义为方法外的全局变量(作为类的属性),则可以在类中的每个方法中使用它 但是如果你的问题是要在不同类的项目中使用它,你可以使用
只需在您创建的方法中返回值:
public class Test {
public int TotalCount12() throws FileNotFoundException {
Scanner file = new Scanner(new File("read.txt"));
int count = 0;
while(file.hasNext()) {
count++;
file.nextLine();
}
System.out.println(count);
file.close();
return count;
}
public static void main(String[] args) {
Test t = new Test();
int testCount = TotalCount12();
}
}
我想将计数用作另一个方法或另一个类中的变量。我只是想知道我是否能做到这一点。然后使
count
成为一个全局变量使用它作为一个参数来调用其他方法在你的类中创建它,而不是在该方法中。问题不清楚。如果复制整个类代码,则更好地理解。@JustMe如果试图从另一个类访问实例变量,请提供公共getter方法,并从该另一个类中引用的实例检索计数。您使用的上下文不是很清楚,因此很难提供有意义的建议。这里的全局变量是什么意思。它只是一个成员变量,因为只有测试类在这个变量上有访问范围variable@wns349您没有正确使用术语“全局”。这是一个实例变量。这是不可用的“全球”。对不起,但我会使用单例设计模式与计数?现在,你有单例关键字,请在谷歌上搜索,然后写你的代码请自己。
public class ClassicSingleton {
private static ClassicSingleton instance = null;
protected ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if(instance == null)
{
instance = new ClassicSingleton();
}
return instance;
}
}
public class Test {
public int TotalCount12() throws FileNotFoundException {
Scanner file = new Scanner(new File("read.txt"));
int count = 0;
while(file.hasNext()) {
count++;
file.nextLine();
}
System.out.println(count);
file.close();
return count;
}
public static void main(String[] args) {
Test t = new Test();
int testCount = TotalCount12();
}
}