我到目前为止的代码:
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 - 离开拉斯维加斯
关于如何解决这个问题有什么想法吗?谢谢!
最佳答案
one-argument substring
method您调用从字符串的开始位置到末尾的位置,这不是您想要的。
您需要找到下一个 \n
字符的索引。如果存在,则使用 the two-argument substring
method这将提取正确的子字符串。如果它不存在,那么您可以像您已经调用的那样调用 substring
来获取子字符串直到字符串末尾。
关于java - 如何使用indexOf()在Java中提取行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18968608/