我正在尝试使用userInput,并使用split方法将找到的任何数字加倍



我正在尝试使用扫描仪获取用户输入,并将userInput中的任何数字加倍。例如:我不知道该做什么22应该打印为:我不知道该怎么做44

当我尝试使用parseInt时,我不确定如何使用它来输出我的结果。

public class CopyOfTester
{
public static void main(String args[])
{
boolean Bool = true;
do{
Scanner kbReader = new Scanner(System.in);
System.out.println("Please type in a sentence, or type EXIT to end the program.");
String UserIn = kbReader.nextLine();
if (UserIn.equals("EXIT")){
Bool=false;
}
else{
String sp[] = UserIn.split("\d+");
sp = UserIn.split(" ");  
String lemon;
int nu;
for (int i = 0; i >= sp.length; i++){
nu= Integer.parseInt(sp[i])*2;
nu = nu * 2;
}
System.out.println(nu );
}
}while (Bool == true);
}
}
  1. 您需要一个循环来继续执行,直到用户输入EXIT
  2. 您可以使用正则表达式匹配和替换整数

演示:

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Scanner kbReader = new Scanner(System.in);
String userIn;
Pattern pattern = Pattern.compile("\b\d+\b");// String of one or more digits bounded by word-boundary
while (true) {
System.out.print("Please type in a sentence, or type EXIT to end the program: ");
userIn = kbReader.nextLine();
if ("EXIT".equalsIgnoreCase(userIn)) {
break;
}
StringBuilder sb = new StringBuilder();
Matcher matcher = pattern.matcher(userIn);
int lastProcessedIndex = 0;
while (matcher.find()) {
String number = matcher.group();
int startIndex = matcher.start();
// Append the string starting from the last processed index and then append the
// doubled integer
sb.append(userIn.substring(lastProcessedIndex, startIndex))
.append(String.valueOf(2 * Integer.parseInt(number)));
// Update the last processed index
lastProcessedIndex = startIndex + number.length();
}
// Append the remaining substring
sb.append(userIn.substring(lastProcessedIndex));
System.out.println("The updated string: " + sb);
}
}
}

样本运行:

Please type in a sentence, or type EXIT to end the program: hello 10 world 5 how are 15 doing?
The updated string: hello 20 world 10 how are 30 doing?
Please type in a sentence, or type EXIT to end the program: exit

else分支中存在许多问题:

  • 在解析is之前,您需要知道您找到了一个(字符串化的(整数。请使用匹配器
  • 如果字符串数组大于0,则永远不会进入解析循环。使用<而不是>=
  • 要打印整个输入,请操作字符串数组;不要试图使用int来打印字符串
  • 只定义一次字符串数组
  • 柠檬味道不错,但在这里没有帮助:(

这是有效的:

String sp[] = userIn.split(" ");
Pattern p = Pattern.compile("-?\d+");
for (int i = 0; i < sp.length; i++) {
Matcher m = p.matcher(sp[i]);
while (m.find()) {
sp[i] = String.valueOf(Integer.parseInt(m.group()) * 2);
}
}
Arrays.stream(sp).forEach(string -> System.out.print(string + " "));
System.out.println();

最新更新