开发者

number not printing only [] is coming in text file

开发者 https://www.devze.com 2023-01-28 12:04 出处:网络
In the below code the questions, answers i enter in jsp form are entered in text file. But infront of it number must be printed

In the below code the questions, answers i enter in jsp form are entered in text file. But infront of it number must be printed

<%@ page language="java" import="java.io.*" errorPage="" %>
<%

         /* String num=request.getParameter("qnum");
    session.setAttribute("quesnum",num);*/

    String q=request.getParameter("qn");
    session.setAttribute("question",q);

    String opt1=request.getParameter("A");
    session.setAttribute("a",opt1);

    String opt2=request.getParameter("B");
    session.setAttribute("b",opt2);

    String opt3=request.getParameter("C");
    session.setAttribute("c",opt3);

    String opt4=request.getParameter("D");
    session.setAttribute("d",opt4);

    String ans=request.getParameter("ANS");
    session.setAttribute("answer",ans);


%>

<html>
<head>
<title>Text File</title>
</head>

<body>
<%



File f=new File("D:\\Program Files\\Tomcat 6.0\\webapps\\ROOT\\tst.txt");
f.createNewFile();
try
{

BufferedWriter bw=new BufferedWriter(new FileWriter(f,true));

    int num=1;

   bw.newLine();
 while(num<100)
   {  

        bw.write((char)num);
        bw.write("|");
    bw.write(q);

        bw.write("|");
    bw.write(opt1);

        bw.write("|");
    bw.write(opt2);

        bw.write("|");
    bw.write(opt3);

        bw.write("|");
    bw.write(opt4);

        bw.write("|");
        bw.write(ans);

        bw.flush();


bw.close();
}

num++;
}
catch(Exception e)
{
}
%>

</body>
</html>

Output must be 
1|quest1开发者_运维技巧|option a |option b|option c|option d| and:a
2|quest2|option a |option b|option c|option d| and:b
3|quest3|option a |option b|option c|option d| and:d

but instead of 1 2 3 i get 
 []|quest1|option a |option b|option c|option d| and:a

[] symbol is coming in text file. Whats the problem?


You are casting the intnumbers from 1 to 100 to char as byte-values. This is probably not what you want, because this is - assuming western languages - equivalent to the ASCII table from the beginning on. The first 32 or so characters are non-printable stuff like Linefeeds, Beeps etc. which apparently do not make it into your output.

So instead of

bw.write((char)i);

you need to convert your int into a String, e. g. like so:

bw.write(String.valueOf(i));


Here

bw.write((char)num);

you're converting the number (e.g. 1) to a char but you want the number printed as a string:

bw.write(String.valueOf(num));

is a simple solution.

bw.write(String.format("%d", i));

is slightly better as is allows formatting of the numbers (alignment, leading zeros, ...)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号