2015-02-10 67 views
-1

我有一个输入包含任意2个数字在一行上,可以有无限数量的行,例如。我如何将输入吐入2?

 30 60 
     81 22 
     38 18 

我想将每一行分成2个标记,第一个标记是左边的数字,第二个标记是右边的数字。我该怎么办?所有的帮助表示赞赏。

+0

请分享您的代码或至少告诉我们尝试了什么。 – hanumant 2015-02-10 04:39:23

回答

1

随着扫描仪和System.in:

public class SplitTest 
{ 
    public static void main (final String[] args) 
    { 
     try (Scanner in = new Scanner (System.in)) 
     { 
      while (in.hasNext()) 
      { 
       System.out.println ("Part 1: " + in.nextDouble()); 
       if (in.hasNext()) 
        System.out.println ("Part 2: " + in.nextDouble()); 
      } 
     } 
     catch (final Throwable t) 
     { 
      t.printStackTrace(); 
     } 
    } 
} 
+0

我需要通过扫描仪接收来自用户的输入,输入可以是单个行上的任意两个数字,也可以是不限数量的行。 – 2015-02-10 04:28:49

+0

它的工作。谢谢! – 2015-02-10 04:40:08

0

如果输入总是这样的设置,看看到String.split()

0
// For just splitting into two strings separated by whitespace 
String numString = "30 60"; 
String[] split = numString.split("\\s+"); 

// For converting the strings to integers 
int[] splitInt = new int[split.length]; 
for(int i = 0; i < split.length; i++) 
    splitInt[i] = Integer.parseInt(split[i]); 
+0

这些数字并不总是这样。 – 2015-02-10 04:23:29

+0

@danielp我不明白。我只是使用你发布的例子。 – ssh 2015-02-10 04:24:01

+0

在代码中,您将“String numString =”30 60“”,但用户可以输入任何内容,任何2个数字。我的问题中的这些数字只是一个例子。 – 2015-02-10 04:26:01

相关问题