您的位置:首页 > 编程语言 > Java开发

JAVA学习笔记(一)Vector类中set方法的使用问题

2015-03-28 13:38 711 查看
最近在学习JAVA语言,前天做了一个学校实验报告册里的实验,题目如下:

设计并实现一个应用程序,创建一个柱状图,用于查看一组数字分布情况。程序在1-100的整数范围内读取任意数量的整数(以-1结束),然后生成一个类似一于下面所示的图,以指明有多少输入值分别属于1-10,11-20,等等。对应每一个输入值打印出一个星号。

(1)程序输出格式如下:

     1  -  10   | * * * *

     11 -  20   | * *

     21 -  30   | * * * * * * * * * * * * * *

     31 -  40   | 

     41 -  50   | * * *

     51 -  60   | * * * * * * * *

     61 -  70   | * *

     71 -  80   | * * * * *

     81 -  90   | * * * * * * *

     91 -  100  | * * * * * 
思来想去,不知道如何用数组实现动态申请空间。再请教度娘之后呢,我了解了vector这个类,于是就有了一下程序:

import java.util.Scanner;
import java.util.Vector;

public class Exp2_3_1 {
public static Vector<Integer>  getNumber(){

System.out.print("please input numbers:");
int n=0;
Vector<Integer> num = new Vector<Integer>(1,1);
@SuppressWarnings("resource")
Scanner in=new Scanner(System.in);
do
{

num.set(n, in.nextInt());
n++;
}while(num.get(n)!=-1);
return num;
}
public static void print(int x,int n){
System.out.print(x-9+" - "+(x)+" | ");
for(int i=0;i<n;i++){
System.out.print("*");
}
System.out.print("\n");
}
public static void main(String[] args){
Vector<Integer> num=getNumber();
int[] mark=new int[10];
int y=num.size()-1;
while(y>0){
for(int i=0;i<10;i++){
if(num.get(y)-(i+1)*10<=0){
mark[i]++;break;
}
}
y--;
}
for(int i=0;i<10;i++)
print((i+1)*10,mark[i]);
}
}


但是,这个程序是有问题的,问题主要出在
num.set(n, in.nextInt());
这条语句上面,错误提示为数组越界。

为了搞清到底为何会出现这个错误,我们先来看下api中对于该方法的解释:

 set

public E set(int index,

             E element)

Replaces the element at the specified position in this Vector with the specified element.

Specified by:

set in interface List<E>

Overrides:

set in class AbstractList<E>

Parameters:

index - index of element to replace.

element - element to be stored at the specified position.

Returns:

the element previously at the specified position.

Throws:

ArrayIndexOutOfBoundsException - index out of range (index < 0 || index >= size()).

Since:

1.2

很明显,vector.set的用法是取代特定位置上的元素。也就是说必须vector中已经存在了元素,才可以使用set进行修改。修改后的代码如下:

import java.util.Scanner;
import java.util.Vector;
public class Exp2_3 {

public static Vector<Integer>  getNumber(){

System.out.print("please input numbers:");

Vector<Integer> num = new Vector<Integer>(1,1);
@SuppressWarnings("resource")
Scanner in=new Scanner(System.in);
do
{

int x=in.nextInt();
if(x==-1) break;
num.add(x);
}while(true);
return num;
}
public static void print(int x,int n){
System.out.print(x-9+" - "+(x)+" | ");
for(int i=0;i<n;i++){
System.out.print("*");
}
System.out.print("\n");
}
public static void main(String[] args){
Vector<Integer> num=getNumber();
int[] mark=new int[10];
int y=num.size()-1;
while(y>0){
for(int i=0;i<10;i++){
if((num.get(y)-(i+1)*10)<=0){
mark[i]++;break;
}
}
y--;
}
for(int i=0;i<10;i++)
print((i+1)*10,mark[i]);
}
}


以上修改正确,代码成功运行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java
相关文章推荐