java - 使用 ArrayList 显示另一个类的值
问题描述
我正在尝试制作一个待办事项列表,要求您一项一项地输入您的任务,然后按顺序显示它们(如 1.task1、2.task 2、3.task 3 等)。但是当它显示任务时,它一次返回为“0.null”,而不是列出任何输入的任务。这是我正在使用的脚本:
一级
package todolist;
import java.util.ArrayList;
public class ToDoList1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<ToDoList2> list = new ArrayList<ToDoList2>();
System.out.println("Time to make a digital to-do list!");
ToDoList2 n = new ToDoList2();
list.add(n);
System.out.println(ToDoList2.name + "'s to-do list");
System.out.println(ToDoList2.i + ". " + ToDoList2.l);
for(ToDoList2 enhanced : list)
{
System.out.println(ToDoList2.i + ". " + ToDoList2.m);
}
}
}
二等
package todolist;
import java.util.Scanner;
public class ToDoList2 {
public static String name;
public static int i;
public static String l;
public static String m;
{
Scanner s = new Scanner(System.in);
System.out.println("First type your name to identify your list in case you lose it");
name = s.nextLine();
System.out.println("Make sure to type \"end\" when you are finished");
System.out.println("Type in the first item on your to-do list");
String l = s.nextLine();
}
public ToDoList2()
{
Scanner s = new Scanner(System.in);
for(int i = 1; i == i; i++)
{
System.out.println("Type in the next item for your to-do list");
String m = s.nextLine();
if("end".equals(m))
{
break;
}
}
}
}
解决方案
您的代码不正确。ToDoList2 从标准输入扫描项目列表但不存储它。你应该做如下
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class TodoList {
public static String name;
List<String> tasks;
public TodoList(String name) {
this.name = name;
this.tasks = new ArrayList<>();
}
public void addTask(String task) {
this.tasks.add(task);
}
public String toString() {
int i = 1;
StringBuilder stringBuilder = new StringBuilder();
for (String task : tasks) {
stringBuilder.append(i + ". " + task);
stringBuilder.append("\n");
i++;
}
return stringBuilder.toString();
}
}
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("First type your name to identify your list in case you lose it");
String name = s.nextLine();
System.out.println("Make sure to type \"end\" when you are finished");
System.out.println("Type in the first item on your to-do list");
TodoList todoList = new TodoList(name);
String task = null;
while (!(task = s.nextLine()).equals("end")) {
todoList.addTask(task);
System.out.println("Type in the next item for your to-do list");
}
System.out.println(todoList);
}
}
推荐阅读
- android - onMapReady 不会显示地图
- javascript - 获取子数组的排列而不改变子数组的顺序
- python-3.x - 在python中将一个类的变量列表发送到另一个类
- excel - VBA - 在循环中设置计数器以复制/粘贴到主表中的下一列
- c# - C# CancellationToken 保存在本地存储中
- r - 在 Stata 中创建临时数据集
- javascript - Flot rotateTicks xaxis 日期显示额外的一天
- parsing - 如何使用带有'sh'的sed获取字符串中的第一个数字
- ios - 获取一周的日期
- html - 字体真棒图标位于文本字段后面