我正在创建一个程序来计算他的旅行费用。每个段都有一个成本,要求用户输入每个段的成本,然后输入 3 个段 ID (0-6)。将 3 个 ID 的成本相加得出最终价格。
如果用户输入> = 1,我需要从头开始重复程序(见最后的评论),我该怎么做?另外,我可以改进我的程序吗?如何改进?
import java.util.Scanner;
public class AssignmentArrays{
public static void main(String[] args){
Scanner seg0 = new Scanner(System.in);
Scanner seg1 = new Scanner(System.in);
Scanner seg2 = new Scanner(System.in);
Scanner seg3 = new Scanner(System.in);
Scanner seg4 = new Scanner(System.in);
Scanner seg5 = new Scanner(System.in);
int[] data = new int [6];
data[0] = 0;
data[1] = 0;
data[2] = 0;
data[3] = 0;
data[4] = 0;
data[5] = 0;
/* Segment values */
while(data[0] == 0){
System.out.println("Enter cost for segment 0:");
data[0] = seg0.nextInt();
System.out.println("Enter cost for segment 1:");
data[1] = seg1.nextInt();
System.out.println("Enter cost for segment 2::");
data[2] = seg2.nextInt();
System.out.println("Enter cost for segment 3:");
data[3] = seg3.nextInt();
System.out.println("Enter cost for segment 4:");
data[4] = seg4.nextInt();
System.out.println("Enter cost for segment 5:");
data[5] = seg5.nextInt();
/* Path inputs */
Scanner node1 = new Scanner(System.in);
Scanner node2 = new Scanner(System.in);
Scanner node3 = new Scanner(System.in);
int node1value;
int node2value;
int node3value;
int pathCost;
System.out.println("Enter ID of segment 0 of path:");
node1value = node1.nextInt();
System.out.println("Enter ID of segment 1 of path:");
node2value = node2.nextInt();
System.out.println("Enter ID of segment 2 of path:");
node3value = node3.nextInt();
/* Path cost calculation */
pathCost = data[node1value] + data[node2value] + data[node3value];
System.out.println("The cost of the trip is: $" + pathCost);
/* Repeate or end program */
Scanner end = new Scanner(System.in);
int userChoice;
System.out.println("Enter 0 to exit or any other number to evaluate another path:");
userChoice = end.nextInt();
if (userChoice == 0){
System.out.println("The program has ended");
break;
}
else if(userChoice >= 1){
/* REPEATE ALL OF THE ABOVE HERE */
}
}
}
}