gpt4 book ai didi

java处理命令行输入

转载 作者:行者123 更新时间:2023-12-01 14:27:57 24 4
gpt4 key购买 nike

我试图实现一个 java 程序来处理来自命令行的用户输入。问题是在 Algorithms 一书中给出的(sedgewick )

1.1.21 Write a program that reads in lines from standard input with each line contain- ing a name and two integers and then uses printf() to print a table with a column of the names, the integers, and the result of dividing the first by the second, accurate to three decimal places. You could use a program like this to tabulate batting averages for baseball players or grades for students.

我尝试按如下方式实现这一点..但我坚持存储用户输入,以便可以使用 printf() 打印它..我认为 Scanner 适合获取用户输入..我似乎仍然无法存储输入以供以后使用。

Stack 类来自 sedgewick 的书。

知道如何解决这个问题吗?

 Scanner input = new Scanner(System.in);        
Stack st = new Stack();
while(input.hasNext()){
String tkn = input.next();
st.push(tkn);
if (st.size()==3){
int y = Integer.parseInt((String)st.pop());
int x = Integer.parseInt((String)st.pop());
String name = (String)st.pop();
System.out.println("name="+name+",x="+x+",y="+y);

}
}

最佳答案

通过使用st.pop()它将删除并返回堆栈的最后一项。如果您不希望它被删除,您可以使用一个有序的Collection,例如 ArrayList并通过 list.get 访问该项目或使用Iterator .

另一个建议是创建一个对象来存储名称和 y、x 属性:

class MyObject {
private String name;
private int x;
private int y;

//... setter and getter methods for the properties
}

对代码的建议:它将输入推送到Stack中,然后弹出项目以创建MyObject并添加到列表 :

ArrayList listObjects = new ArrayList();
Scanner input = new Scanner(System.in);
Stack st = new Stack();
while(input.hasNext()){
String tkn = input.next();
st.push(tkn);
if (st.size()==3){
int y = Integer.parseInt((String)st.pop());
int x = Integer.parseInt((String)st.pop());
String name = (String)st.pop();
//create and add the object to the list for further use
listObjects.add(new MyObject(name, x, y));
System.out.println("name="+name+",x="+x+",y="+y);

}
}

关于java处理命令行输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17036259/

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