有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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');
    }
}

共 (1) 个答案

  1. # 1 楼答案

    do-while循环似乎是多余的,可能会被删除

    在输入第i个学生的数据时,最好检查输入的y,如果输入了除y以外的任何字符,最好将其打断

    更新
    需要解决的其他问题:

    1. 在拆分全名时检查str的长度;将最后一个名称移到开头(而不仅仅是第二个名称)
    2. 在读取choice1时,使用nextLine()而不是next(),因为\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;
            }
        }