我正在创建一个计算旅行费用的程序。每个段都有成本,要求用户输入每个段的成本,然后输入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 */
}
}
}
}
答案 0 :(得分:1)
我可能会让这个类更加面向对象。但是,您可以使用以下方法分解代码来简化您的工作:
import java.util.Scanner;
public class AssignmentArrays{
static int[] data = new int [6];
public static void getSegmentIDs() {
...
}
pubilc static int getUserMenuChoice() {
...
}
public static void main(String[] args){
int exit = false;
while(!exit) {
getSegmentIDs();
choice = getUserMenuChoice();
if (choice == 0) exit = true;
}
}
}
答案 1 :(得分:0)
我会通过这样做将整个事情放入do while语句中:
String answer ="";
do {
Scanner seg0 = new Scanner(System.in);
Scanner seg1 = new Scanner(System.in);
Scanner seg2 = new Scanner(System.in);
YOUR CODE CONTINOUS
/* Repeate or end program */
System.out.println("would you like to redo? (Y/N)");
answer = end.next();
} while(answer.toLowerCase().contains("y"));