[java] lengh

Viewer

  1. // Import the Scanner class from its ‘package’java.util
  2. import java.util.Scanner;
  3.  
  4. public class lengthOfWord {
  5.         public static void main(String[] args){
  6.  
  7.         // Setup an object of the Scanner class.
  8.         Scanner in = new Scanner(System.in);
  9.         System.out.print("Please enter the words: ");
  10.  
  11.         //Use methods of the new Scanner object to get input
  12.         String str = in.nextLine();
  13.  
  14.         int length=str.length();
  15.         //訂最後一個單字的位置
  16.         int spaceposition=0;
  17.  
  18.         //從後面開始算空格位置
  19.         for(int i=length-1 ;i>=0;i--){
  20.             if(str.substring(i,i+1).equals(" ")){
  21.                 spaceposition=i;
  22.                 break;
  23.             }
  24.         }
  25.  
  26.         String last =str.substring(spaceposition+1,length);
  27.  
  28.         System.out.println(last);
  29.     }
  30. }

Editor

You can edit this paste and save as new:


File Description
  • lengh
  • Paste Code
  • 24 Sep-2020
  • 857 Bytes
You can Share it: