2013-10-16 18 views
1

我不得不編寫這個程序來輸出名字的第一個字母和姓氏的前五個字母加上從10-99的隨機數字。它的工作原理,但我認爲子字符串方法從0開始,並從那裏去,所以substring(0,0)將包括第一個字母和同樣子字符串(0,4)將包括0 1 2 3 4個字母的前5個還是不包括輸出中的最終數字?子串方法

import java.util.Scanner; 
import java.util.Random; 

public class NameModifier 
{ 

public static void main (String[] args) 
    { 

    String namefirst; 
    String namelast; 
    Random generator = new Random(); 
    int num; 

    num = generator.nextInt(99) + 10; 

    Scanner scan = new Scanner (System.in); 

    //prompts user 
    System.out.print ("Enter your first name: "); 
    namefirst = scan.nextLine();  
    System.out.print ("Enter your last name: ");  
    namelast = scan.nextLine(); 
    System.out.println("Your entered: " + namefirst + " " + namelast); 

    //outputs modified username possibility 
    System.out.println("Here is a random username for you: "); 
    System.out.print (namefirst.substring(0, 1)); 
    System.out.print (namelast.substring(0,5)); 
    System.out.print (num); 

    scan.close(); 

    } 
} 

回答

2

Java的字符串輸入,

public String substring(int beginIndex,int endIndex) 

beginIndex - the beginning index, inclusive. 
endIndex - the ending index, exclusive. 

注意的排斥。子(0,1)將返回一個字符串,包括字符0,直到但不包括字符1.

來源:http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,INT)

+0

非常好,謝謝! – Lou44

+0

@ Lou44幫助記住這種行爲的一種方法是'substring()'像_typical_ for-next循環一樣工作,它會終止最後一個數字。 _e.g._ for(int i = 1; i user949300

2

我希望你可以用這個例子更好的理解:

enter image description here

+0

現在有道理,謝謝! – Lou44