2016-09-18 11 views
-8

私は初心者のプログラミングコースに参加していて、私のプログラムで文字列の最後の文字を出力できない場合がありますか?あなたが最後の文字を取得しようとすると、代わりにその情報を使用しての、文字列の最後の文字を出力

System.out.print("The length of " + word + " is " + word.length()); 

しかし:あなたは、単語の長さを取得する方法を知っている、あなたはここでそれをやった

public class String { 
    private static java.lang.String string;  

    public static void main(java.lang.String[] args) {  
     Scanner input = new Scanner(System.in);        
     System.out.println("Enter a string: "); //user enters a word      
     java.lang.String word = input.nextLine();    
     System.out.print("The length of " + word + " is " +   
     word.length()); //gives the number of characters in the word   
     java.lang.String length = input.nextLine();     
     System.out.print("The first character: " + word.charAt(0)); //gives the first letter of word   
     java.lang.String first = input.next();    
     System.out.print("The last character: " + word.charAt(4)); //gives the last letter of word  
     java.lang.String last = input.next(); 
    } 
} 
+2

もちろん、最後のインデックスではなく、インデックス4でcharを取得しているためです。最後のインデックスを取得するには、string.length - 1 – Winter

答えて

1

:ここに私のプログラムです定数 "4"を使用します。

System.out.print("The last character: " + word.charAt(4)); //gives the last letter of word 

2つの答えを組み合わせてみてください。しかし、長さから1を減算することに関するあなたの記事のコメントにも注意してください。

0
System.out.println("last character: " + 
         string.substring(string.length() - 1)); 

希望します。

関連する問題