验证用户输入

发布于 2024-09-28 19:47:46 字数 2498 浏览 0 评论 0原文

我快完成了,但是我的代码中有两件事困扰着我。 当我向用户查询测试分数时,如果分数不在 0-100 范围内,我想不接受它,然后告诉他们原因并要求另一个输入。 我还想在平均分数旁边打印他们的平均成绩字母。 由于某种原因,当我尝试检查以确保输入的分数在 0-100 范围内时,我的 If 逻辑语句不起作用。 另外,我不知道如何打印字母等级,但我没有收到任何错误输出,所以我认为我走在正确的轨道上。我认为我可以主要在 while 循环中使用指针来检查数字是否在 0-100 范围内。我将不胜感激。 这是我的代码:

    import java.text.DecimalFormat;
import java.util.Scanner;
public class GradeReport 
{
 String name;
 int score1, score2, score3;
 double average;
 String grade;
 public GradeReport()  //creates the first constructor
 {
  Scanner sc = new Scanner (System.in);

  System.out.println ("Enter student's name: ");
  name = sc.nextLine();

  System.out.println ("Enter first grade: "); //try while loops to get grade in between 0-100
    score1 = sc.nextInt();
    while
        (score1 <0 || score1 > 100);
    System.out.println("please enter a grade 0-100"); //checks that score is inclusive 1-100

    System.out.println ("Enter second grade: ");
    score2 = sc.nextInt();
    while
        score2 <0 || score2 > 100;
    System.out.println("please enter a grade 0-100");//checks that score is inclusive 1-100

    System.out.println ("Enter third grade: ");
    score3 = sc.nextInt();
    while
        score3 <0 || score3 >100;
    System.out.println("please enter a grade 0-100");//checks that score is inclusive 1-100
 }
 public GradeReport (String v1, int v2, int v3, int v4)
 {
  name = v1;  //these are to initialize the variables so that I don't get null for the second set of results.
  score1 = v2;
  score2 = v3;
  score3 = v4;
 }
 public void calculateAvg()
 {
  average = (double)((score1 + score2 + score3) / 3.0);


 }
 public String calculateGrade()
 {
  if (average >= 90)
   grade = "A";
  else if (average >= 80)
   grade = "B";
  else if (average >= 70)
   grade = "C";
  else if (average >= 60)
   grade = "D";
  else
   grade = "F";
  return grade;
 }

 public String toString()
 {
  DecimalFormat fmt = new DecimalFormat ("0.00"); //to format average to 2 decimal places
  String gradeReport = name + "\n " + Double.toString(score1) + "\t" + Double.toString(score2)+ "\t" + Double.toString(score3) + "\n" + fmt.format(average) + grade;
  return gradeReport;
 }

 public static void main (String[] args)
 {
  GradeReport gr1 = new GradeReport();
  GradeReport gr2 = new GradeReport("Col Een", 76, 76, 75);
  gr1.calculateAvg();
  gr1.calculateGrade();
  gr2.calculateAvg();
  gr2.calculateGrade();
  System.out.println(gr1);
  System.out.println(gr2);
 }

}

I am almost done with this but there are 2 things that are stumping me in my code.
When I query a user for the test score, if the score is not within the 0-100 range, I want to not accept it and then tell them why and ask for another input.
I also want to print the letter grade for their average next to their average score.
For some reason my If logic statement isn't working when I try to check to make sure the score entered is within 0-100.
Also I can't figure out how to get the letter grade to print, but I am not getting any error output so I think that I am on the right track. I think that I could mainly use pointers on my while looping to check for the number being in the range of 0-100. I would greatly appreciate it.
Here is my code:

    import java.text.DecimalFormat;
import java.util.Scanner;
public class GradeReport 
{
 String name;
 int score1, score2, score3;
 double average;
 String grade;
 public GradeReport()  //creates the first constructor
 {
  Scanner sc = new Scanner (System.in);

  System.out.println ("Enter student's name: ");
  name = sc.nextLine();

  System.out.println ("Enter first grade: "); //try while loops to get grade in between 0-100
    score1 = sc.nextInt();
    while
        (score1 <0 || score1 > 100);
    System.out.println("please enter a grade 0-100"); //checks that score is inclusive 1-100

    System.out.println ("Enter second grade: ");
    score2 = sc.nextInt();
    while
        score2 <0 || score2 > 100;
    System.out.println("please enter a grade 0-100");//checks that score is inclusive 1-100

    System.out.println ("Enter third grade: ");
    score3 = sc.nextInt();
    while
        score3 <0 || score3 >100;
    System.out.println("please enter a grade 0-100");//checks that score is inclusive 1-100
 }
 public GradeReport (String v1, int v2, int v3, int v4)
 {
  name = v1;  //these are to initialize the variables so that I don't get null for the second set of results.
  score1 = v2;
  score2 = v3;
  score3 = v4;
 }
 public void calculateAvg()
 {
  average = (double)((score1 + score2 + score3) / 3.0);


 }
 public String calculateGrade()
 {
  if (average >= 90)
   grade = "A";
  else if (average >= 80)
   grade = "B";
  else if (average >= 70)
   grade = "C";
  else if (average >= 60)
   grade = "D";
  else
   grade = "F";
  return grade;
 }

