Java程序设计基础(第5版) 陈国君 清华大学出版社 个人设计
习题5.8 从键盘上输入一个字符串和子串开始位置与长度,截取该字符串的子串并输出。
代码块:
package App;
import java.util.*;
public class App1
{
public static void main(String[] args)
{
String str;
Scanner reader=new Scanner(System.in);
System.out.print("Please enter string: ");
str=reader.nextLine();
int sLocation, length;
System.out.print("Please enter start location: ");
sLocation=reader.nextInt();
System.out.print("Please enter length: ");
length=reader.nextInt();
while((sLocation+length-1)>str.length())
{
System.out.print("Error!Retry!\n");
System.out.print("Please enter length: ");
length=reader.nextInt();
}
String sub="";
int i, n=str.length();
for(i=0; i<n; i++)
sub=str.substring(sLocation-1, sLocation+length-1);
System.out.println("The new string: "+sub);
}
}