日期:2014-05-20  浏览次数:20679 次

java 输入回车问题
Scanner s=new Scanner(System.in); //输入数据
Random random=new Random(); //产生随机数
int [] guessNumber=new int[4]; //保存玩家输入的数

for(int i=0;i<4;i++)
{
  guessNumber[i]=s.nextInt();
}
 我想如果在循环里,输入回车的时候执行某个命令,怎么写??不懂呀!!初学java,请大家帮忙哈!谢谢了!!

------解决方案--------------------
哦 哦 原来楼主是这个意思啊,
Java code
import java.util.Scanner;

public class Test
{

    static int[] guessNumber = new int[4]; // 保存玩家输入的数

    static Scanner s;

    static int i;

    public static void main(String[] args)
    {
        w();
    }

    public static void w()
    {    
        System.out.println("输入结束请按回车然后ctrl+z");
        
        StringBuffer sb = new StringBuffer();
        
        s = new Scanner(System.in);
        
        while (s.hasNext())
        {
            sb = sb.append(s.next() + " ");
        }
        
        if (4 != sb.toString().split(" ").length)
        {
            System.out.println("输入不正确");
        }
        else
        {
            System.out.println("输入正确");
            
            for (int i = 0; i < 4; i++)
            {
                guessNumber[i] = Integer.parseInt(sb.toString().split(" ")[i]);
            }
            
            System.out.print("数组内容为:  ");
            
            for (int number : guessNumber)
            {
                System.out.print(number + " ");
            }
        }
    }
}

------解决方案--------------------
经我测试了可以。。。 
package task;
import java.util.Scanner;

public class Panduan{

static int[] guessNumber = new int[4]; // 保存玩家输入的数

public static void main(String[] args)
{
w();
}

public static void w()
{
Scanner s = new Scanner(System.in);

System.out.println("情输入四个数,按回车结束!");
String str = new String();
str = s.nextLine();
String str1[] = new String[4];
str1 = str.split(" ");

if (4 != str1.length)
{
System.out.println("请输入四个数!");
return;
}
else
{
System.out.println("输入正确");
String str2 ="";

for (int i = 0; i < 4; i++)
{
str2+=str1[i];
}
System.out.print("数组内容为: "+str2);


}
}
}