核心JAVA:根据用户输入循环整个程序

时间:2018-08-14 07:03:44

标签: java loops

我刚刚开始了Java入门课程,所以请原谅我拙劣的编码。我一直在尝试做循环循环-循环整个程序(根据用户选择),该程序需要n个整数输入并确定最大,最小。

import java.util.Scanner;

public class Max_Min_Game {

    private int min;
    private  int max;
    int counter=1;
    private int noofnumbers;
    private int value;
    Scanner input= new Scanner(System.in);

    public void getInput() {

        System.out.print("How many Numbers # ");
        noofnumbers = input.nextInt();

        System.out.print("Enter #1 : ");
        value = input.nextInt();

    }

    public void getCalc() {

        min=Integer.MAX_VALUE;
        max=Integer.MIN_VALUE;

        do {
            System.out.print("Enter #"+(counter+1)+" : ");
            value = input.nextInt();

            if(value<min)
            {
                 min=value;
            }
            if(value>max)
            {
                max=value;
            }
            counter++;
        } while (counter < noofnumbers);
    }
    public void display() {
        System.out.println("\nMax="+max);
        System.out.println("Min="+min);
    }
}

主类:

import java.util.Scanner;

public class Max_Min_Game_Main {

    public static void main(String[] args) {

        Max_Min_Game r = new Max_Min_Game();
        String playAgain = "";
        Scanner input = new Scanner(System.in);

        do {
            r.getInput();
            r.getCalc();
            r.display();

            System.out.println("\nWould u like to Restart?");
            System.out.print("Press Y to Restart, any other key to Exit");

            playAgain = input.nextLine();

        } while (playAgain.equalsIgnoreCase("Y") );

        System.out.println("Thanx for PLaying");
    }
}

但是,它执行的是第一个循环,但是在下一次迭代时会遇到麻烦-

How many Numbers # 5
Enter #1 : 6
Enter #2 : 3
Enter #3 : 9
Enter #4 : 8
Enter #5 : 5

  Max=9
  Min=3

Would u like to Restart?
Press Y to Restart, any other key to Exit y
How many Numbers # 3
Enter #1 : 9
Enter #6 : 6

Max=6
Min=6

任何帮助/解释将不胜感激。

谢谢。

1 个答案:

答案 0 :(得分:0)

您不会在第二次迭代中再次重置计数器变量。修改后的代码如下:

import java.util.Scanner;
public class Max_Min_Game {

private int min;
private  int max;
int counter=1;
private int noofnumbers;
private int value;


Scanner input= new Scanner(System.in);


public void getInput() {

    System.out.print("How many Numbers # ");
    noofnumbers = input.nextInt();

    System.out.print("Enter #1 : ");
    value = input.nextInt();
    min=value;
    max=value;
    counter =1;

}

public void getCalc() {

    //min=Integer.MAX_VALUE;
    //max=Integer.MIN_VALUE;


do  {
        System.out.print("Enter #"+(counter+1)+" : ");
        value = input.nextInt();

        if(value<min)
        {
            min=value;
        }
        if(value>max)
        {
            max=value;
        }
        counter++;
    }while (counter < noofnumbers);

}

public void display() {
    System.out.println("\nMax="+max);
    System.out.println("Min="+min);
}

}