Java:如何在方法中连接字符串,在main方法中接收它,并在main方法中使用它?

时间:2013-10-24 20:46:55

标签: java

这是我的代码:

package labassignment6;

//Imports:
import java.util.Scanner;

class LabAssignment6
{
    //Method for asking the strings:
    public static String mStrings(int m, Scanner keyboard2)
    {
        String input = "", st = "";
        for (int x = 1; x <= m; x++)
        {
            System.out.println("Enter string " + x + ":");
            input = keyboard2.nextLine();
            keyboard2.next();
        }
    return input;
    } //End of mStrings.

    public static void main(String[] args)
    {
        //Declare a scanner object:
        Scanner keyboard = new Scanner(System.in);

        //Declare variables:
        int m;

        //Ask the user the number of strings they want to read:
        System.out.print("Enter the number of strings you want to read: \n");
        m = keyboard.nextInt();

        //Call the method, and print the concatenated string:
        //mStrings(m, keyboard);
        String stReturned = mStrings(m, keyboard); //Put the returned string into a variable.
        System.out.println(stReturned); //Print the concatenated string.

        //Convert the string to lowercase:
        //String stLower = stReturned.toLowerCase();

    } //End of main.

} //End of class LabAssignment6.

这是输出:

Enter the number of strings you want to read: 
3
Enter string 1:
I
Enter string 2:
need
Enter string 3:
help

BUILD SUCCESSFUL (total time: 10 seconds)

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

我想你想实现这个目标:

import java.util.Scanner;

public class LabAssignment6 {
    //Method for asking the strings:
    public static String mStrings(int m, Scanner keyboard2)
    {
        String input = "", st = "";
        for (int x = 1; x <= m; x++)
        {
            System.out.println("Enter string " + x + ":");
            st = keyboard2.next();
            input = input + st;
//            result = result+" "+input;
        }
    return input;
    } //End of mStrings.

    public static void main(String[] args)
    {
        //Declare a scanner object:
        Scanner keyboard = new Scanner(System.in);

        //Declare variables:
        int m;

        //Ask the user the number of strings they want to read:
        System.out.print("Enter the number of strings you want to read: \n");
        m = keyboard.nextInt();

        //Call the method, and print the concatenated string:
        //mStrings(m, keyboard);
        String stReturned = mStrings(m, keyboard); //Put the returned string into a variable.
        System.out.println(stReturned); //Print the concatenated string.

        //Convert the string to lowercase:
        //String stLower = stReturned.toLowerCase();

    } //End of main.
}

输出:

Enter the number of strings you want to read: 
3
Enter string 1:
I
Enter string 2:
Need
Enter string 3:
Help

INeedHelp