encontrar el número máximo en el bucle for

public static void evenSumMax(Scanner console){
      System.out.print("How many integers?");
       int a=console.nextInt();
      int sum=0;
       for(int i=1;i<=a;i++){
      System.out.print("Next integer?");
      int v=console.nextInt();
      if(i%2==0){
      sum=sum+v;
      }else{

      }

       }
      System.out.println("Sum of even is "+sum);



      }

and How i can find maximum even number in for loop?

i need to write System.out.print("maximum even is "+????);

preguntado el 28 de mayo de 14 a las 12:05

3 Respuestas

You can try with following code:

public static void evenSumMax(Scanner console){
   System.out.print("How many integers?");
   int a=console.nextInt();
   int maxEven = 0;
   for(int i=1;i<=a;i++){
      System.out.print("Next integer?");
      int v=console.nextInt();
      if(v%2==0){
          if(v > maxEven)
              maxEven = v;
      }

   }
   System.out.println("Maximum even is " + maxEven);
}

contestado el 28 de mayo de 14 a las 13:05

You can use this: (added to your existing code)

public static void evenSumMax(Scanner console) {
    System.out.print("How many integers?");
    int a = console.nextInt();
    int sum = 0;
    int max = Integer.MIN_VALUE; // the smallest value possible in 32-bit integer
    for (int i = 1; i <= a; i++) {
        System.out.print("Next integer?");
        int v = console.nextInt();
        // assuming you're looking for max odd number in input numbers
        if (v % 2 == 0 && v > max) {
            max = v;
        }
        if (i % 2 == 0) {
            sum = sum + v;
        } else {}
    }
    System.out.println("Sum of even is " + sum);
    System.out.print("maximum even is "+ max);
}

contestado el 28 de mayo de 14 a las 13:05

The following will work. After checking the condition that entered value is even add it to the sum variable and compare it to the maxInt. If the entered number is larger than the previously entered number then set maxInt to new value.

 public static void evenSumMax(Scanner console){

  System.out.print("How many integers?");

  int a=console.nextInt();
  int sum=0;
  int maxInt=0;

  for(int i=0;i<a;i++)
  {

  System.out.print("Next integer?");
  int v=console.nextInt();

  if(v%2==0){
  sum=sum+v;

   if(maxInt<v){
       maxInt=v;
               }

           }
   }




  System.out.println("Sum of even is "+sum);
  System.out.println("Maximum even number is "+maxInt);


  }

contestado el 28 de mayo de 14 a las 13:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.