【发布时间】:2020-10-18 21:05:53
【问题描述】:
这是我的代码需要做的:
"此代码将字符串作为输入,如果字符串为空、仅包含空格或不以数字或 +/- 开头,则返回 0。否则,代码会将字符串作为修剪后的数字返回(否前导或尾随空格),数字后面没有尾随字母。”
这就是我所拥有的:
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();
}
}
我遇到了一些问题:
- 我似乎无法让我的 while 循环在输出中保留“+”或“-”。
- 我似乎无法让 while 循环从我的输出中修剪前导和尾随空格。
- 我无法让程序在执行循环之前检测第一个字符是否不是数字或“+”或“-”。
欢迎提出任何建议!谢谢!
【问题讨论】:
-
else while不存在,将整个 while 循环放在 else 块中 -
是的,就像 azro 说的,
else while不是有效的 java。你可以把它改成else if