gpt4 book ai didi

java - 用户输入后重复执行的代码

转载 作者:行者123 更新时间:2023-12-01 15:02:42 26 4
gpt4 key购买 nike

我正在创建一个程序来计算旅行费用。每个段都有一个成本,用户需要输入每个段的成本,然后输入 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 */
}
}

}

}

最佳答案

我可能会让这个类更加面向对象。但是,您可以通过使用方法分解代码来简化您所拥有的内容:

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;
}

}
}

关于java - 用户输入后重复执行的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13412697/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com