我现在正在做的一个java任务有问题。我试图回答问题3和问题4,这是基于下面的代码。
运行程序后,输出窗口应该如下所示:
1: Enter a line
Some input
2: Enter another line
More input
3: Enter the last line
The end
The end,More input,Some inputimport java.util.Scanner;
public class Practical1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String msg1, msg2, msg3;
System.out.println("Enter a line");
msg1 = in.nextLine();
System.out.println("Enter another line");
msg2 = in.nextLine();
System.out.println("Enter the last line");
msg3 = in.nextLine();
System.out.println(msg3 + "," + msg2 + "," + msg1) ; }}以上代码分析了问题1和问题2。
对于问题3,它要求我像调用Line那样创建一个新的java类,然后向类中添加适当的实例变量(字段)和构造函数,这样就可以存储一行文本(字符串,称为文本)和序列号( int,称为seqNum)。这些实例变量应该是其他类的“只读”变量。也就是说,应该声明它们为返回值而提供的“私有”和"getter“方法。这就是我在下面的代码中所做的:
public class Line {
public String getText() {
return text;
}
private String text;
public int getSeqNum() {
return seqNum;
}
private int seqNum;}
然后,它请求修改类Practical1的主要方法,以便将每一行文本及其序列号存储在一个line中,而不是一个String对象中。修改变量类型(msg1等)如有需要。注意,要打印出一行,需要调用getter方法。你的程序的输出应该和以前一样。
最后,更多的输入,一些输入
最后,它要求您现在更改程序,以便用行打印序列号。最后一项产出应是:
3: The end,2: More input,1: Some input我该怎么回答这个问题?
对于最后一个问题,它要求我修改程序,以便它使用循环重复执行:- seqNum和提示短语:“输入一行”--读取输入行--将输入行存储在行数组或行的ArrayList的下一个位置。
一旦用户输入停止作为输入,循环应该终止,另一个循环应该以相反的顺序打印每一行。例如(您应该输入的输入是粗体):
1: Enter a line
Some input
2: Enter a line
More input
3: Enter a line
The end
4: Enter a line
STOP
3: The end
2: More input
1: Some input我该怎么回答这个问题?
发布于 2020-03-15 10:34:41
你可以按照下面的方法来解决这个问题。
第一线类
public class Line
{
private int seq_num;
private String text;
Line(int seq_num, String text)
{
this.seq_num = seq_num;
this.text = text;
}
public String getText()
{
return this.text;
}
public int getSeq()
{
return this.seq_num;
}
}演示类,用于在提供停止文本之前接受无限输入
class Demo
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Line> list = new ArrayList<>();
int counter =0;
while(true)
{
String scanned_line = sc.nextLine();
if(scanned_line.equals("STOP"))
break;
list.add(new Line(counter,scanned_line));
counter++;
}
//sort the list as per the seq num in reverse order
list.sort(Comparator.comparingInt(Line::getSeq).reversed()); // java 8 comparator
list.forEach(e-> System.out.println(e.getSeq()+" "+e.getText()));//java 8 forEach
}
}还有,
需要指出的是,
while(scanner.hasNextLine())代替while(true)。因此,它将扫描直到它有下一行输入provided.forEach可以用传统的for循环.代替。
https://stackoverflow.com/questions/60691767
复制相似问题