 public String toString()
 {
  DecimalFormat fmt = new DecimalFormat ("0.00"); //to format average to 2 decimal places
  String gradeReport = name + "\n " + Double.toString(score1) + "\t" + Double.toString(score2)+ "\t" + Double.toString(score3) + "\n" + fmt.format(average) + grade;
  return gradeReport;
 }

 public static void main (String[] args)
 {
  GradeReport gr1 = new GradeReport();
  GradeReport gr2 = new GradeReport("Col Een", 76, 76, 75);
  gr1.calculateAvg();
  gr1.calculateGrade();
  gr2.calculateAvg();
  gr2.calculateGrade();
  System.out.println(gr1);
  System.out.println(gr2);
 }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

抽个烟儿 2024-10-05 19:47:46

一些评论...

缩进

请尽量与您的缩进风格保持一致。它使您的代码更易于阅读。

空白

请小心管理空白。当您阅读一本书、一本杂志或一个网页时,空格用于分隔想法 - 段落、部分等。同样,空格应该用于分隔您的功能或功能中的想法。例如:

void f1()
{
  do();
  domore();
}


void f2()
{
  doAnotherThing();
  andYetAnother();
}


void f3()
{
  do1();
  do2();

  do3();
  do4();
}

请注意,很容易看到有 3 个独立的函数,第三个函数有两组独立的函数正在执行 - do1() 和 do2() 与 do3() 和 do4() 之间有空格,直观地表明 do1() 和 do2() 存在相似之处,do3() 和 do4() 也存在相似之处,并且 1&2 与 3&4 有所不同。

如果这没有意义,请随意忽略:)(但我建议您阅读一本基本的视觉设计书)

大括号

养成在所有条件周围使用大括号的习惯是个好主意块 - 它非常清楚块的开始和结束位置。例如,

if(condition)
   line1;
   line2;

与第一种情况不同

if(condition)
{
   line1;
   line2;
}

,当且仅当条件为真时,line1 才会执行,但无论如何,line2 都会执行 - 缩进是欺骗性的。在第二种情况下,当且仅当条件为真时,line1 和 line2 才会执行。

在第一种情况下,意图尚不清楚 - 原始开发人员是否搞砸了缩进(对于迂腐的人来说,忽略使用缩进来管理循环的语言)?或者他/她忘记戴牙套了吗?如果第一种情况写成如下,我们就知道答案了:

if(condition) {
  line1
}
  line2

当然,如果整个文件的缩进一致,那么下面代码的意图也很清楚:

if(condition)
  line1
line2

无限循环

注意尾随分号

 while
        (score1 <0 || score1 > 100);

结束了块。如果score1无效,循环将永远不会退出。

编译

我不确定这

while
        score2 <0 || score2 > 100;

是否是有效的代码。您应该在条件周围放置括号。您还再次遇到了尾随分号的无限循环问题。

获取成绩

当您询问成绩时,您的代码当前看起来像这样,

score = readLine()
while(...)
  System.out.println(...)

这意味着您读取用户输入,然后进入循环,在循环中打印一条消息。请记住:循环从 while 开始的地方开始,因此在第一次迭代之后永远不会读取输入。您需要读取用户在循环的每次迭代中写入的值。

score = readline()
while(score is invalid)
{
   print error
   score = readline()
}

变量命名

如果这部分现在没有意义,请忽略它 - 认为它是对您稍后将学到的内容的糟糕介绍。

如果可以选择,您应该始终有意义地命名变量。 GradeReport 构造函数有 4 个变量,如果您无法访问源代码,则完全不清楚其用途:

public GradeReport (String v1, int v2, int v3, int v4)

您可以使用与类槽相同的变量名称,并且可以使用 this关键字。如果我们首先在构造函数中为所有类变量插入 this ,其余部分保持不变,则变为:

 public GradeReport (String v1, int v2, int v3, int v4)
 {
  this.name = v1;  //these are to initialize the variables so that I don't get null for the second set of results.
  this.score1 = v2;
  this.score2 = v3;
  this.score3 = v4;
 }

如果我们将 v1 替换为“name”...

 public GradeReport (String name, int v2, int v3, int v4)
 {
  this.name = name;  //these are to initialize the variables so that I don't get null for the second set of results.
  this.score1 = v2;
  this.score2 = v3;
  this.score3 = v4;
 }

然后将 v2 替换为 Score1...

 public GradeReport (String name, int score1, int v3, int v4)
 {
  this.name = name;  //these are to initialize the variables so that I don't get null for the second set of results.
  this.score1 = score1;
  this.score2 = v3;
  this.score3 = v4;
 }

Some comments...

indentation

Please try to be consistent with your indentation style. It makes your code much easier to read.

whitespace

Be careful how you manage your whitespace. When you read a book or a magazine or a web page, blank spaces are used to separate ideas - paragraphs, sections, etc. Similarly, empty space should be used to separate your functions, or ideas within functions. For example:

void f1()
{
  do();
  domore();
}


void f2()
{
  doAnotherThing();
  andYetAnother();
}


void f3()
{
  do1();
  do2();

  do3();
  do4();
}

Note that it's easy to see that there are 3 separate functions, and the third function has two separate groups of things it's doing - do1() and do2() are separated from do3() and do4() with empty space, visually indicating that there's something similar about do1() and do2(), something else similar about do3() and do4(), and that 1&2 are somehow different from 3&4.

If that doesn't make sense, feel free to ignore :) (but I would suggest you read a basic visual design book)

braces

It's a good idea to get into the habit of using braces around all conditional blocks - it makes it very clear where the block begins and ends. For example,

if(condition)
   line1;
   line2;

is different from

if(condition)
{
   line1;
   line2;
}

In the first case, line1 will execute if and only if the condition is true, but line2 will evaluate no matter what - the indentation is deceiving. In the second case, both line1 and line2 will execute if and only if the condition is true.

In the first case, the intention is unclear - did the original developer screw up indentation (for the pedantic, ignore languages that use indentation to manage loops)? Or did s/he forget the braces? If the first case were written as follows, we'd know the answer:

if(condition) {
  line1
}
  line2

Of course, if indentation were consistent through the file, the intention of the following code would be clear, as well:

if(condition)
  line1
line2

infinite loop

Note the trailing semicolon that you have on

 while
        (score1 <0 || score1 > 100);

The trailing semicolon ends the block. If score1 is invalid, the loop will never exit.

compilation

I'm not sure that

while
        score2 <0 || score2 > 100;

is valid code. You should place parens around the condition. You've also got the infinite loop problem with the trailing semicolon, again.

getting grades

When you ask for grades, your code currently looks like

score = readLine()
while(...)
  System.out.println(...)

This means that you read user input, then enter the loop, in which you print a message. Remember: the loop starts where the while starts, so reading input never happens after the first iteration. You need to read the value the user writes every iteration of the loop.

score = readline()
while(score is invalid)
{
   print error
   score = readline()
}

variable naming

Ignore this section if it doesn't make sense right now - consider it a bad introduction to stuff you'll learn later.

If you have the option, you should always name your variables meaningfully. The GradeReport constructor has 4 variables, whose purpose is totally unclear if you don't have access to the source code:

public GradeReport (String v1, int v2, int v3, int v4)

You could use the same name for the variable as the class slot, and you can differentiate with the this keyword. If we first insert this for all class variables in the constructor, and leave the rest unchanged, it becomes:

 public GradeReport (String v1, int v2, int v3, int v4)
 {
  this.name = v1;  //these are to initialize the variables so that I don't get null for the second set of results.
  this.score1 = v2;
  this.score2 = v3;
  this.score3 = v4;
 }

and if we replace v1 with "name"...

 public GradeReport (String name, int v2, int v3, int v4)
 {
  this.name = name;  //these are to initialize the variables so that I don't get null for the second set of results.
  this.score1 = v2;
  this.score2 = v3;
  this.score3 = v4;
 }

and then replace v2 with score1...

 public GradeReport (String name, int score1, int v3, int v4)
 {
  this.name = name;  //these are to initialize the variables so that I don't get null for the second set of results.
  this.score1 = score1;
  this.score2 = v3;
  this.score3 = v4;
 }
把回忆走一遍 2024-10-05 19:47:46

您的某些代码对我来说看起来无法编译,但除此之外,请考虑以下三行代码之间的区别:

while (score1 <0 || score1 > 100)

if (score2 <=0)

if (score3 <=0)

我认为您会在那里找到部分问题。对于验证,请考虑以下模式:

do {
  //collect input
} while (something that's false if input is invalid);

Some of your code looks uncompilable to me, but that aside, consider the difference between the following three lines of code:

while (score1 <0 || score1 > 100)

compared to

if (score2 <=0)

and

if (score3 <=0)

I think you'll find part of your problem there. For validation, consider the following pattern:

do {
  //collect input
} while (something that's false if input is invalid);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文