我正在编写一个程序,以接收包含三个不同字符的50 x 50块的文本文件的输入:#,*和/,并根据每个符号为输出PNG文件的每个像素着色,以便有一个与每个字符相关的颜色。
但是,我在第43行看到“字符串索引超出范围:2500”的错误。
我知道虽然正在读取的文本文件正好有50行,每行50个字符,这意味着总共有2500个项目,那么问题是什么呢?帮助将不胜感激。
这是我的代码:
import java.util.Scanner;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
public class Lab_Week8_ImgFrmTxtFINAL {
public static void main(String[] args) throws Exception {
int image_width = 50;
int image_height = 50;
String output_file_path = ("image.png");
String input_file_path = "superimage.txt";
int r = 0;
int g = 0;
int b = 0;
int a = 255;
Scanner reader = new Scanner (new FileInputStream(input_file_path));
int i = 0;
int x = 0;
int y = 0;
if(image_width <= 0 || image_height <= 0) {
System.err.println("Width and Height have to be strictly positive!");
}
if(x < 0 || y < 0) {
System.err.println("Coordinates (x, y) cannot be negative numbers!");
}
if(r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) {
System.err.println("Colour values (r, g, b) have to be between 0 and 255!");
}
BufferedImage image = new BufferedImage (image_width, image_height, BufferedImage.TYPE_INT_ARGB);
while (reader.hasNextLine()){
char c = reader.next().charAt(i);
for (i = 0; i < image_width * image_height; i++)
{
int p = (a << 24) | (r << 16) | (g << 8) | b;
for (x = 0; x < image_width; x++)
{
for (y = 0; y < image_height; y++){
if (c == ('#'))
{p = (a << 24) | (r << 16) | (g << 8) | b;
image.setRGB(x, y, p);
}
else if (c == ('/'))
{p = (a << 0) | (r << 16) | (g << 8) | b;
image.setRGB(x , y , p);
}
else if (c == ('*'))
{p = (a << 8) | (r << 16) | (g << 24) | b;
image.setRGB(x , y , p);
}
}
x += 1;
}
y += 1;
x = 0;
}
}
File f = new File (output_file_path);
ImageIO.write(image, "png", f);
reader.close();
}
}
更换
while (reader.hasNextLine()) 与
while (i < image_width * image_height && reader.hasNextLine()) 您的代码的问题在于,当时i = image_width * image_height,for循环停止,但while循环仍继续并尝试执行char c = reader.next().charAt(i);cause String index is out of range: 2500。
更新:基于讨论的注释/聊天,您需要如下更改代码:
while (reader.hasNextLine()) {
for (i = 0; i < image_width * image_height ; i++) {
int p = (a << 24) | (r << 16) | (g << 8) | b;
for (x = 0; x < image_width && reader.hasNext(); x++) {
char c = reader.next().charAt(i);
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。