2

クラスのラボの一部で問題が発生しました。ほとんどの場合は簡単ですが、何らかの理由で、whileステートメントが希望どおりに機能していません。無効な入力を返し、ユーザーに賃貸人を促すことになっています。ただし、すべての入力が無効であると見なされます。(コードで見やすいはずです)これを修正するにはどうすればよいですか?または、私の本でそれを見つけることができないので、私はその情報を見つけることができましたか?(2番目のwhileループ、最初のループは機能します)

import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class lab8
{
    public static void main (String[] args)
    {
        int choice;
        String item;
        double costper;
        ArrayList <String> Items = new ArrayList <String> (); 
        Items.add ("computer");
        Items.add ("Monitor");
        Items.add ("Color Printer");
        Items.add ("Color Scanner");
        Items.add ("DVD/CDROM");
        Items.add ("To Quit");

        ArrayList <Integer> Num = new ArrayList <Integer> ();
        Num.add (0);
        Num.add (1);
        Num.add (2);
        Num.add (3);
        Num.add (4);
        Num.add (5);

        System.out.println ("\t\tMy Super Computer Store\n");
        int index=0;
        int endex= 0;
        while (index < Items.size() && endex < Num.size())
        {
            System.out.println ("\t" +Num.get(index)+"\t"+Items.get (endex));
            index++;
            endex++;
        }
        Scanner scan = new Scanner (System.in);
        System.out.print ("\n\t\t\tEnter the item to purchase: ");
        choice = scan.nextInt ();
        {
            if (choice==5)
            {
                JOptionPane.showMessageDialog (null, "Thanks for considering My Super Computer Store");
                System.exit (0);
            }
        }
        {
            if (choice==0 || choice==1 || choice==2 || choice==3 || choice==4)
            {
                item = Items.get (choice);
            }
        }
        while (choice!=0 || choice!=1 || choice!=2 || choice!=3 || choice!=4 || choice!=5)
        {
            System.out.println ("Invalid Input, Please enter a integer between 0 and 5. ");
            System.out.print ("\n\t\t\tEnter the item to purchase: ");
            choice = scan.nextInt ();    
        }
        System.out.print ("\n\n\t\t\tEnter the quantity to purchase: ");
        int Qty = scan.nextInt ();
    }
}
4

2 に答える 2

6

あなたの論理は間違っています。

あなたが欲しい:

!(choice == 0 || choice == 1 || choice == 2 || choice == 3 || choice == 4)

これはあなたが書いたものと同じではありません。

ド・モルガンの法則はあなたの友達です:)

ド・モルガンの法則によることに注意してください

!(choice == 0 || choice == 1 || choice == 2 || choice == 3 || choice == 4)

(choice != 0 && choice != 1 && choice !=2 && choice !=3 && choice != 4)

そしてもちろん、有効な選択に使用している整数を使用しているため、次の条件を使用することもできます。

(choice < 0 || choice > 4)
于 2012-04-11T02:06:43.903 に答える
2

You've used || in your loop conditions. Logically, you're saying:

"If the choice isn't 0, or isn't 1, or isn't 2, etc.", meaning that a value of '1' fulfills the conditions because it's not 0, and it's not 2. Replace your while loop with:

while (choice!=0 && choice!=1 && choice!=2 && choice!=3 && choice!=4)

And you'll be ok.

于 2012-04-11T02:08:51.400 に答える