【问题标题】:Need help splitting a string into two separate integers for processing需要帮助将字符串拆分为两个单独的整数进行处理
【发布时间】:2011-11-14 12:27:03
【问题描述】:

我正在研究 java 中的一些数据结构,但我对如何将此字符串拆分为两个整数有点困惑。基本上,用户将输入一个像“1200:10”这样的字符串。我使用indexOf 来检查是否存在:,但现在我需要将冒号前的数字设置为val,并将另一个数字设置为rad。我想我应该使用substringparseInt 方法,但我不确定。下面的代码也可以在http://pastebin.com/pJH76QBb查看

import java.util.Scanner;  // Needed for accepting input

 public class ProjectOneAndreD
 {
    public static void main(String[] args)
    {
        String input1;
        char coln = ':';
        int val=0, rad=0, answer=0, check1=0;

        Scanner keyboard = new Scanner(System.in);  //creates new scanner class
        do
        {
            System.out.println("****************************************************");
            System.out.println("             This is Project 1. Enjoy!              ");     //title
            System.out.println("****************************************************\n\n");

            System.out.println("Enter a number, : and then the radix, followed by the Enter key.");
            System.out.println("INPUT EXAMPLE:  160:2   {ENTER} ");     //example

            System.out.print("INPUT:  ");               //prompts user input.
            input1 = keyboard.nextLine();       //assigns input to string input1


            check1=input1.indexOf(coln);

            if(check1==-1)
            {
                System.out.println("I think you forgot the ':'.");

            }
            else
            {
                System.out.println("found ':'");

            }
        }while(check1==-1);
    }
 }

【问题讨论】:

    标签: java substring indexof parseint


    【解决方案1】:

    子字符串可以,但我建议查看 String.split。

    split 命令将创建一个字符串数组,然后您可以使用 parseInt 获取其整数值。

    String.split 接受一个正则表达式字符串,因此您可能不想在其中放入任何字符串。

    试试这样的:

    "Your|String".split("\\|");,其中| 是分割字符串两部分的字符。

    两个反斜杠将告诉 Java 你想要那个确切的字符,而不是 | 的正则表达式解释。这仅对某些角色很重要,但更安全。

    来源:http://www.rgagnon.com/javadetails/java-0438.html

    希望这能让你开始。

    【讨论】:

      【解决方案2】:

      做这个

          if(check1==-1)
          {
              System.out.println("I think you forgot the ':'.");
      
          }
          else
          {
           String numbers [] = input1.split(":"); //if the user enter 1123:2342 this method 
      
           //will
           // return array of String which contains two elements numbers[0] = "1123" and numbers[1]="2342"
          System.out.print("first number = "+ numbers[0]);
          System.out.print("Second number = "+ numbers[1]);
          }
      

      【讨论】:

        【解决方案3】:

        您使用 indexOf 知道 : 的位置。假设字符串长度为 n 并且 : 出现在索引 i 处。然后从 0 到 i-1i+1 到 n-1 请求 substring(int beginIndex, int endIndex)。更简单的是使用String::split

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-06-20
          • 2021-07-01
          • 1970-01-01
          • 1970-01-01
          • 2017-04-15
          相关资源
          最近更新 更多