Exercise
Array Of Struct And Menu
Objetive
Expand the previous exercise (array of points), so that it displays a menu, in which the user can choose to:
- Add data for one point
- Display all the entered points
- Calculate (and display) the average values for x and y
- Exit the program
Example Code
import java.util.*;
public class Main
{
private final static class points
{
public byte x;
public byte y;
public points clone()
{
points varCopy = new points();
varCopy.x = this.x;
varCopy.y = this.y;
return varCopy;
}
}
public static void main(String[] args)
{
points[] p = new points[1000];
boolean Finish = false;
int countArray = 0;
int TotalX = 0;
int TotalY = 0;
do
{
System.out.println("1.Add data for one point");
System.out.println("2.Display all the entered points");
System.out.println("3.Calculate (and display) the average values for x and y");
System.out.println("0.Exit the program");
System.out.print("Enter a number: ");
byte respuesta = Byte.parseByte(new Scanner(System.in).nextLine());
switch (respuesta)
{
case 1:
System.out.println();
System.out.print("Enter a number for point x: ");
p[countArray].x = Byte.parseByte(new Scanner(System.in).nextLine());
TotalX += p[countArray].x;
System.out.println();
System.out.print("Enter a number for point y: ");
p[countArray].y = Byte.parseByte(new Scanner(System.in).nextLine());
TotalY += p[countArray].y;
System.out.println();
countArray++;
break;
case 2:
if (countArray > 0)
{
for (int i = 0; i < countArray; i++)
{
System.out.printf("Valor x%1$s: %2$s" + "\r\n", i + 1, p[i].x);
System.out.printf("Valor y%1$s: %2$s" + "\r\n", i + 1, p[i].y);
}
}
else
{
System.out.println("No hay datos");
}
break;
case 3:
if (countArray > 0)
{
System.out.printf("Average x: %1$s" + "\r\n", TotalX / countArray);
System.out.printf("Average y: %1$s" + "\r\n", TotalY / countArray);
}
else
{
System.out.println("No hay datos");
}
break;
case 0:
Finish = true;
break;
default:
break;
}
} while (!Finish);
}
}