In: Computer Science
Java programming
Create a application with a method void (after main()
) that creates an array and asks for the user fill it with float
numbers.
This array have infinite elements until the user decide that it is
enough and input a command to stop.
Display this array's elements data in another method
void.
Thanks for your help!
The below code will do your requirements. Note that, when the
code ask you for Do you want to enter array element? Enter
1(if yes) Enter 0(if no): you must respond with an integer
else the program will raise an exception. If you enter a integer
not(0/1) then an error message is displayed and ask you to eneter
correct option. See the code below for better
understanding:
import java.util.Scanner;
public class MyClass {
//function to display array
public static void disparray(float[] a, int n){
int i; //for loop through array elements
System.out.println("Array elements are: "); //printing message that array elements are printing below
//for loop to displaying array elements
for(i=0;i<n;i++)
System.out.println(a[i]); //displaying each array elements
}
//function to input array
public static void inputarray(){
//creating scanner object
Scanner sc = new Scanner(System.in);
float[] a = new float[100]; //initializing a floating array
int f = 1; //variable to store flag
int i=0; //variable to loop arrray elements
//loop for getting array elements
do{
//asking user whether to eneter element or not user must respond with a integer(entry message)
System.out.println("Do you want to enter array element? Enter 1(if yes) Enter 0(if no): ");
//getting user response
f=sc.nextInt();
//cheking user response
if(f==1){ //if user response is 1
System.out.println("Enter array element: "); //message to enter array element
a[i] = sc.nextFloat(); //getting array element
i++; //incrementing array index
}
else if(f==0) //if user response is 0
System.out.println("Array entry stopped!"); //showing message for stopping entry
else{ //if user response is a integer but neither 0 or 1
System.out.println("ERROR: Enter the correct option"); //showing to enter the correct option
f=1; //setting flag to 1 (for asking the entry message)
}
}while(f==1); //continue loop when user response is 1
//calling function to print array with the entered index
disparray(a, i);
}
public static void main(String args[]) {
//calling the method to insert array
inputarray();
}
}
Sample OUTPUT: