ASCII艺术的数字表示

时间:2015-03-08 01:48:19

标签: java ascii

我正在尝试编写一个程序,将ASCII艺术的数字表示转换为艺术本身。

例如,

3
2,+,3,*
5,-
1,+,1,- 

应该给:

3
++***
-----
+-

“art”和数字表示顶部显示的数字是文件中显示的行数。

这是我为此任务编写的代码。文件“origin.txt”包含ASCII艺术的数字表示,而目标文件夹应该获得艺术本身。

import java.io

import java.util.*; 

public class Numerical
{
    public static void main(String[]args)

    throws FileNotFoundException
    {
        File input = new File("origin.txt");
        File output = new File("destination.txt");
        numToImageRep(input,output); 
    }
    public static void numToImageRep(File input, File output)

throws FileNotFoundException
    {
        Scanner read = new Scanner(input);
        PrintStream out = new PrintStream(output);      
       int size =     read.nextInt();                                           
        String symbol; 
        out.println(size);

    for(int i = 0; i < size; i++)                                 
    {
        int x = 0; 
        symbol = read.next();
        while(x < symbol.length())
        {
            char a = symbol.charAt(x);                           
            int c = Character.getNumericValue(a);          
            x = x + 2 ;
            char L = symbol.charAt(x);                    
            for(int j = 0; j < c; j++)
            {
                out.print(L);
            }
            x = x + 2; 
        }
        out.println(); 
    }

}

}

此代码似乎适用于不包含空格的数字格式,但只要数字格式中出现空格,我就会得到一个超出范围的字符串异常。

例如:

2
2,+,2,*
1,+,6,-

将转换为艺术,

但是,

2
2, ,5,*
3, ,9,*

将导致:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException:   String index out of range: 2
at java.lang.String.charAt(String.java:646)
at Numerical.numToImageRep(Numerical.java:28)
at Numerical.main(Numerical.java:9)

我不确定为什么会发生这种情况。如果有人对我有任何建议,我会非常感激。

2 个答案:

答案 0 :(得分:0)

就像@ user2693587所说,问题可能是你在迭代字符串时使用x + 2这一事实。

读取输入的更标准方法是使用string.split(",")并获取需要数字表示的字符数组。

答案 1 :(得分:0)

问题出在声明中:

symbol = read.next();

默认情况下,Scanner类的next()方法仅返回空格之前的内容。所以,当你在行

上调用read.next()时
2, ,5,*

它返回字符串“2”,这显然会导致越界异常。

相反,用

替换该行
symbol = read.nextLine();

它应该解决你的问题。