import java.util.Scanner; public class Lab5Q1_loop { static int DEFAULT_VALUES=5; /** * Read in numbers from the user, and then print them with their sum * * @param args */ public static void main(String[] args) { int num_values=DEFAULT_VALUES; // check if value was passed in on command line if(args.length>0){ try{ num_values=Integer.parseInt(args[0]); }catch(NumberFormatException ex){} // ignore if the command line value is not an integer } Scanner reader=new Scanner(System.in); int[] values=new int[num_values]; // array for storing values int sum=0; // prompt the user for each number for(int i=0; i<num_values; i++){ System.out.print("Number "+ (i+1)+": "); values[i]=reader.nextInt(); // store value for later if (i % 2 == 1) sum-=values[i]; // decrease our sum of values else sum+=values[i]; // increase our sum of values } /* print each number followed by an addition sign * count one less than our number of values, so the correct number of * addition signs are added */ for(int i=0; i<num_values-1; i++){ if (i % 2 == 1) System.out.print(values[i]+" + "); else System.out.print(values[i]+" - "); } // print out last number, and the sum System.out.print(values[num_values-1]+" = "+sum); } }