for循环中的语句只执行一次

时间:2014-06-07 20:24:06

标签: java loops for-loop java.util.scanner

import java.util.Scanner;

public class Test {

    public static void main(String args[]) {
        String name = " ", n;
        double r, h, s, m = 0;
        int c;

        Scanner i = new Scanner(System.in);
        Employee e[] = new Employee[5];

        for (int j = 0; j < 5; j++) {
            System.out.printf("\nPlease enter the name of Employee %d ", j + 1);
            /* THE PROBLEM LIES IN THE ABOVE STATEMENT IT IS EXECUTED ONLY ONCE WHILE IT'S MEANT TO BE EXECUTED 5 TIMES */
            n = i.nextLine();
            System.out.print("\t1.PartTime\n\t2.FullTime\n");
            c = i.nextInt();

            switch (c) {
                case 1:
                    System.out.print("hours worked ");
                    h = i.nextDouble();
                    System.out.print("rate per hour ");
                    r = i.nextDouble();
                    e[j] = new Part(n, h, r);
                    break;
                case 2:
                    System.out.print("Salary ");
                    s = i.nextDouble();
                    e[j] = new Full(n, s);
                    break;
                default:
                    System.out.print("\n***INVALID*** ");
                    j--;
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

所以你应该在每个案例后添加一个休息时间。

我喜欢使用println而不是printf,它可以让你少用&#34; \ n&#34;并使你的代码更有条理。

你使用的是Java,就像它是C ++一样,我认为这样做容易得多 System.out.println(&#34;请输入员工姓名&#34; +(j + 1));

如果没有剩下的源代码,它会很难帮助你。

答案 1 :(得分:0)

问题是,在第二个循环n = i.nextLine();被跳过,因为Scanner缓冲区中仍然有一行内容,而是需要清除Scanner

您可以添加类似......

的内容
if (i.hasNextLine()) {
    i.nextLine();
}

for-loop的末尾,例如..

for (int j = 0; j < 5; j++) {
    System.out.printf("\nPlease enter the name of Employee %d ", j + 1);
    /* THE PROBLEM LIES IN THE ABOVE STATEMENT IT IS EXECUTED ONLY ONCE WHILE IT'S MEANT TO BE EXECUTED 5 TIMES */
    n = i.nextLine();
    System.out.print("\t1.PartTime\n\t2.FullTime\n");
    c = i.nextInt();

    switch (c) {
        case 1:
            System.out.print("hours worked ");
            h = i.nextDouble();
            System.out.print("rate per hour ");
            r = i.nextDouble();
            e[j] = new Part(n, h, r);
            break;
        case 2:
            System.out.print("Salary ");
            s = i.nextDouble();
            e[j] = new Full(n, s);
            break;
        default:
            System.out.print("\n***INVALID*** ");
            j--;
    }
    if (i.hasNextLine()) {
        i.nextLine();
    }
}

这将确保Scanner之前的输入中没有其他内容