Creating an array in JAVA Write a complete program which pro
Creating an array in JAVA.
Write a complete program which prompts the user for an array size. If the input size is -1, you should halt message). If the input size is another negative value, you should re-prompt the program (with a \"Goodbye for the size. Otherwise, create an array of the input size and repeatedly let the user enter an array of integer values. Once the array is entered, prompt the user for an operator (either + or *) If the user enters another symbol, you should re-prompt for the operator. Calculate sum or multiplication of the elements in the array and print the answer to the console. A sample runs are shown below Enter size of array (-1 to exit): -2 Enter size of array (-1 to exit 0 Enter size of array (-1 to exit): 4 Enter value in index 0:2 Enter value in index 1:1 Enter value in index 2:2 Enter value in index 3:3 Enter Operator: g Enter Operator 9 Enter Operator + rightarrow 8 Enter size of array (-1 to exit): 3 Enter value in index 0:2 Enter value in index 1:2 Enter value in index 2:4 Enter Operator: * rightarrow 16 Enter size of array (-1 to exit): -1 Goodbye!Solution
//Test.java
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int arraySize;
while(true)
{
while(true)
{
System.out.print(\"Enter size of array (-1 to exit): \");
arraySize = sc.nextInt();
if(arraySize == -1)
{
System.out.println(\"GoodBye!\ \");
System.exit(1);
}
else if(arraySize > 0)
break;
}
int[] array = new int[arraySize];
for (int i = 0; i < arraySize; i++ )
{
System.out.print(\"Enter value in index \" + (i+1) + \": \");
array[i] = sc.nextInt();
}
char operator;
while(true)
{
System.out.print(\"Enter operator: \");
operator = sc.next().charAt(0);
if(operator == \'+\' || operator == \'*\')
break;
}
int result = 0;
if(operator == \'*\')
{
result = 1;
for (int i = 0; i < arraySize ;i++ )
{
result = result*array[i];
}
}
else
{
for (int i = 0; i < arraySize ;i++ )
{
result = result + array[i];
}
}
System.out.println(\"Result: \" + result + \"\ \ \");
}
}
}
/*
Output:
Enter size of array (-1 to exit): -2
Enter size of array (-1 to exit): 0
Enter size of array (-1 to exit): 4
Enter value in index 1: 2
Enter value in index 2: 1
Enter value in index 3: 2
Enter value in index 4: 3
Enter operator: g
Enter operator: 9
Enter operator: +
Result: 8
Enter size of array (-1 to exit): 3
Enter value in index 1: 2
Enter value in index 2: 2
Enter value in index 3: 4
Enter operator: *
Result: 16
Enter size of array (-1 to exit): -1
GoodBye!
*/

