gpt4 book ai didi

java - 从不同的函数打印 ArrayList

转载 作者:行者123 更新时间:2023-12-02 05:37:56 25 4
gpt4 key购买 nike

此代码的目的是接收用户输入并将其显示为单个记录。我编写了一个菜单,后跟 2 个方法(设置和显示),使用 Scanner 类来填充 arrayList,但无法使用显示方法打印它们。

这是代码,请告诉我如何解决这个问题。

import java.io.*;
import java.util.*;

public class Records2 {

static ArrayList information = new ArrayList();

public static void main(String[] args) {
int choice;
do {
System.out.println("1.Add \n 2.Delete \n 3.Update \n 4.Show \n Exit");

//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//int choice;
System.out.println("Enter your Choice : ");
Scanner sc = new Scanner(System.in);
choice = sc.nextInt();

switch (choice) {

case 1: System.out.println("Getting ready to Add a Record ");
set();
break;

case 2: System.out.println("Getting ready to Delete a Record ");
//delete();
break;

case 3: System.out.println("Getting ready to Update a Record ");
//update();
break;

case 4: System.out.println("Here is your record ");
display();
break;

case 5: System.out.println("Out we go.");
System.exit(0);
//exit();
break;

default: System.out.println("Try again");
break;
}

} while ( choice > 5 || choice < 1 );

}

public static void set() {

System.out.println("Please enter the ID, Name and Address of the person \n");

Scanner readId = new Scanner(System.in);
int ID = readId.nextInt();

Scanner readName = new Scanner(System.in);
String name = readName.nextLine();

Scanner readAddress = new Scanner(System.in);
String address = readAddress.nextLine();

//ArrayList information = new ArrayList();
information.add(ID);
information.add(name);
information.add(address);
}

public static void display() {

System.out.println("here is your list" + information);
//how to differentiate from one set to another?
}

}

最佳答案

这是因为你的 while 循环!

while ( choice > 5 || choice < 1 );

选择 set() 的 choice = 1 后,代码将退出循环

因此永远不会调用显示。

使用:while ( choice > 0 && choice < 6)

关于java - 从不同的函数打印 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24802205/

25 4 0