in.read(read);
read[2] 可能没付值 ,
改为
byte[] read=new byte[3];
read[0]=0;
read[1]=0;
read[2]=0;就没事了byte 的范围是 0 - 128 溢出就会不正确
read[2] 可能没付值 ,
改为
byte[] read=new byte[3];
read[0]=0;
read[1]=0;
read[2]=0;就没事了byte 的范围是 0 - 128 溢出就会不正确
这样可以,关键是用readLine()。
不过就不能做到只读两位数了,你可以在判断是否小于0时加入 ||是否大与99的判断语句。import java.io.*;
public class Test {
public static void main(String args[]) {
char[] lread=new char[2];
String mgroup = new String();
int g;
boolean flag = false;
BufferedReader lin =
new BufferedReader(
new InputStreamReader(System.in)); while (!flag) {
System.out.println("Please input how many groups number you want to purchase(1-99):");
// System.in.reset();
try {
mgroup=(lin.readLine()).trim();
}
catch (Exception e) {
System.out.println(e.toString());
}
g=Integer.parseInt(mgroup); //这里会执行错误?
System.out.println(g);
if (g<=0){
flag=false;
}
else
flag=true;}
}
}
2、用readLine的话如何判断输入的是字符串啊?
import java.awt.*;
import java.io.*;public class Application1 {public Application1() {
}
/**Main method*/
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(Exception e) {
e.printStackTrace();
}
new Application1();
byte rea[] = new byte[2];
String group;
int g;
boolean flag=false;
while (!flag) {
System.out.print("Please input how many groups number you want to purchase(1-99):");
try {
System.in.read(rea);
}
catch (Exception e) {
System.out.println(e.toString());
}
try {
group=new String(rea).trim();
g=Integer.parseInt(group);
if (g<=0){
flag=false;
}
else
flag=true;
System.out.println("i love you"+g); }catch(Exception e){
}
} }
}
干吗这么自责,知识总是无止境,共同探讨吧
另外,很少有例程中直接用in去读,它的上面的很多stream类有更多、更简便的方法可以利用。
2。关于对输入内容的判断可以根据parseInt是否出现NumberFormatExeption,把try和catch放入一个while(1)循环中,在catch块中加入continue,在while最后一行加入break;try it!
while (!flag) {
System.out.println("Please input how many groups number you want to purchase(1-99):");
try {
mgroup=(lin.readLine()).trim();
g=Integer.parseInt(mgroup); //这里会执行错误?
}
catch (Exception e) {
continue;
}
if (g<=0||g>100){
flag=false;
}
else
flag=true;}
import java.io.*;
public class Happy {
public static void main(String args[]) {
String mgroup = new String();
int g;
BufferedReader lin =
new BufferedReader(
new InputStreamReader(System.in)); while (true) {
System.out.println("Please input how many groups number you want to purchase(1-99):");
try {
mgroup=(lin.readLine()).trim();
g=Integer.parseInt(mgroup); //这里会执行错误?
if (g<=0||g>100) throw new Exception();
}
catch (Exception e) {
continue;
}
break;}
}
}
{ continue;}
catch (Exepiton e)
{ e.printStackTrace();}