输入一个数组(以"#"结束)并排序输出,运行出问题,请大家看下怎么解决
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class ArraySort
{
private int a[],num;
public ArraySort(int n)
{
a=new int[n];
num=n;
}
public void putIn()
{
for(int i=0;i<num;i++)
{
System.out.print("a["+i+"]=");
Scanner scan=new Scanner(System.in);
if(scan.equals("#")){num=i;break;}
a[i]=scan.nextInt();
}
}
public void putOut()
{
for(int i=0;i<num;i++)
{
for(int j=i;j<num;j++)
{
if(a[i]>a[j])
{
int t=a[i];
a[i]=a[j];
a[j]=t;
}
}
System.out.print(a[i]+" ");
}
System.out.println();
}
public static void main(String args[])
{
ArraySort array=new ArraySort(5);
array.putIn();
array.putOut();
}
}
[解决办法]
scan输入,先获得值再做判断。只要修改 putin()函数
import java.awt.*;import java.util.*;import javax.swing.*;public class ArraySort { private int a[], num; public ArraySort(int n) { a = new int[n]; num = n; } public void putIn() { for (int i = 0; i < num; i++) { System.out.print("a[" + i + "]="); Scanner scan = new Scanner(System.in); String str = scan.next(); if (str.equals("#")) { num = i; break; } a[i] = Integer.parseInt(str); } System.out.println("put in"); } public void putOut() { for (int i = 0; i < num; i++) { for (int j = i; j < num; j++) { if (a[i] > a[j]) { int t = a[i]; a[i] = a[j]; a[j] = t; } } System.out.print(a[i] + " "); } System.out.println("put out"); } public static void main(String args[]) { ArraySort array = new ArraySort(5); array.putIn(); array.putOut(); }}