我的代码中发生了一些奇怪的交互,但是我找不到解决方案

时间:2019-05-09 14:00:24

标签: java string java.util.scanner

我计算平均值的代码是正确的,但是我的程序不会按照我希望的方式停止执行。我必须使用扫描仪的功能才能操纵字符串。

所以我想提高Java的水平,导师给我解决了一个问题。程序必须在一个字符串中全部接受régredstudent id及其name of the subject,然后计算该id的平均分数。字符串的格式为marks,其中6位数字为"123456 math 5.5 physics 6.5 end",而id则使程序停止等待数字并进行计算。

  • "end"是从ID0的6位数字,如果是9,则程序必须终止。

  • 000000正在停止输入,但没有停止循环,但是"End"结束了循环。

在我的代码中,一切正常,但要使用我要重置的变量,我必须输入两次单词"000000",如果我想停止循环,则必须两次键入"end",即显然不是我想要的。你能指出我的错误吗?

我的老师建议使用"000000"的功能来获取我想要的东西。因为这些功能起作用,我无法解决这个问题吗?

Scanner

2 个答案:

答案 0 :(得分:1)

“在我的代码中,一切正常”

好吧,不是!

使用String str = sc.next();行读取所需的数据。

您应该将其放在末尾以读取课程名称。

while(sc.hasNext()) {                       
    // check student id
    if (sc.hasNext("[0-9]{6}")) {                 
        AM=sc.next(); // read student number
        System.out.println("AM: " + AM);
        if (AM.equals("000000")) break;
    } 
    // check if line ends prematurely --> error
    else if(sc.hasNext()== false) {
        System.out.println("Data format error.");
        //return;
    } 
    // check for a float
    else if(sc.hasNextFloat()){                  
        sum += sc.nextFloat();  // read the float
        count++;                                
    } 
    // check for "end"
    else if(sc.hasNext("end")){
        String endStr = sc.next(); // read "end"
        System.out.println("Average is " + sum / count);
        count = 0;
        sum = 0.0;
    } 
    // all other not yet considered strings (e.g. a course)
    else {        
        String course = sc.next();  // read course
    }
}

答案 1 :(得分:0)

尝试一下:

    String AM = null;                              //6 numbers from 0-9 consists the student id 
            System.out.println("Give string: ");
    String str = null;
    while(sc.hasNext()) {                       

                if (sc.hasNext("[0-9]{6}"))
                {
                    str = sc.next("[0-9]{6}");
                    AM = str;
                    System.out.println("AM: " + AM);
                    if (AM.equals("000000")) break;
                }

                else if(sc.hasNext()== false) {                       
                    System.out.println("Data format error.");
                    //return;
                   }       

                while(sc.hasNextDouble()){                             
                    sum += sc.nextDouble();
                    count++;                                
                }

                if(sc.next().equals("end")){                             
                    System.out.println("Average is " + sum / count);
                    count = 0;
                    sum = 0.0;
                }
    }

我没有检查您的sc.hasNext()== false是否有效,但是其他所有东西似乎都正常运行。仅键入结束一次即可转到下一个选项,“ 000000”结束整个程序。我将下一个浮点数更改为下一个双精度点,因为您已将sum声明为一个双精度点,并将其放入循环中,以便找到所有下一个双精度点。我也将所有后续操作都移到了条件中。请记住,.next()移至下一个。使用sc.hasNext(“ end”)的旧代码根本没有移动光标。让我知道是否有事或有任何疑问!