我试图打电话给我的扫描仪,但它无法正常工作。我该怎么办?

时间:2013-09-21 22:54:43

标签: java java.util.scanner

import java.util.Scanner;

public class Words
{
    public static void main (String[] args)
{
    Scanner myScan = new Scanner(System.in);
    String s1;
    int myAge;
    int time = 6;

    System.out.print("What is your name? ");
    s1 = myScan.nextLine();

    System.out.print("How old are you? ");
    myAge = myScan.nextInt(); 

    System.out.println("Really? Cause I am " + (myAge+3) + ". " + "Lets's meet up! ");
    s1 = myScan.nextLine();

    }
}

//在最后一个命令之后,它不会让我在终端窗口中输入任何内容。请帮忙。

2 个答案:

答案 0 :(得分:3)

之间添加nextLine()
System.out.print("How old are you? ");
myAge = myScan.nextInt(); 

myScan.nextLine(); // add this

System.out.println("Really? Cause I am " + (myAge+3) + ". " + "Lets's meet up! ");
s1 = myScan.nextLine();

这是必需的,因为nextInt()仅消耗它读取的int值,而不是它后面的任何行尾字符。

nextLine()将使用\r\n(或行/分隔符的任何结尾),下一个令牌可供另一个nextLine()使用。

答案 1 :(得分:0)

在插入int后输入enter。 nextline将输入为一行。 你需要的是在nextint之后添加一个额外的nextline调用,如下所示:

import java.util.Scanner;

public class Words
{
    public static void main (String[] args)
    {
        Scanner myScan = new Scanner(System.in);
        String s1;
        int myAge;
        int time = 6;

        System.out.print("What is your name? ");
        s1 = myScan.nextLine();

        System.out.print("How old are you? ");
        myAge = myScan.nextInt(); 
        s1 = myScan.nextLine();

        System.out.println("Really? Cause I am " + (myAge+3) + ". " + "Lets's meet up! ");
        s1 = myScan.nextLine();
    }
}