1

I need to get the maximum of three ints, but my code will not give output when the second number is less than zero.

package main; import java.util.Scanner; public class Max { public static void main(String[] args) { Scanner in=new Scanner(System.in); int a=in.nextInt(); int b=in.nextInt(); int c=in.nextInt(); int max; if(a>b){ if(a>c)max =a; else max =c; } else{ if(b>c)max=b; else max=c; System.out.println(max); } } } 

It passed the test of other situations. Could you tell me why it happened?

3
  • 1
    Try storing the values into a List. Then by using Collections.max() to get the largest value. Commented Mar 2, 2017 at 2:45
  • You need to move your System.out.println so its outside of the else. Commented Mar 2, 2017 at 2:45
  • Thanks all of you...I know what is my mistake. Commented Mar 2, 2017 at 2:49

5 Answers 5

3

Your print statement is inside of the else block, so it will only get executed if it goes to the else branch. Move it to outside of the else block.

... else { if(b>c) max=b; else max=c; } System.out.println(max); 
Sign up to request clarification or add additional context in comments.

Comments

2

Its because of where you have your println statement. Its in the second conditional, you want it to be outside the if statements.

public class Max { public static void main(String[] args) { Scanner in=new Scanner(System.in); int a=in.nextInt(); int b=in.nextInt(); int c=in.nextInt(); int max; if(a>b){ if(a>c)max =a; else max =c; } else{ if(b>c)max=b; else max=c; } } System.out.println(max); } 

Comments

2

I suggest writing separate method

public int max(int a, int b) { return Math.max(a, b); } 

and call it like

max(a, max(b, c)); 

The code is lot cleaner this way

Comments

1

Use Collections.max() on a List which stores your int values.

package main; import java.util.Scanner; public class Max { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); Scanner in = new Scanner(System.in); int a= in.nextInt(); list.add(a); int b= in.nextInt(); list.add(b); int c= in.nextInt(); list.add(c); System.out.println("Largest: " + Collections.max(list)); } } 

Comments

-1

Input the numbers into a array instead of three separate variables. then you can use this method :

public int getLargest(int[] nums){ int largest = Integer.MIN_VALUE; if(nums.length == 0) return -1; for(int i : nums){ if(i > largest) largest = i; } return largest; } 

3 Comments

This returns Integer.MIN_VALUE for an array of length 0.
Fixed, i sort of assumed most people wouldn't be sending blank arrays
I would have assumed an Exception would be raised instead of returning a number that doesn't exist in the array. I won't lead you on a wild goose chase though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.