tags:

views:

171

answers:

3

Exercise #3: Write a program that reads 3 integer values and then the user may input the sorting order preference in small or capital letters (i.e., a or A for ascending order, d or D for descending order). Sample input/output: Input 3 number: 7 8 3 Input sort order (a or A for ascending, d or D for descending): d 8 7 3

Exercise #4: Write a program that print the numbers 5, 10, 15, 20 … 100. Also the program should find and print their sum and product.

A: 

If you really don't have a clue where to start with exercise 4 a loop going from 5 to 100 incrementing in fives will get you the numbers that you want to work with. Your running total should start at 0 and the running product should start at 1.

Belinda
+2  A: 

Exercise #3: Write a program that reads 3 integer values

I would start with creating a Scanner that reads the input from System.in:

Scanner s = new Scanner(System.in);

the three integers can be read using the nextInt() method.

int i = s.nextInt();
int j = ...

and then the user may input the sorting order preference in small or capital letters (i.e., a or A for ascending order, d or D for descending order).

Read a character from the user with for instance

char c = s.nextLine().charAt(0);

and compare it using something like

if (c == 'A') {
    // ascending
} else if (c == 'D') {
    // descending
}

I would put the given integers in an array (int[] anArray = { i, j, k };) and then use Arrays.sort.

Reversing the array should be simple enough given that you have exactly three elements.

aioobe
A: 

I'll post the answer to the first one but at-least the second one you must do.

public class Arr {
public static void main(String[] args) {
    Scanner s=new Scanner(System.in);
    System.out.println("Enter 3 number's : ");
    Integer[] arr={s.nextInt(),s.nextInt(),s.nextInt()};
    List<Integer> liArr=Arrays.asList(arr);
    System.out.println("Enter sort choice : ");
    char choice=s.next().toLowerCase().charAt(0);
  switch(choice)
  {
  case 'a':
      Collections.sort(liArr);
      break;

  case 'd':

      Collections.sort(liArr,new Comparator<Integer>(){
          @Override
        public int compare(Integer o1, Integer o2) {
            // TODO Auto-generated method stub
            return o2-o1;
        }
      });
     break;
  default:
      System.out.println("Wrong Choice");
  }
System.out.println(liArr);

}
}
Emil