首页 文章

为什么这段代码没有正常工作[重复]

提问于
浏览
-2

这个问题在这里已有答案:

此代码无法正常运行 . 我无法找到第二次运行循环的原因,它不会为firstName变量输入它只打印“输入名字:” .

import java.util.Scanner;

    public class Test {
        public static void main(String[]args){
          String[] firstName =  new String[30] ;
          String[] secondName = new String [30];
          int[] marksCourseWorkOne =  new int[30];
          int i;
          Scanner sc = new Scanner(System.in);
          for (i = 28; i < firstName.length; i++){
            System.out.print("\nEnter First Name : ");
            firstName[i] = sc.nextLine(); 
            System.out.print("\nEnter Second Name : ");
            secondName[i] = sc.nextLine();
            System.out.print("\nEnter Marks For Course Work One : ");
            marksCourseWorkOne[i] = sc.nextInt();
          }
     }
}

1 回答

  • 4

    首先,不要在nextInt之后使用nextLine,因为后者不使用 \n char,它会被 nextLine 吞噬,使其跳过你想要插入的实际输入 .

    第二,如果你是编译器,你认为 i 是什么?你不会知道,因为程序员没有告诉你 . 你应该写 int i = 28 (你确定它应该是28而不是0?) .

    第三,你没有程序的入口点,所有这些应该在 main 方法(或任何其他方法)内 .

    解:

    • 阅读basic tutorial .

    • 定义 i .

    • nextInt 之后添加另一个 nextLine 以使用 \n .

    • 添加方法! (与1相关) .

相关问题