-4

次の形式のユーザーからの入力があります。

1234 abc def gfh
..
8789327 kjwd jwdn
stop

今、スキャナーを使用し、次に使用する場合

Scanner sc=new Scanner(System.in);
String t=sc.nextLine();
while(!t.equals("stop"))
{
    int i=sc.nextInt();
    int str=sc.nextLine();
    t=sc.nextLine();
}

i=1234 str="abc def gfh" ... などを取得し、ユーザーが停止を入力すると停止する方法はありますか?

正規表現を使用せずに、数値と文字列を別々に受け入れたいです。また、キーワード「stop」で入力の受け付けを停止したい。

4

3 に答える 3

1

の値を変更することはないtため、ファイルの最初の行が。でない限り、while条件は常にtrueになりますstop

于 2012-10-26T15:15:15.573 に答える
1

まず第一に、受け入れられた入力に対して何もしていません。次の入力を無視するだけです。

次に、scanner.nextLine()読み取った次の行である文字列を返します。stringトークンを個別に取得するには、読み取りを分割して取得する必要があります。

3 番目に、次の入力があるかどうかを while でチェックする必要がscanner#hasNextLineありtrueます。

各トークンを個別に読み取りたい場合Scanner#nextは、次に読み取ったトークンを返すメソッドを使用することをお勧めします。

integersまた、とを読みたいstringsので、整数を持っているかどうかもテストする必要があります。Scanner#hasNextIntそのためにはメソッドを使用する必要があります。

各行integerで個別に読みたいので、わかりました。string

あなたが試すことができるものは次のとおりです: -

while (scanner.hasNextLine()) {  // Check whether you have nextLine to read

    String str = scanner.nextLine(); // Read the nextLine

    if (str.equals("stop")) {  // If line is "stop" break
        break;
    }

    String[] tokens = str.split(" ", 1);  // Split your string with limit 1
                                          // This will give you 2 length array

    int firstValue = Integer.parseInt(tokens[0]);  // Get 1st integer value
    String secondString = tokens[1];  // Get next string after integer value
}
于 2012-10-26T15:20:43.113 に答える
1

あなたのコード:

Scanner sc=new Scanner(System.in);
String t=sc.nextLine();
while(!t.equals("stop"))
{
    int i=sc.nextInt();
    int str=sc.nextLine();
    t=sc.nextLine();
}

まず第一に、文字列を返すのint str=sc.nextLine();で間違っています。nextLine()私によると、あなたができることは次のとおりです。

 Scanner sc=new Scanner(System.in);
    String t=sc.nextLine();
    int i;
    String str="";
    while(!t.equals("stop"))
    {
        int index=t.indexOf(" ");
        if(index==-1)
           System.out.println("error");
        else{
               i=Integer.parseInt(t.substring(0,index));
               str=t.substring(index+1);
        }
        t=sc.nextLine();
    }

お役に立てば幸いです。

于 2012-10-26T15:41:54.653 に答える