所以,我正在为我的班级做这个项目。但是,我无法获得打印出我想要的代码。它不断印刷出整首诗#34;
NerdData.txt:
Every man tries as hard as he can.
The best way is this way.
The schedule is very good.
Cosmo Kramer is a doofus.
The best movie was cancelled.
到目前为止我得到了什么:
import java.util.*;
import java.io.*;
public class FileNerd
{
public static void main(String args[]) throws IOException
{
Scanner sf = new Scanner(new File("C:\\temp_Timmy\\NerdData.txt"));
int maxIndx = -1;
String text[] = new String[1000];
while(sf.hasNext( ))
{
maxIndx++;
text[maxIndx] = sf.nextLine( ) ;
}
sf.close( );
for(int j = 0; j <= maxIndx; j++)
{
String q = text[j];
System.out.println(q);
if( q.substring(3).equals("The")) {
System.out.println(q);
}
}
}
}
代码编译得很好但是它没有打印出以单词&#34开头的行;&#34;&#34;它打印出整首诗。
我想要的输出:
The best way is this way.
The schedule is very good.
The best movie was cancelled.
答案 0 :(得分:4)
在这里打印每一行
String q = text[j];
System.out.println(q); // try to remove this
同时考虑使用String.startsWith
,因为您的子字符串错误*
if (q.startsWith("The")) {
System.out.println(q);
}
"Harbison".substring(3) returns "bison"
答案 1 :(得分:0)
你有太多的System.out,而你的子串是错误的......
for(int j = 0; j <= maxIndx; j++)
{
String q = text[j];
System.out.println(q); // this line will print every line
if( q.substring(3).equals("The")) { // this checks starting at char 3
System.out.println(q);
}
}
......应该......
for(int j = 0; j <= maxIndx; j++)
{
String q = text[j];
if( q.substring(0, 3).equals("The")) {
System.out.println(q);
}
}
答案 2 :(得分:0)
要测试给定的行是否以The
开头,我会使用startsWith
之类的
// Don't print every line.
// System.out.println(q);
if (q.startsWith("The")) {
System.out.println(q);
}
或者,要使用substring
,您需要0,3
喜欢
if (q.substring(0, 3).equals("The")) {
System.out.println(q);
}
答案 3 :(得分:0)
您打印循环中的每一行:
for(int j = 0; j <= maxIndx; j++)
{
String q = text[j];
System.out.println(q); // <- Here
if( q.substring(3).equals("The")) {
System.out.println(q);
}
}
你的平等检查是错误的。 "The best way is this way".substring(3)
将返回" best way is this way"
。请改用q.startsWith("The")
:
for(int j = 0; j <= maxIndx; j++)
{
String q = text[j];
if( q.startsWith("The")) {
System.out.println(q);
}
}