2

我正在研究 java 中的一些数据结构,我对如何将此字符串拆分为两个整数有点困惑。基本上,用户将输入一个像“1200:10”这样的字符串。我曾经indexOf检查是否有:礼物,但现在我需要将冒号前的数字设置为val并将另一个数字设置为rad。我想我应该使用substringorparseInt方法,但不确定。下面的代码也可以在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);
    }
 }
4

3 回答 3

2

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

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

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

尝试这样的事情:

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

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

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

希望这能让你开始。

于 2011-09-10T20:18:33.697 回答
1

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

于 2011-09-10T20:22:08.533 回答
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]);
    }
于 2011-09-10T20:23:08.993 回答