初学者;方法和字符串

时间:2014-04-17 17:13:55

标签: java string

以下是代码:

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工作作为字符串的集合,我可以在需要时调用它们。

但是当我尝试上面的例子时,我eclipse告诉我“第一个不能解决为变量”第六行String text = giveMe(first);

我做错了什么?

2 个答案:

答案 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);
}   
 }

答案 1 :(得分: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);
}

然后你想修改你的方法来取一个enum而不是像这样

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";
}