JAVA在学校项目中的控制流和字符串问题。

huangapple go评论72阅读模式
英文:

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();
    }
}

我遇到了一些问题:

  1. 我似乎无法让我的 while 循环在输出中保留 '+' 或 '-'。
  2. 我似乎无法让 while 循环修整输出中的前导和尾随空白字符。
  3. 在执行循环之前,我无法让程序检测第一个字符是否不是数字、'+' 或 '-'。

欢迎提出任何建议!谢谢!

英文:

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(&quot;Enter a string: &quot;);
		
		//store user input in string variable str
		String str = input.nextLine();
		
		//edit and output user inputed string
		if(str.length()==0)
		{
			System.out.println(&quot;return 0: String is empty&quot;);
		}
		else if(str.trim().length()==0)
		{
			System.out.println(&quot;return 0: String is only whitespace&quot;);
		}
		else while(index&lt;str.length() &amp;&amp; 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:

  1. I cant seem to get my while loop to keep the '+' or '-' in my output.
  2. I cant seem to get the while loop to trim leading and trailing whitespace from my output.
  3. 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(&quot;Enter a string: &quot;);
        String str = scan.nextLine();

        if (str.isEmpty())
            return &quot;return 0: String is empty&quot;;
        if (str.trim().isEmpty())
            return &quot;return 0: String is only whitespace&quot;;
        if (str.charAt(0) != &#39;+&#39; &amp;&amp; str.charAt(0) != &#39;-&#39; &amp;&amp; !Character.isDigit(str.charAt(0)))
            return &quot;return 0: String does not start with a number or +/-&quot;;

        StringBuilder buf = new StringBuilder(str.length());

        for (int i = 0; i &lt; 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 &quot;0: empty&quot;;
    }
    str = str.trim();
    if (str.isEmpty()) {
        return &quot;0: whitespace&quot;;
    }
    char first = str.charAt(0);
    if (!(Character.isDigit(first) || first == &#39;+&#39; || first == &#39;-&#39;)) {
        return &quot;0: not a number&quot;;
    }

    StringBuilder sb = new StringBuilder();
    for (int i = 1; i &lt; 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 &amp;&amp; (first == &#39;+&#39; || first == &#39;-&#39;)) {
        return &quot;0: not a signed number&quot;;
    }

    return first + sb.toString();
}

Test:

String[] tests = {
    &quot;&quot;, &quot;acv&quot;, &quot;-&quot;, &quot;+&quot;, &quot;12&quot;, &quot;-01&quot;, &quot;12dgr&quot;, &quot;12+12&quot;, &quot;34 23&quot;, &quot;45-34&quot;, 
    &quot;+346&quot;, &quot;-14&quot;, &quot;-fe&quot;, &quot;+hrr&quot;, &quot;-12ggg&quot;, &quot;+43gd&quot;
};

Arrays.asList(tests).forEach(s -&gt; System.out.printf(&quot;&#39;%s&#39; -&gt; %s%n&quot;, s, process(s)));

Output:

&#39;&#39; -&gt; 0: empty
&#39;acv&#39; -&gt; 0: not a number
&#39;-&#39; -&gt; 0: not a signed number
&#39;+&#39; -&gt; 0: not a signed number
&#39;12&#39; -&gt; 12
&#39;-01&#39; -&gt; -01
&#39;12dgr&#39; -&gt; 12
&#39;12+12&#39; -&gt; 12
&#39;34 23&#39; -&gt; 34
&#39;45-34&#39; -&gt; 45
&#39;+346&#39; -&gt; +346
&#39;-14&#39; -&gt; -14
&#39;-fe&#39; -&gt; 0: not a signed number
&#39;+hrr&#39; -&gt; 0: not a signed number
&#39;-12ggg&#39; -&gt; -12
&#39;+43gd&#39; -&gt; +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(&quot;[-+\\d]\\d+.*&quot;)) { // does not start with digit,+,-
        return 0;
    }
    String num = str.replaceAll(&quot;[^-+0-9]&quot;, &quot; &quot;) // make &quot;not-numeric&quot; symbols blank
                    .trim()
                    .replaceAll(&quot;([-+\\d]\\d+)(.*)&quot;, &quot;$1&quot;);  // keep the first number
    return Integer.parseInt(num);
}

Test:

Arrays.asList(tests).forEach(s -&gt; System.out.printf(&quot;&#39;%s&#39; -&gt; %d%n&quot;, s, processReg(s)));

Output less verbose:

&#39;&#39; -&gt; 0
&#39;acv&#39; -&gt; 0
&#39;-&#39; -&gt; 0
&#39;+0&#39; -&gt; 
&#39;12&#39; -&gt; 12
&#39;-01&#39; -&gt; -1
&#39;12dgr&#39; -&gt; 12
&#39;12+12&#39; -&gt; 12
&#39;34 23&#39; -&gt; 34
&#39;45-34&#39; -&gt; 45
&#39;+346&#39; -&gt; 346
&#39;-14&#39; -&gt; -14
&#39;-fe&#39; -&gt; 0
&#39;+hrr&#39; -&gt; 0
&#39;-12ggg&#39; -&gt; -12
&#39;+43gd&#39; -&gt; 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(&quot;Enter a string: &quot;);
	
	//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(&quot;Return 0: String is empty or is only whitespace&quot;);
	}
	//tests if string starts with a digit, &#39;+&#39;, or &#39;-&#39;
	else if (str.charAt(0) == &#39;+&#39; || str.charAt(0) == &#39;-&#39; || Character.isDigit(str.charAt(0)))
	{	
		//prints &#39;+&#39;, &#39;-&#39;, 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&lt;str.length() &amp;&amp; Character.isDigit(str.charAt(index)))
		{
			System.out.print(str.charAt(index));
			index++;
		}
	}
	//output if the string starts with anything other than &#39;+&#39;, &#39;-&#39;, or a digit
	else 
	{
		System.out.println(&quot;Return 0: String is not a number or does not begin with &#39;+&#39; or &#39;-&#39;&quot;);
	}

	//close input scanner object
	input.close();
}

}


</details>



huangapple
  • 本文由 发表于 2020年10月19日 05:05:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/64418328.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定