需要帮助将字符串拆分为两个单独的整数进行处理

时间:2011-09-10 20:12:15

标签: java substring indexof parseint

我正在研究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);
    }
 }

3 个答案:

答案 0 :(得分:2)

子串可以工作,但我建议查看String.split。

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

String.split采用正则表达式字符串,因此您可能不想只在其中输入任何字符串。

尝试这样的事情:

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

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

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

希望这能让你开始。

答案 1 :(得分:1)

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

答案 2 :(得分:1)

制作本

    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]);
    }
相关问题