2014-12-02 31 views
0

我试图打印出用户指定的字母数量。对于例如用户键入一个字 - 马,并指定他们想要打印的字母数 - 4.输出结果应该是:Hors。我必须使用子字符串方法。打印出用户指定长度的第一部分

我的程序摆脱了用户指定的字母并打印出剩下的字母。我怎样才能解决这个问题?

import java.util.Scanner; 

public class FirstPart { 

public static void main(String[] args) { 
    Scanner reader = new Scanner(System.in); 
    System.out.println("Type a word: "); 
    String word = reader.nextLine(); 
    System.out.println("Length of the first part: "); 
    int firPar = Integer.parseInt(reader.nextLine()); 

    int i = 0; 

    while (i <= firPar) { 

     System.out.print("Result: " + word.substring(firPar)); 
     i++; 
     break; 
    } 

} 

}

+1

我建议你阅读子的文档。 – 2014-12-02 19:37:40

回答

1

您应该使用Scanner.nextInt()并且根本不需要循环。只需拨打String.substring(int, int)0firPar

public static void main(String[] args) { 
    Scanner reader = new Scanner(System.in); 
    System.out.println("Type a word: "); 
    String word = reader.nextLine(); 
    System.out.println("Length of the first part: "); 
    int firPar = reader.nextInt(); 
    System.out.println("Result: " + word.substring(0, firPar)); 
} 
+0

谢谢。这工作得很好。我过于复杂的事情。为什么使用nextInt()而不是Integer.parseInt()? – 2014-12-02 19:40:43

+0

@NoahKettler你已经拥有'Scanner',它可以为你做。我认为它更干净。 – 2014-12-02 19:41:28

0
System.out.print("Result: " + word.substring(0, firPar)); 

如果只指定一个int作为串它是起始索引(含)。如果指定2个整数,则它是开始索引(包括)结束索引(不包括)。你也可以摆脱你的while循环。

substring(startIndex) //will take startIndex to length 

substring(startIndex, endIndex) //will take startIndex (inclusive) to endIndex (exclusive)