我的程序应该将输入的单词向后拼写,如果输入的单词是回文,则跟随下一行并回答。然后它会取伴随的数字,如果它是素数则输出,然后输出它是否完美。
我在命令提示符下的输出仅显示回文部分和素数部分。我也不太明白为什么。
这是完整的代码,这是一个家庭作业,所以你可以忽略评论。
public static void main (String[] args) throws Exception
{
if (args.length == 0 ) // i.e If you did not type anything after "java Lab5" on command line
{
System.out.println("FATAL ERROR: Must type a filename on cmd line\n" +
"Like this -> C:\\Users\\tim\\Desktop>java Lab5 words1.txt");
System.exit(0); //ABORT program. Make user try again with a filename this time
}
Scanner infile = new Scanner( new File(args[0]) );
while ( infile.hasNext() )
{
String word = infile.next(); // grab next token (word) from file
// 1st method you must write below main: printWordBackwards
printWordBackwards( word ); // if word is "foobar" your method prints "baroof"
// 2nd method you must write below main: isPalindrome
if ( isPalindrome( word ) )
System.out.println( word + " IS A PALINDROME" ); // DO NOT MODIFY/REMOVE
else
System.out.println( word + " NOT A PALINDROME" ); // DO NOT MODIFY/REMOVE
// 3rd method you must write below main: isPrime
// NOTE WE ARE ASSUMING THAT EVERY OTHER TOKEN IN FILE IS AN INT TOKEN
int number = infile.nextInt(); // grab next token and convert to int
if ( isPrime( number ) )
System.out.println( number + " IS PRIME" ); // DO NOT MODIFY/REMOVE
else
System.out.println( number + " NOT PRIME" ); // DO NOT MODIFY/REMOVE
// 4th method you must write below main: isPerfect
// NOTE WE ARE ASSUMING THAT EVERY OTHER TOKEN IN FILE IS AN INT TOKEN
if ( isPerfect( number ) )
System.out.println( number + " IS PERFECT" ); // DO NOT MODIFY/REMOVE
else
System.out.println( number + " NOT PERFECT" ); // DO NOT MODIFY/REMOVE
System.out.println();
} // END WHILE
infile.close(); // WE ARE DONE WITH THE INPUT FILE./ CLOSE IT
} // END MAIN
// WRITE YOUR FOUR METHOD DEFINITIONS DOWN HERE
public static void printWordBackwards (String s)
{
for (int i = s.length()-1 ; i<= 0 ; i--)
{
System.out.print(s.charAt(i));
}
System.out.println();
}
public static boolean isPalindrome (String s)
{
int i = 0;
int j = s.length() - 1;
while (j > i)
{
if (s.charAt(i) != s.charAt(j))
{
return false;
}
++i;
--j;
}
return true;
}
public static boolean isPrime (int i)
{
for (int j = 2; j <= i/2; j++)
{
if (i % j == 0)
{
return false;
}
}
return true;
}
public static boolean isPerfect (int i)
{
for (int k = 1; i > 0; i++)
{
i -= k;
}
if (i == 0)
{
return true;
}
return false;
}
}// 结束 LAB5 课程