2016-12-09 2 views
-3

, поэтому, вероятно, это было задано раньше, но я не могу понять всю информацию, которую я читал в Интернете.Используйте один метод другим способом

public static void balanceSheet(){ 
    //Put in the Company u want to get the data from 
    Scanner scan= new Scanner(System.in); 
    System.out.println("Enter your Symbol: "); 
    String symbol= scan.nextLine(); 

    //Diffrent Websites to visit and get the Data 
    String url = ("http://www.morningstar.com/stocks/XNAS/"+symbol+"/quote.html"); 
    driver.switchTo().frame(driver.findElement(By.xpath("//*[(@id = 'quote_quicktake')]//iframe"))); 
    String currPrice = driver.findElement(By.id("last-price-value")).getText(); 
    driver.switchTo().defaultContent(); 

    System.out.println("Current Share Pirce: "+currPrice+"$"); 
} 

Как получить значение String currPrice внутри метода calCulator, чтобы я мог рассчитать его с другими числами?

public void calCulator() { 
    Scanner calCu = new Scanner(System.in); 
    System.out.println("Do you want to Calculate the Value?: "); 
    String calculator = calCu.next(); 

    if(calculator.equals("Yes")) { 
    System.out.println("the Calculation is: "); 
    } 

    else { 
    System.out.println("ok"); 
    } 
} 
+0

Передайте это значение как параметр 'calCulator()' method ?? –

+0

или магазин 'currPrice' как поле –

+0

Могу ли я привести пример? это моя первая программа, поэтому я довольно свежий с java –

ответ

-1

Возьмите currPrice в качестве переменной-члена класса, то вы можете использовать его в другом методе класса, как показано ниже.

public class Culator { 
    // Take "currPrice" as member variable of class 
    public static String currPrice = ""; 


    public static void balanceSheet(){ 

     //Put in the Company u want to get the data from 
     Scanner scan= new Scanner(System.in); 
     System.out.println("Enter your Symbol: "); 
     String symbol= scan.nextLine(); 

     //Diffrent Websites to visit and get the Data 
     String url = ("http://www.morningstar.com/stocks/XNAS/"+symbol+"/quote.html"); 

     driver.switchTo().frame(driver.findElement(By.xpath("//*[(@id = 'quote_quicktake')]//iframe"))); 
     currPrice = driver.findElement(By.id("last-price-value")).getText(); 

     driver.switchTo().defaultContent(); 

     System.out.println("Current Share Pirce: "+currPrice+"$"); 
    } 


    public void calCulator() 
    { 
     Scanner calCu = new Scanner(System.in); 
     System.out.println("Do you want to Calculate the Value?: "); 
     String calculator = calCu.next(); 

     if(calculator.equals("Yes")){ 
      System.out.println("the Calculation is: "); 
     } else { 
      System.out.println("ok"); 
     } 
     // Now You can use "currPrice" in this method 
    } 

}  
+0

, но когда я пытаюсь, я всегда получаю результат Null back, а не currPrice, объявленный в public static void balanceSheet() –

+0

'balanceSheet' является статическим методом, вы не можете получить доступ к переменной экземпляра' currPrice' там – Pat

+0

Обновите свой код как мой обновленный ответ. Вы должны сначала вызвать balanceSheet(). Итак, сначала вычисляется 'currPrice', тогда вы можете использовать это значение переменной в другом методе. –

0

ок я получил ответ я хотел в любом случае после 15 часов чистого глядя на учебники это было очень легко, это был только я, что медленно в голове, но дело в том, что я сделал

public class Webscraper { 

    String currentPrice; <<<<<< ADDED THAT STRING TO MY CLASS 

    public void balanceSheet(){ 
     //Put in the Company u want to get the data from 
     Scanner scan= new Scanner(System.in); 
     System.out.println("Enter your Symbol: "); 
     String symbol= scan.nextLine(); 

     //Diffrent Websites to visit and get the Data 
     String url = ("http://www.morningstar.com/stocks/XNAS/"+symbol+"/quote.html"); 
     driver.switchTo().frame(driver.findElement(By.xpath("//*[(@id = 'quote_quicktake')]//iframe"))); 
     String currPrice = driver.findElement(By.id("last-price-value")).getText(); 
     driver.switchTo().defaultContent(); 

     System.out.println("Current Share Pirce: "+currPrice+"$"); 
     currentPirce = currPrice; <<<<<< ADDED THAT SO THAT THE CLASS STRING WOULD GET ITS VALUE 
    } 

    public void calCulator() { 
     Scanner calCu = new Scanner(System.in); 
     System.out.println("Do you want to Calculate the Value?: "); 
     String calculator = calCu.next(); 

     if(calculator.equals("Yes")) { 
     System.out.println("the Calculation is: "currentPrice); <<<<<< NOW I CAN GET THE VALUE 
     } 

     else { 
     System.out.println("ok"); 
     } 
    } 

Благодарю вас, ребята, за помощь в любом случае и указали мне в правильном направлении. Надеюсь, это поможет другой душе, которая имеет ту же проблему.