java循环,if else [英] java loop, if else

查看:414
本文介绍了java循环,if else的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是非常简单的事情,但是,我只编程了几个月,所以我的大脑有时会出现雾,我需要帮助一个带有嵌套的else if语句的while循环。问题我的循环是连续的,因为用户永远不会有机会输入他们的选择(-1停止循环)。如何通过要求用户输入选项(1-4或-1退出)来更改循环以便操作

I know this is something very simple, however, I've only been programming for a couple months so my brain just fog's out sometimes, and I need help with a while loop with nested else if statements. The problem my loop is continuous because the user is never given the chance to enter in their choice (which -1 stops the loop). How can I change the loop so that it operates by asking user to enter a choice (1-4, or -1 to quit)

请提供任何帮助。我知道这很简单,我已经在之前的论坛讨论中进行了搜索,但我似乎无法使其发挥作用。

Please Any help is appreciated. I know it's something simple, I've searched thorugh previous forum discussions but I can't seem to make it work.

//create new scanner object 
    Scanner userInput = new Scanner (System.in);
    int end = 0;
    //find out what user wants to do with address book
    while (end != -1)
    {
        System.out.println("  ");
        System.out.println("  ");
        System.out.println("----------------------------");
        System.out.println("What would you like to do with your address book? ...");
        System.out.println("----------------------------");
        System.out.println("Add new         [Enter 1]");
        System.out.println("Delete existing [Enter 2]");
        System.out.println("Edit existing   [Enter 3]");
        System.out.println("Search for      [Enter 4]");
        System.out.println("EXIT            [Enter -1]");
    }

    if (userInput.hasNext() && (userInput.nextInt() == 1)) 
    {
        AddressBookProcessor.addContact();
    }
    else if (userInput.hasNext() && userInput.nextInt() == 2)
    {
        AddressBookProcessor.deleteContact();
    }
    else if (userInput.hasNext() && userInput.nextInt() == 3)
    {
        AddressBookProcessor.editContact();
    }
    else if (userInput.hasNext() && userInput.nextInt() == 4)
    {
        AddressBookProcessor.findContact();
    }
    else if (userInput.nextInt() != 1 || userInput.nextInt() != 2 
                     || userInput.nextInt() != 3 || userInput.nextInt() != -1)
    {
        System.out.println("Please enter a valid input");
        end = -1;
    }




}


推荐答案

在while循环中移动你的if / else。

Move your if/else's inside the while loop.

这篇关于java循环,if else的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