在java中循环使用奇数和偶数

时间:2015-07-30 14:06:40

标签: java loops

如何在用户输入负数之前反复询问用户输入输入。如果用户输入负数或0,程序将结束?

private static String RUN_ONCE;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        initViews();

        passedFragment = this.getIntent().getExtras().getString("fragmentClass");

            switch (passedFragment){
                case "com.serverus.oom.fragments.FragmentAgency":
                    fragmentClass = FragmentAgency.class;

                    menuItemReserve = mMenu.findItem(R.id.agency_menu_item);
                    break;
                case "com.serverus.oom.fragments.FragmentServices2":
                    fragmentClass = FragmentServices2.class;
                    menuItemReserve = mMenu.findItem(R.id.services_menu_item);
                    break;
                case "com.serverus.oom.fragments.FragmentContactUs":
                    fragmentClass = FragmentContactUs.class;
                    menuItemReserve = mMenu.findItem(R.id.contact_menu_item);
                    break;
                default:
                    fragmentClass = FragmentAgency.class;
                    break;
            }

        if(savedInstanceState == null){
            fragmentReplace(fragmentClass);
        }else{
            getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG);
        }

    }


@Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(RUN_ONCE, true);
    }

2 个答案:

答案 0 :(得分:4)

你必须改变while子句:

while (x>0)

答案 1 :(得分:0)

使用<>

public static void main(String[] arguments) {
    Scanner s = new Scanner(System.in);
    int x = 0;

    do {

        System.out.println("Enter an integer to check if it is odd or even ");

        try {
            x = Integer.parseInt(s.nextLine());
            if (x > 0) {
                System.out.println("You entered an even number.");
            } else if (x == 0) {
                System.out.println("You entered 0, thats not negativ or positiv.");
            } else {
                System.out.println("You entered an odd number.");
            }

        } catch (Exception e) {
            //e.printStackTrace();
            System.out.println("U call this an Integer? :P");
        }

    } while (x > 0);
    return;
}

上次编辑:检查输入是否为数字,如果要检查错误,可以从catch块中删除//