我刚开始使用Java。我需要从输入中获取前N个字符。输入内容包括输入字符串开头的字符数和字符数。输出包括开头的数字。
例如,如果用户输入“ 3stars”,则输出将为“ 3st”,或者输入“ 7appendices”,输出将为“ 7append”。
尝试了以下方法:
Scanner input = new Scanner(System.in);
System.out.print("Please enter a uncoded string: ");
String first = input.nextLine();
input.close();
if (first.charAt(0) == 'u') {
first = first.toUpperCase();
} else if (first.charAt(0) == 'l') {
first = first.toLowerCase();
} else if (first.charAt(0) == 'e') {
String str = "";
for (int i = 0; i < first.length(); i = i + 2) {
str += first.charAt(i);
}
first = str;
} else if (first.charAt(0) == 'o') {
String str = "";
for (int i = 1; i < first.length(); i = i + 2) {
str += first.charAt(i);
}
first = str;
} else if (first.charAt(0) == 1++) {
String str = "";
for (int i = 1++ ; i < first.length(i); i = i charAt(i)) {
str += first.charAt(i);
}
first = str;
任何帮助都会很棒。
答案 0 :(得分:0)
我希望这会有所帮助:
int num = Character.getNumericValue(first.charAt(0));
String str = "";
for(int i = 0;i < num;i++){
str += first.charAt(i);
}
System.out.println(str);
答案 1 :(得分:0)
这也适用于数字大于9的11abcdefghijklmnopqrstuvwxyz
之类的输入
public static void main(String[] args) {
String input = "7appendices";
// match numbers
Pattern p = Pattern.compile("^([0-9]+)");
// by default at least the integer has one digit
int digits = 1;
int length = 0;
// while the beginning of the input match an integer
while (p.matcher(input.substring(0, digits)).matches()) {
// set length as the integer at the beginning
length = Integer.parseInt(input.substring(0, digits));
// increase the amount of digits from the integer in the input
digits++;
}
System.out.println(input.substring(0, length));
}
您只需像这样用scanner
替换输入
String input = new Scanner(System.in).next();