我编写了这段代码来隐藏和取消隐藏任何文件或文件夹,但是当用户给出错误输入时如何显示错误,我尝试使用 else if 但使用错误的逻辑代码,我想在用户给出错误输入时显示错误选择隐藏或取消隐藏,如果用户提供了错误的隐藏或取消隐藏文件路径。
import java.io.*;
class k
{
public static void main(String args[])
{
String a,h;
boolean q=true;
while(q==true){
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nunhide/hide/exit (u/h/e): ");
h=br.readLine();
if("hide".equalsIgnoreCase(h)){
System.out.print("\nwhat you want 2 hide: ");
a=br.readLine();
if(a.equals(a)){
Runtime r=Runtime.getRuntime();
Process p=r.exec("cmd.exe /c attrib +h "+a);
System.out.print("HIDDEN SUCCESSFULLY");
}
//else if(!a.equals(a)){System.out.print("error");}
}else if("unhide".equalsIgnoreCase(h)){
System.out.print("what u want to unhide: ");
a=br.readLine();
if(a.equals(a)){
Runtime r=Runtime.getRuntime();
Process p=r.exec("cmd.exe /c attrib -h "+a);
}
System.out.print("UNHIDDEN SUCCESSFULLY");
}
else if("exit".equalsIgnoreCase(h)){
System.exit(1);
}
}catch(Exception e){
System.out.println(e);
}
}
}
}
最佳答案
首先:您让用户从 3 个字母中进行选择(h
、u
、e
),
所以你需要确保用户输入“h”而不是“hide”,所以你的检查需要是
if ("h".equalsIgnoreCase(h)) //h not hide {
.....
}
第二:很容易检查您输入的路径是否存在,因此如果错误您可以知道,如下所示:
if (new File(a).exists()) {
Process p = r.exec("cmd.exe /c attrib +h " + a);
System.out.print("HIDDEN SUCCESSFULLY " + p);
} else {
System.out.println("wrong input");
}
关于java - 输入错误时如何显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18853269/