2012-04-15 22 views
0

我试图读取infile中的每个整数并将其传递给方法adScore,该方法确定字母等级,以及所有等级和最高考试分数和最低考试分数。但是我的while循环在执行for循环时并没有从infile中提取数据,因为我在执行system.out.print的for循环之后调试它。什么回报只是数字0-29这是我的循环计数器。可以帮助我了解我做错了什么,以便我可以从infile中提取成绩分数?需要从infile中取出每个整数并将其传递给方法

问候。

 while(infile.hasNextInt()) 
     { 
      for(int i=0; i <30; i++)//<-- it keeps looping and not pulling the integers from the  file. 
      { 
       System.out.println(""+i);//<--- I placed this here to test what it  is pulling in and it is just counting 
       //the numbers 0-29 and printing them out. How do I get each data from the infile to store 
       exam.adScore(i);//determines the count of A, B, C, D, F grades, total count, min and max 
      } 
     } 

回答

1

特隆的权利---你并没有要求扫描仪读取下一个整数。 Scanner.hasNextInt()只需测试以查看是否有要读取的整数。你只是告诉i循环值0-29。我想你的意思是做这样的事情:

while(infile.hasNextInt()) 
{ 
    int i = infile.nextInt(); 
    exam.adScore(i);//determines the count of A, B, C, D, F grades, total count, min and max 
} 

如果你不知道的是,在输入的每一行是一个整数,你可以做这样的事情:

while(infile.hasNext()) { // see if there's data available 
    if (infile.hasNextInt()) { // see if the next token is an int 
     int i = infile.nextInt(); // if so, get the int 
     exam.adScore(i);//determines the count of A, B, C, D, F grades, total count, min and max 
    } else { 
     infile.next(); // if not an int, read and ignore the next token 
    } 
} 
+0

谢谢!我一直在努力研究如何从循环中的infile中获取数据。我不知道我是否可以使用另一个局部变量并将输出分配给该局部变量。这就说得通了!我永远不会忘记这一点,因为我已经在这一连串3天的时间里撞到了我的头:( – SaintClaire33 2012-04-15 12:32:42

2

它打印0 - 29,因为这是你告诉它做的事:

System.out.println(""+i) 

会打印出我,这简直是您正在使用的循环计数器的整数。你永远不会从扫描仪对象中检索下一个值。我猜这是作业,所以我不会给你任何代码,但我会说你一定需要使用Scanner的nextInt()方法来检索输入文件中的值,并在你的内部使用该值for循环。

+0

感谢。是的,我尝试将infile放在那里,但是我有一堆空白的错误。我试过这个来测试它:System.out.println(“”+ infile); rator = \。] [positive prefix =] [negative prefix = \ Q- \ E] [positive suffix =] [negative suffix =] [NaN string = \ Q?\ E] [infinity string = \ Q?\ E] java.util.Scanner [delimiters = \ p {javaWhitespace} +] [position = 0] [match valid = true] [need input = false] [source closed = false] [skipped = false] [group separator = \,] [decimal sepa – SaintClaire33 2012-04-15 02:16:47

相关问题