帮我完善代码import java.util.InputMismatchException; import java.util.Scanner; public class CLI { private static Scanner input = new Scanner(System.in); private static String readLine(String str1) { System.out.print("Type some text:"); String str = input.nextLine(); return str; } private static int readPosInt(String str2) { while(true) { System.out.print("Type some integer:"); int i; while(true) { try { i= input.nextInt(); System.out.println("i:"+i); break; }catch(InputMismatchException e){ System.out.println("You must type an integer!"); input.nextLine(); } } if(i>=0) { return i; }else { System.out.println("Positive intefers only!"); } } } public static void main(String[] args) { String str1 = readLine("Type some text: "); System.out.println("Text read is: " + str1); int i = readPosInt("Type an integer: "); System.out.println("Integer read is: " + i); String str2 = readLine("Type some text again: "); System.out
时间: 2023-12-06 22:41:55 浏览: 96
java代码-实训4-3 import java.util.Scanner
.println("Text read is: " + str2); input.close(); } }
你的代码已经很好了,但我稍微修改了一下以更好地处理异常情况并提供更好的用户体验。
import java.util.InputMismatchException;
import java.util.Scanner;
public class CLI {
private static Scanner input = new Scanner(System.in);
private static String readLine(String prompt) {
System.out.print(prompt);
String str = input.nextLine();
return str;
}
private static int readPosInt(String prompt) {
while (true) {
System.out.print(prompt);
try {
int i = input.nextInt();
input.nextLine(); // consume remaining newline character
if (i >= 0) {
return i;
} else {
System.out.println("Positive integers only!");
}
} catch (InputMismatchException e) {
System.out.println("You must type an integer!");
input.nextLine(); // consume invalid input
}
}
}
public static void main(String[] args) {
String str1 = readLine("Type some text: ");
System.out.println("Text read is: " + str1);
int i = readPosInt("Type an integer: ");
System.out.println("Integer read is: " + i);
String str2 = readLine("Type some text again: ");
System.out.println("Text read is: " + str2);
input.close();
}
}
阅读全文