2014-04-17 31 views
1

下面是代碼:初學者;方法和字符串

import java.util.Scanner; 
public class sending { 

public static void main(String[] args){ 
    Scanner scanner = new Scanner(System.in); 
    String text = giveMe(first); 
    System.out.println(text); 
    int x = scanner.nextInt(); 
    x = number(x); 
    skrivUt(x); 
} 


//method for printing on screen 
public static String giveMe(String first, String second){ 
    first = ("Give me a number and I run down and add five to it"); 
    second = ("Lol"); 
    return first; 
} 

//method for doing math 
public static int number(int x){ 
    x = x + 5; 

    return x; 
} 

//method for printing out 
public static void skrivUt(int x){ 
    System.out.println(x); 
} 
} 

正如你看到的我是新來這和我有主要方法和方法giveMe問題。

我想讓giveMe工作作爲一個字符串的集合,我可以在需要時調用它們。

但是當我嘗試上面的例子中我日食告訴我,在六大行String text = giveMe(first);

我在做什麼錯「首先不能被解析爲一個變量」?

+3

你應該閱讀有關變量_scope_。在'main'方法中,'first'是什麼? –

+0

@SotiriosDelimanolis'第一個'是他看不見的'enum'。 – CodeCamper

回答

1

您嘗試使用一個枚舉,你從未宣佈過一個...你聲明枚舉這樣你的主要之外。

enum s {FIRST, SECOND} //add this 

public static void main(String[] args){ 
    Scanner scanner = new Scanner(System.in); 
    String text = giveMe(s.FIRST); //add the s. so it knows to use your enum 
    System.out.println(text); 
    int x = scanner.nextInt(); 
    x = number(x); 
    skrivUt(x); 
} 

然後你要修改你的方法把一個枚舉,而不是像這樣

public static String giveMe(s string) { 
switch (string) { 
case FIRST: 
    return "Give me a number and I run down and add five to it"; 
case SECOND: 
    return "Lol"; 
} 
return "invalid string"; 
} 
+1

我認爲CodeCamper是正確的。只是好奇,什麼時候'大聲笑'適用? –

+0

@ halal48從我所瞭解的情況看來,他想用一串字符串來製作一個方法,他可以稍後調用'我想讓giveMe作爲一個字符串的集合,當我需要它時可以調用它'所以這種方法可能會用於他想在他的程序中使用'enum'調用的預定義字符串的更大列表。我想他會在他的節目中發生一些有趣的事情時使用「Lol」字符串。也許當用戶點擊撓癢癢按鈕時。 – CodeCamper

+0

我投了你的答案,有人沒有任何解釋就投了票。很顯然,他不是在簡單地嘗試做什麼,而是希利斯提出的建議。或者,也許我錯了。阿德里安拉爾森,你能澄清一下嗎? –

1

初學者,你的問題已解決。

首先聲明在java中很重要。您的代碼塊中沒有固定「第一個」變量。理想情況下,您的場景不是必需的。

試試這個

import java.util.Scanner; 
public class Test2 { 

public static void main(String[] args){ 
    Scanner scanner = new Scanner(System.in); 
    String text = giveMe(); 
    System.out.println(text); 
    int x = scanner.nextInt(); 
    x = number(x); 
    skrivUt(x); 
} 


//method for printing on screen 
public static String giveMe(){ 
    String first = ("Give me a number and I run down and add five to it"); 
    return first; 
} 

//method for doing math 
public static int number(int x){ 
    x = x + 5; 

    return x; 
} 

//method for printing out 
public static void skrivUt(int x){ 
    System.out.println(x); 
} 
} 
+0

我認爲他希望能夠使用'enum'在方法內部的字符串列表中進行選擇,否則爲什麼他會創建giveMe方法? – CodeCamper

+0

非常感謝! –