0

我到目前为止的代码:

import java.util.Scanner;

public class ExtractLine
{
    public static void main (String[] args)
    {
    Scanner stdIn = new Scanner (System.in);
    String songs =
    "1. Bow Wow - Fresh Azimiz\n" +
    "2. Weezer - Beverly Hills\n" +
    "3. Dave Matthews Band - Crash Into Me\n" +
    "4. Sheryl Crow - Leaving Las Vegas\n";

    String songNum; //song number that is searched for
    //int songIndex; //position of where song number is found
    int eolIndex; //position of end of line character
    String song; //the specified line

    System.out.print ("Enter song number: ");
    songNum = stdIn.nextLine();
    eolIndex = songs.indexOf("\n");


    int songIndex = songs.indexOf(songNum);


    song = songs.substring(songIndex);

    System.out.println("\n\n" + song + "\n\n");


}//end main
}//end class

需要发生的是用户必须输入一个数字,1-4,然后输出将只是上面有歌曲的那一行,例如。用户输入:1,输出:1. Bow Wow - Fresh Azimiz。(不是我的选择,这是教科书中的内容)。

我的问题,我可以让程序认识到它需要从我输入的任何数字开始,输出恰好包含所有内容,而不仅仅是行。

例如:输入:3

输出:3. Dave Matthews Band - Crash Into Me (\n) 4. Sheryl Crow - 离开拉斯维加斯

有想法该怎么解决这个吗?谢谢!

4

2 回答 2

1

您调用的单参数substring方法从字符串的开头位置到结尾,这不是您想要的。

您将需要找到下一个 \n字符的索引。如果存在,则使用两个参数的substring方法来提取正确的子字符串。如果它不存在,那么您可以substring像已经调用它一样调用它——让子字符串一直到字符串的末尾。

于 2013-09-23T20:54:23.513 回答
0

您可能需要考虑使用集合来存储您的歌曲(例如 HashMap)。这样,您可以直接从键访问值,而不必担心访问子字符串。

这是执行此操作的一种方法(注意java.lang.NumberFormatException,如果用户输入除整数以外的任何内容,您将收到 a ,如果未找到密钥,您将收到 null 对象):

public static void main(String[] args) {
    Scanner stdIn = new Scanner(System.in);
    Map<Integer, String> songs = new HashMap<>();
    songs.put(1, "Bow Wow - Fresh Azimiz");
    songs.put(2, "Weezer - Beverly Hills");
    songs.put(3, "Dave Matthews Band - Crash Into Me");
    songs.put(4, "Sheryl Crow - Leaving Las Vegas");

    Integer songNum; 
    System.out.print("Enter song number: ");
    songNum = Integer.valueOf(stdIn.nextLine());

    System.out.println("\n\n" + songs.get(songNum) + "\n\n");
    stdIn.close();
}
于 2013-09-23T21:19:40.273 回答