[英]Java passing variables from method in one class into different class
我已經在StringSplit類中獲得了這個int變量,我需要將其值傳遞給另一個名為EndStatement的類以進行打印; 盡管我認為不能真正將其作為參數傳遞。 如何最好地將變量獲取到需要的地方? 有人可以幫忙嗎? 我讀過Java教程,但還不太了解。 在Java編程中,變量和傳遞變量似乎是我的致命弱點之一。
編輯: parseCommands
可以調用多個不同的Statement類,例如EndStatement或PrintlnStatement,具體取決於從String解析的Array的第一個元素,該String用作HashMap的關鍵字,稱為commandHash。 Statement類實現了Directive接口,該接口僅具有一個名為execute
的方法,該方法帶有參數String[] parts
。 ( EndStatement implements Directive
)。 擴展了parseCommands
方法以顯示正在發生的事情。
public class StringSplit
{
public void parseCommands(String fileName)
{
//FileReader and BufferedReader to read a file with the code
//to execute line by line into an ArrayList myString
int lineCounter=0; //need to get this variable's value into class EndStatement
for (String listString: myString)
{
lineCounter++;
String[] parts=listString.trim.split("[\\s]+", 2)//split String into 2 parts
//to get commands
Directive directive= commandHash.get(parts[0])//parts[0] is the hashmap keyword
}
public class EndStatement implements Directive
{
public void execute(String[] parts)
{
//need to get lineCounter here--how?
System.out.print(lineCounter +"lines processed.");
}
public static void main (String[]args)
StringSplit ss = new StringSplit();
ss.parseCommands(args[0]);
}
這是我第一次回答問題,但我認為我是對的。
在StringSplit
您要在數據字段中聲明linceCounter
。
public class StringSplit
{
public void parseCommands(String fileName)
{
lineCounter=0; //this is the variable I need to pass into a different class
for (String listString: myString)
{
lineCounter++;
//more code here
}
}
public int getLineCounter()
{
return lineCounter;
}
private int lineCounter; //this is what I call a data field, you should declare these as private as oppose to public to comply with encapsulation
}
然后在您的主方法中調用getLinceCounter
,然后將返回的內容傳遞給EndStatment
。
這有意義嗎? 我理解你的問題對嗎?
public class StringSplit
{
private int lineCounter=0;
public void parseCommands(String fileName)
{
for (String listString: myString)
{
lineCounter++;
//more code here
}
}
public int getLineCounter() {
return lineCounter;
}
}
public class EndStatement implements Directive
{
StringSplit ss = new StringSplit();
public void execute(String[] parts)
{
//need to get lineCounter here--how?
System.out.print(ss.getLineCounter() +"lines processed.");
}
public static void main (String[]args)
{
ss.parseCommands(args[0]);
}
}
我認為您混用了一些術語。 沒有將變量從一類傳遞到另一類的事情。 我假設您要做的只是能夠訪問(設置/獲取)StringSplit類之外的變量。 為此,您必須在parseCommands方法外部聲明lineCounter作為StringSplit的屬性。 當前,lineCounter對於parseCommands方法而言是本地的,因此無法在該方法外部可見/訪問,更不用說能夠從類/對象外部訪問它。 去做:
public class StringSplit
{
public int lineCounter = 0;
...
現在,您將可以從同一類的不同方法以及類外部的方法訪問lineCounter。 將lineCounter公開可以使其他人完全訪問它。 正如“喬恩”所指出的那樣,有時可能很危險,但對於本示例來說,這種情況是可以接受的。 您可能會看到如何使用“ Nurlan's私有字段”(該成員僅用於提供讀取訪問權限)來防止外部寫入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.