编程论坛's Archiver

Ethip 发表于 2008-5-8 19:55

Java中输入String类型和int类型数据的先后顺序

J2SE疏于学习,不纯熟。遇到了问题!

刚才在pfan中回帖时,发现了个问题。
要求从console下输入一个String类型和一个int类型的数据,如先输入String类型的,没有错误;若要求先输入int类型的数据,再输入String类型的数据。就会有错误!
将源代码中的name = sc.nextLine();和age = sc.nextInt();的先后顺序调换后,就没有问题!
我的IDE是[color=#ff0000]eclipse3.3[/color]
[color=#ff0000]源代码如下:[/color]
/***
* 要求用户输入int,String等类型数据时,先输入String
*/
package test;

import java.util.Scanner;

class Cat {
    private int age = 0;
    private String name = null;

    public void showMessage() {
        System.out.println("The cat's name is " + name + "! It is " + age
                + " years old.");
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

public class InputAttation {
    public static void main(String[] args) {
        String name = null;
        int age = 0;
        // 定义输出流
        Scanner sc = new Scanner(System.in);
        // 提示用户输入,注意:先输入字符串,否则会有错误!
        [color=red][bo]System.out.println("Input the age of the cat:  ");
        if(sc.hasNextInt())
            age = sc.nextInt();
        System.out.println("Input the name of the cat:  ");
        name = sc.nextLine();[/bo]    [/color]    // 实例化类Cat
        Cat cat = new Cat();
        // 给属性赋值
        cat.setAge(age);
        cat.setName(name);
        cat.showMessage();
    }
}

hanzhu3366 发表于 2008-5-13 22:56

回复 1# 的帖子

謝謝,我剛剛遇見這樣的問題!

sunkaidong 发表于 2008-5-13 23:09

age = Integer.parseInt(sc.nextLine());

Ethip 发表于 2008-5-15 20:01

回复 3# 的帖子

貌似!我试试![tk10]

Ethip 发表于 2008-5-15 20:10

回复 3# 的帖子

[tk11] Over![tk16]

大活宝 发表于 2008-5-25 10:38

好^^^好^^好^^

爪哇小帥哥 发表于 2008-5-25 11:36

我也試試

页: [1]

Powered by Discuz! Archiver 6.1.0  © 2001-2007 Comsenz Inc.