英文:
JAVA trouble with control flow and strings in school project
问题
这是我的代码需要完成的任务:
"这段代码接收一个字符串作为输入,如果字符串为空,仅包含空白字符,或者不以数字、+/- 开头,则返回 0。否则,代码将返回经过修整的字符串(没有前导或尾随空白字符),其中不会有紧随数字之后的尾随字母。"
这是我的代码:
import java.util.Scanner;
public class stringManipulator
{
public static void main(String[] args)
{
// 初始化一个新的系统输入扫描器对象命名为input
Scanner input = new Scanner(System.in);
// 初始化变量
int index = 0;
// 提示用户输入一个字符串
System.out.println("输入一个字符串:");
// 将用户输入存储在字符串变量str中
String str = input.nextLine();
// 编辑和输出用户输入的字符串
if (str.length() == 0)
{
System.out.println("返回 0:字符串为空");
}
else if (str.trim().length() == 0)
{
System.out.println("返回 0:字符串仅包含空白字符");
}
else
{
while (index < str.length() && (Character.isDigit(str.charAt(index)) || (index == 0 && (str.charAt(index) == '+' || str.charAt(index) == '-'))))
{
System.out.print(str.charAt(index));
index++;
}
}
// 关闭输入扫描器对象
input.close();
}
}
我遇到了一些问题:
- 我似乎无法让我的 while 循环在输出中保留 '+' 或 '-'。
- 我似乎无法让 while 循环修整输出中的前导和尾随空白字符。
- 在执行循环之前,我无法让程序检测第一个字符是否不是数字、'+' 或 '-'。
欢迎提出任何建议!谢谢!
英文:
This is what my code needs to do:
"This code takes a string as input and returns 0 if the string is empty, contains only whitespace, or does not start with a number or +/-. Otherwise, the code will return the string as a trimmed number(no leading or trailing whitespace) with no trailing letters following the numbers."
This is what I have:
import java.util.Scanner;
public class stringManipulator
{
public static void main (String[]args)
{
//initialize new system.in scanner object named input
Scanner input = new Scanner(System.in);
//initialize variables
int index = 0;
//prompt user for a string as input
System.out.println("Enter a string: ");
//store user input in string variable str
String str = input.nextLine();
//edit and output user inputed string
if(str.length()==0)
{
System.out.println("return 0: String is empty");
}
else if(str.trim().length()==0)
{
System.out.println("return 0: String is only whitespace");
}
else while(index<str.length() && Character.isDigit(str.charAt(index)))
{
System.out.print(str.charAt(index));
index++;
}
//close input scanner object
input.close();
}
}
Im having trouble with a few things:
- I cant seem to get my while loop to keep the '+' or '-' in my output.
- I cant seem to get the while loop to trim leading and trailing whitespace from my output.
- Im having trouble getting the program to detect if the first character is not a digit or '+' or '-' before executing the loop.
Any suggestions are appreciated! Thanks!
答案1
得分: 1
public class stringManipulator {
public static void main(String... args) {
Scanner scan = new Scanner(System.in);
System.out.println(readNumber(scan));
}
public static String readNumber(Scanner scan) {
System.out.print("输入一个字符串:");
String str = scan.nextLine();
if (str.isEmpty())
return "返回 0:字符串为空";
if (str.trim().isEmpty())
return "返回 0:字符串只包含空白字符";
if (str.charAt(0) != '+' && str.charAt(0) != '-' && !Character.isDigit(str.charAt(0)))
return "返回 0:字符串不以数字或+/-开头";
StringBuilder buf = new StringBuilder(str.length());
for (int i = 0; i < str.length(); i++)
if (i == 0 || Character.isDigit(str.charAt(i)))
buf.append(str.charAt(i));
return buf.toString();
}
}
英文:
public class stringManipulator {
public static void main(String... args) {
Scanner scan = new Scanner(System.in);
System.out.println(readNumber(scan));
}
public static String readNumber(Scanner scan) {
System.out.print("Enter a string: ");
String str = scan.nextLine();
if (str.isEmpty())
return "return 0: String is empty";
if (str.trim().isEmpty())
return "return 0: String is only whitespace";
if (str.charAt(0) != '+' && str.charAt(0) != '-' && !Character.isDigit(str.charAt(0)))
return "return 0: String does not start with a number or +/-";
StringBuilder buf = new StringBuilder(str.length());
for (int i = 0; i < str.length(); i++)
if (i == 0 || Character.isDigit(str.charAt(i)))
buf.append(str.charAt(i));
return buf.toString();
}
}
答案2
得分: 0
以下是您要求的代码部分的中文翻译:
// 建议将功能实现在一个单独的方法中,返回特定的结果以便于测试。
private static String process(String str) {
if (null == str || str.isEmpty()) {
return "0: 空字符串";
}
str = str.trim();
if (str.isEmpty()) {
return "0: 空格字符串";
}
char first = str.charAt(0);
if (!(Character.isDigit(first) || first == '+' || first == '-')) {
return "0: 不是数字";
}
StringBuilder sb = new StringBuilder();
for (int i = 1; i < str.length(); i++) {
char c = str.charAt(i);
if (Character.isDigit(c)) {
sb.append(c);
} else {
break;
}
}
// 针对像 +asd、-dsf 这样的输入进行额外验证
if (sb.length() == 0 && (first == '+' || first == '-')) {
return "0: 不是有符号数字";
}
return first + sb.toString();
}
测试部分:
String[] tests = {
"", "acv", "-", "+", "12", "-01", "12dgr", "12+12", "34 23", "45-34",
"+346", "-14", "-fe", "+hrr", "-12ggg", "+43gd"
};
Arrays.asList(tests).forEach(s -> System.out.printf("'%s' -> %s%n", s, process(s)));
输出:
'' -> 0: 空字符串
'acv' -> 0: 不是数字
'-' -> 0: 不是有符号数字
'+' -> 0: 不是有符号数字
'12' -> 12
'-01' -> -01
'12dgr' -> 12
'12+12' -> 12
'34 23' -> 34
'45-34' -> 45
'+346' -> +346
'-14' -> -14
'-fe' -> 0: 不是有符号数字
'+hrr' -> 0: 不是有符号数字
'-12ggg' -> -12
'+43gd' -> +43
另外,正则表达式可以用来验证输入并去除多余部分。假设要返回一个有效的整数,可以使用以下方法:
private static int processReg(String str) {
str = str.trim();
if (str.isEmpty() || !str.matches("[-+\\d]\\d+.*")) { // 不以数字、+或-开头
return 0;
}
String num = str.replaceAll("[^-+0-9]", " ") // 将“非数字”字符替换为空格
.trim()
.replaceAll("([-+\\d]\\d+)(.*)", "$1"); // 保留第一个数字
return Integer.parseInt(num);
}
测试部分:
Arrays.asList(tests).forEach(s -> System.out.printf("'%s' -> %d%n", s, processReg(s)));
输出较为简洁:
'' -> 0
'acv' -> 0
'-' -> 0
'+0' -> 0
'12' -> 12
'-01' -> -1
'12dgr' -> 12
'12+12' -> 12
'34 23' -> 34
'45-34' -> 45
'+346' -> 346
'-14' -> -14
'-fe' -> 0
'+hrr' -> 0
'-12ggg' -> -12
'+43gd' -> 43
英文:
It's better to implement functionality in a separate method returning a specific result to facilitate testing.
private static String process(String str) {
if (null == str || str.isEmpty()) {
return "0: empty";
}
str = str.trim();
if (str.isEmpty()) {
return "0: whitespace";
}
char first = str.charAt(0);
if (!(Character.isDigit(first) || first == '+' || first == '-')) {
return "0: not a number";
}
StringBuilder sb = new StringBuilder();
for (int i = 1; i < str.length(); i++) {
char c = str.charAt(i);
if (Character.isDigit(c)) {
sb.append(c);
} else {
break;
}
}
// additional validation of inputs like +asd, -dsf
if (sb.length() == 0 && (first == '+' || first == '-')) {
return "0: not a signed number";
}
return first + sb.toString();
}
Test:
String[] tests = {
"", "acv", "-", "+", "12", "-01", "12dgr", "12+12", "34 23", "45-34",
"+346", "-14", "-fe", "+hrr", "-12ggg", "+43gd"
};
Arrays.asList(tests).forEach(s -> System.out.printf("'%s' -> %s%n", s, process(s)));
Output:
'' -> 0: empty
'acv' -> 0: not a number
'-' -> 0: not a signed number
'+' -> 0: not a signed number
'12' -> 12
'-01' -> -01
'12dgr' -> 12
'12+12' -> 12
'34 23' -> 34
'45-34' -> 45
'+346' -> +346
'-14' -> -14
'-fe' -> 0: not a signed number
'+hrr' -> 0: not a signed number
'-12ggg' -> -12
'+43gd' -> +43
Also, regular expressions may be used to validate input and remove redundant parts.
Assuming that a valid integer is to be returned, the method may be implemented as follows:
private static int processReg(String str) {
str = str.trim();
if (str.isEmpty() || !str.matches("[-+\\d]\\d+.*")) { // does not start with digit,+,-
return 0;
}
String num = str.replaceAll("[^-+0-9]", " ") // make "not-numeric" symbols blank
.trim()
.replaceAll("([-+\\d]\\d+)(.*)", "$1"); // keep the first number
return Integer.parseInt(num);
}
Test:
Arrays.asList(tests).forEach(s -> System.out.printf("'%s' -> %d%n", s, processReg(s)));
Output less verbose:
'' -> 0
'acv' -> 0
'-' -> 0
'+0' ->
'12' -> 12
'-01' -> -1
'12dgr' -> 12
'12+12' -> 12
'34 23' -> 34
'45-34' -> 45
'+346' -> 346
'-14' -> -14
'-fe' -> 0
'+hrr' -> 0
'-12ggg' -> -12
'+43gd' -> 43
答案3
得分: 0
这就是我想出的解决方案,感谢所有的反馈和帮助!
import java.util.Scanner;
public class stringManipulator
{
public static void main (String[]args)
{
// 初始化一个名为input的新System.in扫描对象
Scanner input = new Scanner(System.in);
// 初始化变量
int index = 1;
// 提示用户输入一个字符串
System.out.println("输入一个字符串:");
// 将修剪过的用户输入存储在字符串变量str中
String str = input.nextLine();
str = str.trim();
// 测试字符串是否为空或仅包含空格
if(str.length()==0)
{
System.out.println("返回0:字符串为空或仅为空白字符");
}
// 测试字符串是否以数字、'+'或'-'开头
else if (str.charAt(0) == '+' || str.charAt(0) == '-' || Character.isDigit(str.charAt(0)))
{
// 打印'+'、'-'或字符串的第一个数字
System.out.print(str.charAt(0));
// 循环打印str的字符,直到字符串长度,只要它们是数字
while(index<str.length() && Character.isDigit(str.charAt(index)))
{
System.out.print(str.charAt(index));
index++;
}
}
// 如果字符串以除'+'、'-'或数字以外的任何字符开头,则输出
else
{
System.out.println("返回0:字符串不是数字,或者不以'+'或'-'开头");
}
// 关闭输入扫描对象
input.close();
}
}
<details>
<summary>英文:</summary>
This ended up being the solution I came to, thanks for all the feedback and help!
import java.util.Scanner;
public class stringManipulator
{
public static void main (String[]args)
{
//initialize new system.in scanner object named input
Scanner input = new Scanner(System.in);
//initialize variables
int index = 1;
//prompt user for a string as input
System.out.println("Enter a string: ");
//store trimmed user input in string variable str
String str = input.nextLine();
str = str.trim();
//test if string is empty or contains only whitespace
if(str.length()==0)
{
System.out.println("Return 0: String is empty or is only whitespace");
}
//tests if string starts with a digit, '+', or '-'
else if (str.charAt(0) == '+' || str.charAt(0) == '-' || Character.isDigit(str.charAt(0)))
{
//prints '+', '-', or first digit of string
System.out.print(str.charAt(0));
//loop prints characters of str up to string length as long as they are digits
while(index<str.length() && Character.isDigit(str.charAt(index)))
{
System.out.print(str.charAt(index));
index++;
}
}
//output if the string starts with anything other than '+', '-', or a digit
else
{
System.out.println("Return 0: String is not a number or does not begin with '+' or '-'");
}
//close input scanner object
input.close();
}
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论