有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中拆分字符串的问题

我在用多个参数拆分字符串时遇到问题,我必须拆分的字符串由空格、逗号、数字符号和冒号组成。我试图按每个参数拆分字符串,但由于我多次拆分字符串,因此在输出中多次打印内容时遇到了问题。我尝试使用数组,但没有成功,因为它只查找空格,而不查找其他参数。然后我想到了一个使用定界符的主意,这个主意非常好,直到我遇到一个错误,程序将继续无休止地运行,而不会输出任何东西。因此,我需要的帮助是能够以给定格式分解字符串语句。以下是输入:克拉克,肯,XL:Steelers,匹兹堡:沃德#86以下是我应该得到的输出:

  • 肯克拉克
  • XL
  • 匹兹堡
  • 钢铁工人
  • 病房-86

以下是我目前的代码:

public class NFL_Jersey_Order {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       
       Scanner scan = new Scanner(System.in); 
       System.out.println("Enter Order Information: ");
       //String name1 = scan.nextLine(); 
       scan.useDelimiter(",");
        
       String last = scan.next();
       String first = scan.next();
       first = first.trim();
        
       scan.useDelimiter(" ");
       String space1 = scan.next();
       String size = scan.next(); 
       //size = size.trim(); 
       
       scan.useDelimiter(" ");
       String space3 = scan.next(); 
       String space4 = scan.next(); 
       
       scan.useDelimiter(" ");
       String city = scan.next();
       
       scan.useDelimiter(" ");
       String space5 = scan.next(); 
       String player = scan.next(); 

 System.out.print(first + " " + last + "\n" + size + "\n" + space4 + "\n" + player);
}
}

共 (1) 个答案

  1. # 1 楼答案

    我自己设法弄明白了,然后又开始使用数组

    public class Order_2 {
    
       
        public static void main(String[] args) {
            
          Scanner scan = new Scanner(System.in); 
          System.out.println("Enter Order Information: ");
          String name1 = scan.nextLine();
          
          String substrings[] = name1.split("[,:# ]"); 
          
          
          String team = substrings[7];
          substrings[7] = team.toUpperCase();
          
          
            
            System.out.println(substrings[2] + "\n" + substrings[0] + "\n" + substrings[4] + "\n" + substrings[8] + "\n" + substrings[7] + "\n" + substrings[11] + "-" + substrings[12]);
         
          
          
      
        }
    }