java - 我怎样才能让它运行?
问题描述
好像我已经尝试了一切,但没有任何效果。我怎样才能得到这个,以便用户可以决定是否添加另一个名字?我可以在没有用户决定的情况下很好地运行 for 循环。
import java.util.Scanner;
import java.text.DecimalFormat;
public class Part2 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
final int STUDENT_SIZE = 50;
char choice1 = 'n';
int i = 0;
int stdntLength = 0;
boolean choice = true;
String[] stdntName = new String[STUDENT_SIZE];
String[] WIDNUM = new String[STUDENT_SIZE];
int[] EXM1 = new int[STUDENT_SIZE];
int[] EXM2 = new int[STUDENT_SIZE];
int[] EXM3 = new int[STUDENT_SIZE];
int[] finalExm = new int[STUDENT_SIZE];
do {
for (i = 0; i < stdntName.length; i++) {
System.out.println("Please enter the name of Student "
+ (i + 1) + ": ");
stdntName[i] = s.nextLine();
String fullName = stdntName[i];
String str[] = fullName.split(" ");
StringBuilder sb = new StringBuilder();
sb.append(str[1]);
sb.append(", ");
sb.append(str[0]);
String fullname = sb.toString();
stdntName[i] = fullname;
System.out.println(stdntName[i]);
System.out.print("Do you wish to enter another? (y/n): ");
choice1 = s.next().charAt(0);
}
} while (choice1 == 'y');
}
}
解决方案
do-while
循环似乎是多余的,可能会被删除。
在输入第 i 个学生的数据时,最好检查输入,y
如果没有输入任何字符,y
则中断。
更新
其他需要解决的问题:
str
拆分全名时检查长度;将姓氏移到开头(不仅仅是第二个名字)。- 在阅读时使用
nextLine()
而不是- 因为不被消耗,并且下一个读取的名称将是一个空行。next()
choice1
\n
nextLine
for (i=0; i < stdntName.length; i++) {
System.out.println("Please enter the name of Student " + (i+1) + ": ");
stdntName[i] = s.nextLine();
String fullName = stdntName[i];
String str [] = fullName.split(" ");
if (str.length > 1) {
StringBuilder sb = new StringBuilder();
sb.append(str[str.length - 1]); // move the last name to beginning
sb.append(", ");
for (int j = 0; j < str.length - 1; j++) { // join remaining names
if (j > 0) {
sb.append(' ');
}
sb.append(str[j]);
}
stdntName[i] = sb.toString();
}
System.out.println(stdntName[i]);
System.out.print("Do you wish to enter another? (y/n): ");
choice1 = s.nextLine().toLowerCase().charAt(0); // read entire line
if (choice1 != 'y') {
break;
}
}
推荐阅读
- matlab - 用 1 随机替换矩阵中的零
- openshift - 将 Let's Encrypt 与 openshift-acme 一起使用
- apache-spark - 我可以从 Spark 依赖项中安全地删除 Hive jar 吗?
- javascript - 类型错误:类扩展值未定义不是构造函数或 nulll
- python - 有没有办法使用 matplotlib 使颜色条仅显示一系列值?
- javascript - 如何不覆盖以前的文本
?
- python - 在哪里可以找到 Github 上某个模块缺少的 Python API/文档?
- flutter - 从 Firestore 存储和检索多个复选框值
- python - Flask / Python:如何从另一个文件调用函数?
- python - 我可以有一个启用了实时字典的界面吗?