本文介绍了LOOP->阵列输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个循环来填充数组。我想我已经编码了,但是当我运行通过Java编译code,它不直接在命令提示符下出来了。

I'm writing a loop to fill an array. I think I have the coding down, but when I run the compiled code through Java, it doesn't come out right in the command prompt.

这里的code:

import java.util.Scanner;
import java.io.*;
public class Pr42
{
    public static void main(String[]args) throws IOException
{
    int k,m,g;
    String n;
    //double g;
    Scanner input1=new Scanner(System.in);
    String[]Name=new String [5];
    double[]Grade=new double[Name.length];
    k=0;
    while (k<Name.length)
        {
        m=k+1;
        System.out.print("Enter the name of student "+m+": ");
        Name[k]=input1.nextLine();
        System.out.print("");
        System.out.print("Please enter the grade of student "+m+": ");
        Grade[k]=input1.nextInt();
        k++;
        }
    }
}

下面是在命令提示符下的输出:

Here's the output in the command prompt:

输入学生1名:

请输入学生1级:

请输入学生2名:请输入学生2级:

Please enter the name of student 2: Please enter the grade of student 2:

问题是关于第二个学生该行。

The problem is that line regarding the second student.

我做了什么错在code得到这样的输出?

What did I do wrong in the code to get an output like that?

推荐答案

您需要确定名称中下一行输入,名称[K] = input1.nextLine();

You need to identify name has input in next line with Name[k] = input1.nextLine();

int k, m, g;
String n;
//double g;
Scanner input1 = new Scanner(System.in);
String[] Name = new String[5];
double[] Grade = new double[Name.length];
k = 0;
while (k < Name.length) {
    m = k + 1;
    System.out.print("Enter the name of student " + m + ": ");
    Name[k] = input1.nextLine();
    System.out.print("");
    System.out.print("Please enter the grade of student " + m + ": ");
    Grade[k] = input1.nextDouble();
    input1.nextLine();
    k++;
}

编辑:按照这个答案下汤姆的评论中提到,当你有名称[K] = input1.nextLine(); 而不是 input1.nextLine(); 程序正常工作,但它与数组的价值搞砸

EDITED: As per mentioned in Tom's comment under this answer when you have Name[k] = input1.nextLine(); instead of input1.nextLine(); program works correctly, but it messed up with value of array.

这篇关于LOOP-&GT;阵列输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 23:44