gpt4 book ai didi

java - 意想不到的结果 - 可以请一些人指出错误

转载 作者:行者123 更新时间:2023-12-01 23:18:43 25 4
gpt4 key购买 nike

在花费了几个小时并尝试了不同的事情之后,我无法弄清楚我的代码出了什么问题,这是一个简单的程序:`

public class AssignGrades {

private int ntotal=0;
private int []y;

//constructor to initialize class instances
AssignGrades(int t)
{
ntotal = t;
//y = num1;

}
AssignGrades( int []num1)
{
y=num1;
for (int i=0;i<y.length;i++)
y[i] = num1[i];

}
//method to sort grades int []num1

void setGrades()
{
int [] y = new int[ntotal];
for (int i=0;i<y.length;i++)

{

//assign grades
if
(y[i]<80){
System.out.println("grade is A" +y[i]);}
else if (y[i]<70)
System.out.println("grade is B" +y[i]);
else if (y[i]<60)
System.out.println("grade is c" +y[i]);
else
System.out.println("FAIL" +y[i]);
}
}

//show student grades - to print array[] values
void showGrades()
{
for (int u: y)
System.out.println(u);
}

}`

我的客户端程序

`import java.util.Scanner;


public class AssignGradesDemo {

public static void main(String[] args) {
// TODO Auto-generated method stub

int t=0;

System.out.println("enter no of students" );

Scanner input = new Scanner(System.in);
{
t=input.nextInt();
// input.close();
}


int [] num1 = new int[t];
System.out.println("enter grades");

Scanner input1 = new Scanner(System.in);
for (int i=0;i<num1.length;i++)
{
num1[i]=input1.nextInt();
}
input1.close();

AssignGrades ag = new AssignGrades(t);
AssignGrades ag1 = new AssignGrades( num1);

ag.setGrades();
ag1.showGrades();

}


}

输出为:

enter no of students
2
enter grades
78
98
grade is A0
grade is A0
78
98

问题:现在在输出“A”和“0”中 -> 问题所在,看起来数组未初始化,所有值似乎为零:而当我单独打印它们时,它们已初始化。 ?!

如果需要更多说明,请告诉我。谢谢

最佳答案

您有一个名为 y 的局部变量和一个同名的类变量 y。这似乎是问题所在。您正在使用本地 y,但我认为您打算使用 y 类。

好吧,你的代码有很多问题。这是修复后的版本。

public class AssignGrades {

private int[] y;

public AssignGrades(int[] num1) {
y = num1;
}

// method to set grades
void setGrades() {
for (int i = 0; i < y.length; i++)
{
// assign grades

if (y[i] < 50)
System.out.println("FAIL" + y[i]);
else if (y[i] < 60)
System.out.println("grade is C" + y[i]);
else if (y[i] < 70)
System.out.println("grade is B" + y[i]);
else if (y[i] < 80) {
System.out.println("grade is A" + y[i]);
}

}
}

// method to show student grades
void showGrades() {
for (int u : y){
System.out.println(u);
}
}

}




import java.util.Scanner;

public class AssignGradesDemo {

public static void main(String[] args) {
int t = 0;
System.out.println("enter no of students");

Scanner input = new Scanner(System.in);
t = input.nextInt();

int[] num1 = new int[t];
System.out.println("enter grades");

for (int i = 0; i < num1.length; i++) {
num1[i] = input.nextInt();
}
input.close();

AssignGrades ag = new AssignGrades(num1);

ag.setGrades();
ag.showGrades();
}

}

关于java - 意想不到的结果 - 可以请一些人指出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20845388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com