题目要求是:从键盘接收10个数字放到一个数组进行排序再输出最大和最小值.
我的程序编译没错误.就是输出些莫名其妙的数.
import java.io.*;
import java.util.*;
public class Array
{
public static void main(String aa[])throws Exception
{
int ch=0;
int pos=0;
byte buf[]=new byte[255];
String str;
System.out.println("请输入10个数字");
while(true)
{
ch=System.in.read();
if(ch=='\r')
break;
if(ch=='\n')
System.out.write(buf);
buf[pos++]=(byte)ch;
}
Arrays.sort(buf,0,pos);
System.out.println(buf[0]);
System.out.println(buf[pos]);
}
}
我的程序编译没错误.就是输出些莫名其妙的数.
import java.io.*;
import java.util.*;
public class Array
{
public static void main(String aa[])throws Exception
{
int ch=0;
int pos=0;
byte buf[]=new byte[255];
String str;
System.out.println("请输入10个数字");
while(true)
{
ch=System.in.read();
if(ch=='\r')
break;
if(ch=='\n')
System.out.write(buf);
buf[pos++]=(byte)ch;
}
Arrays.sort(buf,0,pos);
System.out.println(buf[0]);
System.out.println(buf[pos]);
}
}
import java.util.*;
public class ArrayTest
{
public static void main(String[] args) throws Exception
{
int pos=0;
String str;
byte buf[]=new byte[10];
System.out.println("请输入10个数字");
DataInputStream dis=new DataInputStream(System.in);while( pos <10 )
{
str = dis.readLine();
buf[pos++]=Byte.parseByte(str);
}
Arrays.sort(buf);
System.out.println("");
System.out.println(buf[0]);
System.out.println(buf[pos-1]);
}
}
2
50
0输入的2 对应的asci码是 50 是你程序里的问题 byte buf[]=new byte[255];
import java.util.*;
public class Array
{
public static void main(String aa[])throws Exception
{
int ch=0;
int pos=0;
byte buf[]=new byte[255];
String str;
System.out.println("请输入10个数字");
while(true) //你的本意是将输入的数字存入到数组buf中,但是实际上,你将空格也存入了数组中,空格的ASC码是32.
{//所以,你输入10个数字后,且每个数字间有一个空格,则你最终的pos的值是19.
ch=System.in.read(); //注意,ch接受到的值实际上是数字的ASC码,要减去48.(48是0的ASC码,在输出处减即可)
if(ch=='\r')
break;
if(ch=='\n')
System.out.write(buf);
if(ch!=32)buf[pos++]=(byte)ch; //加上一个if(ch!=32),空格的ASC码是32,就可以不将空格计算在内,只存入数字了.
}
System.out.println(pos);
Arrays.sort(buf,0,pos);
System.out.println(buf[0]);
System.out.println(buf[pos-1]);//输入了10个数,pos的值是10,但最后一个数在数组中的脚标其实是9,因为数组脚标是从0开始的
for(int i=0;i<pos;i++)System.out.println(buf[i]-48);//用for循环将排完序后的数组输出
}
}