Java中能否直接将输入转为double数组?求代码简化方案
问题描述
我正在做一个微积分课程项目,要写程序求解任意两条直线或平面的交点。但已经一年没写代码,很多编程知识都忘了,现在这段输入处理的代码重复度很高,想简化一下。目前我让用户输入两条直线的位置向量和方向向量,再一步步转成double数组,想知道有没有更高效的实现方式,比如能不能直接把输入存成double数组?
当前代码如下:
System.out.println("Input the position vector of the first line in the format x,y,z with no spaces."); String posv1 = vscanner.nextLine(); System.out.println("Input the direction vector of the first line in the format x,y,z with no spaces."); String dirv1 = vscanner.nextLine(); System.out.println("Input the position vector of the second line in the format x,y,z with no spaces."); String posv2 = vscanner.nextLine(); System.out.println("Input the direction vector of the second line in the format x,y,z with no spaces."); String dirv2 = vscanner.nextLine(); vscanner.close(); //split all vectors at commas and place in array String[] posv1s = posv1.split(","); String[] dirv1s = dirv1.split(","); String[] posv2s = posv2.split(","); String[] dirv2s = dirv2.split(","); //convert string array to double array double[] posv1d = Arrays.stream(posv1s).mapToDouble(Double::parseDouble).toArray(); double[] dirv1d = Arrays.stream(dirv1s).mapToDouble(Double::parseDouble).toArray(); double[] posv2d = Arrays.stream(posv2s).mapToDouble(Double::parseDouble).toArray(); double[] dirv2d = Arrays.stream(dirv2s).mapToDouble(Double::parseDouble).toArray();
简化方案
核心思路是把重复的「提示输入→读取字符串→拆分转换为double数组」逻辑提取成工具方法,调用方法就能直接得到double数组,彻底消除重复代码。
实现代码
import java.util.Scanner; import java.util.Arrays; public class LineIntersection { public static void main(String[] args) { Scanner vscanner = new Scanner(System.in); // 直接调用工具方法获取目标double数组 double[] posv1d = readVector(vscanner, "Input the position vector of the first line in the format x,y,z with no spaces."); double[] dirv1d = readVector(vscanner, "Input the direction vector of the first line in the format x,y,z with no spaces."); double[] posv2d = readVector(vscanner, "Input the position vector of the second line in the format x,y,z with no spaces."); double[] dirv2d = readVector(vscanner, "Input the direction vector of the second line in the format x,y,z with no spaces."); vscanner.close(); // 后续业务逻辑直接使用这些double数组即可 } // 提取的工具方法:统一处理向量输入,直接返回double数组 private static double[] readVector(Scanner scanner, String prompt) { System.out.println(prompt); String input = scanner.nextLine(); return Arrays.stream(input.split(",")) .mapToDouble(Double::parseDouble) .toArray(); } }
优化点说明
- 彻底消除重复代码,代码结构更简洁,可读性提升明显
- 后续如果需要调整输入逻辑(比如添加格式验证,确保输入是3个有效数字),只需要修改
readVector这一个方法,无需多处改动 - 跳过中间的字符串数组变量,一步到位得到目标double数组,减少代码冗余
内容的提问来源于stack exchange,提问作者Rani
相关产品推荐
相关产品推荐

