Java代码无法调用自定义color方法生成不同深浅红色问题排查
问题原因分析
- 方法传参逻辑断裂:main方法中计算的
a*number值仅调用了color()方法但未将结果传递给递归绘制矩形的rerectangle()方法,而rerectangle()内部调用color()时没有传入任何参数,和你定义的带int入参的color()方法签名不匹配,根本无法正常执行。 - 颜色值越界:RGB色彩通道的合法取值范围是0~255,你当前的
color()方法直接做乘法计算,很容易生成超出255的数值,导致StdDraw颜色设置异常。 - 冗余代码:重复调用了两次
StdDraw.enableDoubleBuffering(),属于无效重复代码。
修复方案
- 给
rerectangle()方法新增一个int类型的入参,用于接收红色通道的计算值 - 在main方法中提前计算好红色基础值,调用
rerectangle()时将该值传入 - 给
color()方法增加边界判断,保证返回值始终在0~255的合法区间内 - 删除重复的双缓冲启用代码
完整修正代码
import java.util.Scanner; public class Pop { public static void main(String[] args) throws java.io.IOException { StdDraw.enableDoubleBuffering(); java.util.Scanner scan = new java.util.Scanner(new java.io.FileReader("numfile.txt")); int a = scan.nextInt(); int b = scan.nextInt(); int c = scan.nextInt(); // 读取用户输入选择颜色深度 Scanner myObj = new Scanner(System.in); System.out.println("Enter a number between 1 and 10"); int number = myObj.nextInt(); System.out.println("The number you selected is " + number + ". Good choice! One moment..."); // 提前计算红色通道基础值 int redBase = color(a * number); // 调用绘制方法时传入红色值 rerectangle(0.0, 0.5, redBase); StdDraw.show(); } // 新增redValue参数接收红色通道值 static void rerectangle(double x, double radius, int redValue) { if (radius > 0.01) { // 直接使用传入的红色值设置笔色 StdDraw.setPenColor(redValue, 0, 0); StdDraw.filledRectangle(0.5, radius, radius, radius); // 递归调用时继续传递红色值 rerectangle(x + radius * 0.2, radius * 0.9, redValue); } } static int color(int color1) { int res = color1 * 2; // 限制颜色值不超出RGB通道合法范围 return Math.min(Math.max(res, 0), 255); } }
内容的提问来源于stack exchange,提问作者C.C.
相关产品推荐
相关产品推荐

