【问题标题】:JAVA trouble with control flow and strings in school project学校项目中控制流和字符串的JAVA问题
【发布时间】: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();
    }
}

我遇到了一些问题:

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

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

【问题讨论】:

  • else while 不存在,将整个 while 循环放在 else 块中
  • 是的,就像 azro 说的,else while 不是有效的 java。你可以把它改成else if

标签: java string loops


【解决方案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("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】:

    最好在单独的方法中实现功能,返回特定的结果以方便测试。

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

    测试:

    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: 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
    

    此外,正则表达式可用于验证输入并删除冗余部分。 假设要返回一个有效的整数,该方法可以实现如下:

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

    测试:

    Arrays.asList(tests).forEach(s -> System.out.printf("'%s' -> %d%n", s, processReg(s)));
    

    输出不那么冗长:

    '' -> 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】:

      这最终成为了我的解决方案,感谢所有反馈和帮助!

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-23
        • 2017-07-31
        • 2015-08-26
        • 2011-03-04
        • 2013-02-07
        • 1970-01-01
        • 2019-09-01
        • 1970-01-01
        相关资源
        最近更新 更多