简体   繁体   中英

How to automatically output strings in loops

So I just have a quick little issue

 int pickmeup = 0;
        while (true)
        {
        pickmeup = scanner.nextInt();
        if (pickmeup == 1)
         {System.out.println ("you entered 1");}
        if(pickmeup == 2)
         {System.out.println ("you entered 2");}
        {
            break;
        }
    System.out.println ("Invalid code");

Now when I run this code it all works fine however in regards to the strings but it seems as though the loop doesn't work all that well when I enter '3', as it doesn't return the string 'Invalid code'.

If I were to get rid of the strings after both if statements, then it works perfectly fine. What exactly am I doing wrong? Are there other ways to automatically have strings output?

I believe you want to use a logical or || and an else like,

int pickmeup;
while (true) {
    pickmeup = scanner.nextInt();
    if (pickmeup == 1 || pickmeup == 2) {
        System.out.printf("you entered %d%n", pickmeup);
    } else {
        System.out.println("Invalid code");
    }
}

Alternatively, you could use an else if chain like,

int pickmeup;
while (true) {
    pickmeup = scanner.nextInt();
    if (pickmeup == 1) {
        System.out.println("you entered 1");
    } else if (pickmeup == 2) {
        System.out.println("you entered 2");
    } else {
        System.out.println("Invalid code");
    }
}

You could start with firstly correcting your code, you can do that in eclipse Source-Format or by pressing CTRL + SHIFT + F

For your example, I corrected as much as I understood, currently it breaks only if else is reached. Break can be modified.

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int pickmeup = 0;
    while (true){
        pickmeup = scanner.nextInt();
        if (pickmeup == 1){
            System.out.println("one");
        }
        else if (pickmeup == 2){
            System.out.println("two");
        }
        else{
            System.out.println("Invalid code");
            break;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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