gpt4 book ai didi

java - 尝试响应命令行用户输入时出现问题

转载 作者:行者123 更新时间:2023-11-30 07:49:29 25 4
gpt4 key购买 nike

我已经创建了这个类和链表类,它们位于同一个文件夹中。除了运行程序类不会输出任何内容(即使我在命令提示符中输入 p 时)之外,输入似乎工作正常。即使我将方法封装在 System.out.print 中,也没有任何反应。

运行类

public class runner{

static String s;
public static void main(String[] args) throws java.io.IOException{
linkedlist link= new linkedlist();
System.out.println("Type a command\n");
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
try{
s=in.readLine();
char first=s.charAt(0);
while(in.readLine()!=null){
s=in.readLine();
int space= s.indexOf(" ");
if(first=='i'){
String w=s.substring(space);
link.insert(w);
}
if(first=='d'){
String w=s.substring(space);
link.delete(w);
}
if(first=='f'){
String w=s.substring(space);
link.find(w);
link.find(w);
}
if(first== 'p'){
link.printlist();
}
}
}catch(Exception e) {
System.out.println("Ack!: " + e);
}finally{
in.close();
}
}

}

链表类

import java.io.*;

public class linkedlist{
node head;
public linkedlist(){
head=null;
}

public void insert(String s){
head= new node(s,head);
}

public void printlist(){
node i= head;
while(i.getData(i)!=null){
System.out.print(i.getData(i));
i=i.getNext();
}
}

public String find(String s){
String comp=head.getData(head);
node ref=head.getNext();
String check=ref.getData(ref);
String temp=check;
while(check != "null"){
if(s.equals(check)){
head=ref;
ref=head.getNext();
check=ref.getData(ref);
}
else{
temp=check;
}
}
return temp;
}

public String delete(String s){
String comp=head.getData(head);
node ref=head.getNext();
String check= ref.getData(ref);
node ref2= ref.getNext();
String post=ref2.getData(ref2);
String temp=check;
while(check != "null"){
if(s.equals(check)){
ref=ref2;
}
else{
comp=check;
ref=head.getNext();
check=ref.getData(ref);
ref2= ref.getNext();
post=ref2.getData(ref2);
}
}
return temp;
}
}

最佳答案

我猜发生这种情况是因为您在这里吞下了几行输入:

try{
s=in.readLine(); //you consume one line here
char first=s.charAt(0);
while(in.readLine()!=null){ //you consume another here
s=in.readLine(); //and another one..

将其替换为:

 while ((s = in.readLine()) != null) { // while loop begins here
char first=s.charAt(0);
[...]
} // end while

关于java - 尝试响应命令行用户输入时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33465768/

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