编写一个程序,从用户那里读取一行文本。该程序应打印“太短”"如果结果字符串包含少于10个字符;否则,它应该打印字符串中的字符数
到目前为止,我已经得到了什么,package exercise;
import java.util.Scanner;
public class ex6 {
public static void main(String[] args){
///creates a scanner object
Scanner input = new Scanner(System.in);
//prompt the user to enter a line of text
System.out.print("Enter a line of text: " );
String text = input.nextLine();
//counts characters prints too short if text is less than 10
int counter = 0;
for( int i=0; i < text.length(); i++ ) {
if( text.charAt(i) == '$' ) {
counter++;
}
else if ( text.length() < 10){
System.out.println("To short");
}
System.out.print("String Length :" );
System.out.println(text.length());
}
}
}
这段代码的问题在于,如果我输入man,例如它会打印出太短的三次。输出示例如下;
输入一行文字:man 太短 字符串长度:3 太短 字符串长度:3 太短 字符串长度:3
答案 0 :(得分:2)
这是因为你循环遍历字符串的长度。因此,当输入一个包含4个字符的字符串时,您将循环遍历您的条件4次,同时打印4次。
public static void main(String[] args){
///creates a scanner object
Scanner input = new Scanner(System.in);
//prompt the user to enter a line of text
System.out.print("Enter a line of text: " );
String text = input.nextLine();
//counts characters prints too short if text is less than 10
if (text.length() < 10) {
System.out.println("Too short");
} else {
System.out.print("String Length :" );
System.out.println(text.length());
}
}
在这种情况下,您应该避免使用循环。你只想检查一次。