在不添加额外的readLine的情况下读取字符后无法接受下一个输入

时间:2018-06-30 16:55:56

标签: java char bufferedreader

必须添加额外的行“ String x = in.readLine();”在读取字符“ sec =(char)in.read();”之后否则,程序将不会继续进行更多的输入,请参见下面的代码注释。请注意,我不想使用扫描仪类。

import java.io.*;
class marks
{
public static void main(String args[])
{
    BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
    int rl,m1,m2,m3,tot=0;
    String nm,cl;
    nm=cl="";
    char sec='A';
    double avg=0.0d;
    try
    {
        System.out.println("Enter the information of the student");
        System.out.print("roll no:");
        rl=Integer.parseInt(in.readLine());
    System.out.print("class:");
    cl=in.readLine();
    System.out.print("section:");
    sec=(char)in.read();
    String x=in.readLine();  /* have to add this line only then marks of 3 subject can be inputed */
    System.out.println("marks of three subjects "+x);
    m1=Integer.parseInt(in.readLine());
    m2=Integer.parseInt(in.readLine());
    m3=Integer.parseInt(in.readLine());
    tot=m1+m2+m3;
    avg=tot/3.0d;
    System.out.println("total marks of the students = "+tot);
    System.out.println("avg marks of the students = "+avg);
    }
    catch (Exception e)
    {};
}
} 

3 个答案:

答案 0 :(得分:1)

如何更换:

sec=(char)in.read();

具有:

sec = in.readLine().charAt(0);

答案 1 :(得分:0)

解决

import java.io.BufferedReader;
import java.io.InputStreamReader;

class Marks {
    public static void main(String args[]) {
        try (BufferedReader in = new BufferedReader(new InputStreamReader(System.in))) {
            int rl, m1, m2, m3, tot = 0;
            String nm, cl;
            nm = cl = "";
            char sec = 'A';
            double avg = 0.0d;
            System.out.println("Enter the information of the student");
            System.out.print("roll no:");
            rl = Integer.parseInt(in.readLine());
            System.out.print("class:");
            cl = in.readLine();
            System.out.print("section:");
            sec = in.readLine().charAt(0); //changes are here, instead of 
            // String x = in.readLine(); /* have to add this line only then marks of 3
            // subject can be inputed */
            System.out.println("marks of three subjects ");
            m1 = Integer.parseInt(in.readLine());
            m2 = Integer.parseInt(in.readLine());
            m3 = Integer.parseInt(in.readLine());
            tot = m1 + m2 + m3;
            avg = tot / 3.0d;
            System.out.println("total marks of the students = " + tot);
            System.out.println("avg marks of the students = " + avg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  

输出

Enter the information of the student
roll no:21
class:10
section:c
marks of three subjects 
56
65
56
total marks of the students = 177
avg marks of the students = 59.0

答案 2 :(得分:0)

问题是当您根据文档使用in.read()时:“读取单个字符”,但实际上是键入“两个”字符:一个字符和一个“ \ n”,它们存储在InputStreamReader的缓冲区中并在您使用in.readLine();

时会再次读取