简体   繁体   中英

Java Printing Prob

This is the supposed printing result (available for all integers):

Please input 5 integers: 54 98 23 14 37
54
98 <-- largest value
23
14 <-- smallest value
37

This is my unfinished program:

public static void main(String[] args) {

    Scanner in = new Scanner (System.in);
    System.out.print("Please input 5 integers: ");
    int [] x = new int [5];
    for (int i=0; i < x.length; i++) {
        x[i] = in.nextInt();
    }

    System.out.println(x[i]);

    int max = x[0];
    int min = x[0];

    for (int i=0; i < x.length; i++) {
        if (x[i] > max) {
            max = x[i];
        }
    }

    for (int i=1; i < x.length; i++) {
        if (x[i] < min) {
            min = x[i];
        }
    }

}       

I've finished the core part, which is the functioning part. The problem I'm facing is how to apply these functioning results into the last step: printing.

Can anybody help me solve the problem? Thanks :))

Pseudocode:

for each number
    print number
    if number is max
        print "<-- largest value"
    if number is min
        print "<-- smallest value"
for (int i=0; i < x.length; i++) {
    if (x[i] == min) {
       System.out.println(min + "<-- smallest value");
    }else if(x[i] == max){
       System.out.println(max + "<-- largest value");
    }else{
       System.out.println(x[i]);
 }
}

I would check for max and min in your input loop and I get your output exactly as requested with -

Scanner in = new Scanner(System.in);
System.out.print("Please input 5 integers: ");
int[] x = new int[5];
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 0; i < x.length; i++) {
  if (!in.hasNextInt()) { // <-- do we have an int?
    if (!in.hasNext()) {  // <-- do we have any input?
      System.err.println("No more input.");
      System.exit(1);
    }
    System.err.println(in.next() + " is not a number");
    i--; // <-- reget this "number".
    continue;
  }
  int val = in.nextInt();
  if (val < min) { // <-- is it smaller then min?
    min = val;
  }
  if (val > max) { // <-- is it larger then max?
    max = val;
  }
  x[i] = val;
}
for (int i : x) {
  String str = "";
  if (i == min && i == max) {
    str = " <-- largest and smallest value"; // <-- just in case.
  } else if (i == min) {
    str = " <-- smallest value";
  } else if (i == max) {
    str = " <-- largest value";
  }
  System.out.printf("%d%s%n", i, str);
}

Output

Please input 5 integers: 54 98 23 14 37
54
98 <-- largest value
23
14 <-- smallest value
37

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