繁体   English   中英

Java Scanner 没有这样的元素异常

[英]Java Scanner No Such Element Exception

编辑:已解决

我在让我的扫描仪正常工作时遇到问题。 我在谷歌上搜索了很多关于这个,他们建议放置一个 hasNextInt() 但这只是跳过 nextLine ,所以它继续使用默认值选择垃圾输出。 如果我取出 hasNextInt,它会给出 No such Element Exception。 问题出在战斗方法上。 源代码如下。

public static void game()
{
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println();
    StarterSword starterw = new StarterSword();
    weapons[0] = starterw;
    StarterArmour startera = new StarterArmour();
    armour[0] = startera;
    Heal heal = new Heal();
    items[0] = heal;

    System.out.println();
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("Lets start with an easy monster fight first.\nLater on it will be harder as monsters evolve.");

    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    int[] b = fight(a, starterw, startera, heal);
    a++;
    int coin = b[0];
    coins = coins + coin;
    System.out.println("You now have " + coins + " coins");
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    contGame();
}

public static void contGame(){
    System.out.println("Now a slightly harder boss!");
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Scanner choose = new Scanner(System.in);
    while(a <= 40)
    {
        Weapon weapon = PVMGame.weapons[0];
        Armour armour = PVMGame.armour[0];
        Items heal = PVMGame.items[0];
        int[] b = fight(a, weapon, armour, heal);
        int coin = b[0];
        coins = coins + coin;
        System.out.println("You now have " + coins + " coins");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if(b[1] == 1)
        {

            System.out.println("You won! You can go to the next level!");
            a++;
        }
        else
        {

            System.out.println("You lost!");

        }
        choose.close();

    }

}

public static int[] fight(int level, Weapon weapon, Armour armour, Items heal){

    int[] a = new int[2];
    int b = 0;
    int c = 0;
    int damage;
    int health ;
    health = level * 30;
    damage = (level * 4) - 1;
    System.out.println("\nThis Monster has " + health + " health and " + damage + " damage.\n1)Attack\n2)Use Heal(You can only have one of each type of item)\n3)QUIT THIS WHOLE PROGRAMME!!");
    boolean isAlive = true;
    boolean isPAlive = true;
    boolean win = false;
    int pHealth = armour.hp;
    int attack = weapon.damage;
    int healing = heal.healHP;
    String weaponT = weapon.name;
    String armourT = armour.name;
    String healT = heal.name;
    int max = pHealth;
    int totalD = 0;
    int choice = 1;
    @SuppressWarnings("resource")
    Scanner userInput = new Scanner(System.in);
    while(isAlive && isPAlive){

        if(userInput.hasNextInt()){
            choice = userInput.nextInt(); //This is where it goes wrong
        }
        if(choice == 1)
        {

            health = health - attack;

            System.out.println("\nYou inflicted " + attack + " damage on the enemy with your" + weaponT + "\nHe now only has " + health + " health left.");
            if(health <= 0){

                b = (level * 40) - 5;
                System.out.println("You defeated the monster! You won " + b + " coins.");
                a[0] = b;
                win = true;
                isAlive = false;
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            pHealth = pHealth - damage;
            System.out.println("\nThe Monster inflicted " + damage + " damage on your" + armourT + "\nYou only have " + pHealth + " health left.");
            totalD = totalD + damage;
            if(pHealth <= 0){

                System.out.println("You failed.");
                    isPAlive = false;
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            System.out.println("\n1)Attack\n2)Use Heal\n3)QUIT THIS WHOLE PROGRAMME!!");

        }
        else if(choice == 2)
        {
            pHealth = pHealth + healing;
            if(pHealth > max){
                healing = totalD;
                pHealth = max;
            }
            if(healing != 0){
                System.out.println("\nYou healed " + healing + " health on yourself with your" + healT + "\nYou have " + pHealth + " health left.");
            }
            else{
                System.out.println("You have no healing potions left!");
            }
            healing = 0;

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            pHealth = pHealth - damage;
            System.out.println("\nThe Monster inflicted " + damage + " damage on your" + armourT + "\nYou only have " + pHealth + " health left.");
            totalD = totalD + damage;
            if(pHealth <= 0){

                System.out.println("You failed.");
                    isPAlive = false;
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            System.out.println("\n1)Attack\n2)Use Heal\n3)QUIT THIS WHOLE PROGRAMME!!");

        }
        else if(choice == 3)
        {
            System.exit(0);
        }
        else
        {
            System.out.println("TYPE EITHER 1, 2, OR 3");
            fight(level,weapon,armour,heal);
        }

    }
    if(win){

        c = 1;

    }
    if(win == false){

        c = 0;

    }
    a[1] = c;
    return a;
}

问题在这里:

if(userInput.hasNextInt()){
    choice = userInput.nextInt(); //This is where it goes wrong
}

您没有处理 else 情况。 把它改成这样:

if(userInput.hasNextInt()){
    choice = userInput.nextInt(); //This is where it goes wrong
} else {
    System.out.println("Invalid input");
    userInput.nextLine(); // Ignore till the end of line
    continue; // Continue again
}

正如我在评论中提到的,发生这种情况是因为一旦System.in流关闭,如果System.in流关闭,则无法重新打开它。 您可以从NoSuchElementException错误中看到这种情况。 如果您按预期输入其他内容而不是整数作为输入,您将得到InputMismatchException

看到这个这个相关的问题。

因此,您最好使用全局Scanner并在退出程序时关闭流一次,这是最好和最简单的解决方案。

您也可以忽略来自 IDE 的任何警告,并且永远不要关闭您打开的System.in流。

最后,在我引用的第二个链接中演示的另一个想法是为System.in创建一个FileInputStream包装器,并且永远不要调用 close。 下面是一个例子:

Scanner sc = new Scanner(new FilterInputStream(System.in){public void close(){}});

稍后,您可以执行sc.close() ,但System.in将保持打开状态,因为sc.close()不执行任何操作。

这对我来说似乎太过分了。 我会采用全局Scanner方式。

最后,期待其他类型的价值观是一个明智的选择,所以我会记住@KDM 的建议。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM