显示所选消息字符串

时间:2014-10-22 23:57:21

标签: java arrays methods

我正在研究一种遍历所有数组消息并显示所选消息的方法。我是Java的新手,所以我还在试图找出方法和数组。当我运行它时,它说它成功但它没有显示任何东西。有人可以帮我解决这个问题。

package chatbox;

import java.util.Scanner;

public class ChatBox
{
 public static void main(String[] args)
 {
 String chatMessages[] = new String[10];
 //declare arrays
 chatMessages[0]= "Pepperoni";
 chatMessages[1]= "Olives";
 chatMessages[2]= "Cheese";
 chatMessages[3]= "Onions";
 chatMessages[4]= "Bacon";
 chatMessages[5]= "Tomato sauce";
 chatMessages[6]= "Bell peppers";
 chatMessages[7]= "Mushrooms";
 chatMessages[8]= "Sausage";
 chatMessages[9]= "Beef";       

 } 

 Scanner scan = new Scanner (System.in);

public Scanner chatCannedMessage(String chatMessages)
          {              
for (int i=0;i<chatMessages.length;i++){ 

     System.out.println(chatMessages[i]); //Prints Message
 }

System.out.println("Select a message");

String chatMessage = scan.next();

scan.nextLine();      

 return scan;

          }
}

1 个答案:

答案 0 :(得分:1)

正如PM 77-1所说,你从未调用过shoutOutCannedMessage方法,也从不打印或返回任何字符串。
我试图尽量减少对代码的更改,我认为这可能是您打算做的。

import java.util.Scanner;

public class ShoutBox {

    Scanner scan = new Scanner(System.in);

    public static void main(String[] args) {

        String messages[] = new String[10];
        //declare 10 arrays
        messages[0] = "Pepperoni";
        messages[1] = "Olives";
        messages[2] = "Cheese";
        messages[3] = "Onions";
        messages[4] = "Bacon";
        messages[5] = "Tomato sauce";
        messages[6] = "Bell peppers";
        messages[7] = "Mushrooms";
        messages[8] = "Sausage";
        messages[9] = "Beef";

        String m = new ShoutBox().shoutOutCannedMessage(messages);
        System.out.println(m);
    }

    public String shoutOutCannedMessage(String[] messages) {
        for (int i = 0; i < messages.length; i++) {

            System.out.println(i+". "+messages[i]); //Should print the messages
        }

        System.out.println("Select a message");

        int idx = scan.nextInt();

        String message = messages[idx];

        return message;

    }
}