【问题标题】:How to consider the newline character(\n) as a delimeter in the file input in Java?如何将换行符(\n)视为Java文件输入中的分隔符?
【发布时间】:2021-05-13 16:31:14
【问题描述】:

我有一个包含以下内容的文本(比如 test.txt)文件

1

2,3

基本上可以认为是"1\n2,3"。我正在编写一个简单的 Java 代码,它读取这个输入并且应该将输出作为 6(提取的 3 个数字的总和)。

这里存在一些问题,因为它无法忽略分隔符。它自己停止在那里接受输入。

public static void main(String[] args) throws IOException{
  File f=new File("./test.txt");
  Scanner sc=new Scanner(f);
  sc.useDelimiter("\n");
  
  String input=sc.next();
  int result=Add(input);
  System.out.println(result);}

在我的 Add() 函数中,我使用了正则表达式来考虑 \n 和 ","。代码如下:

public static int Add(String numbers){
  if(numbers.length()==0)
  {
    return 0;
  }
  if(numbers.length()==1)
  {
    int num=Integer.parseInt(numbers);
    return num;
  }
  // 1,2,3\n4
  String[] nums=numbers.split("\\n|,");
  int sum=0;
  for(int i=0;i<nums.length;i++)
  {
      int num1=Integer.parseInt(nums[i]);
      sum+=num1;
  } 
  return sum;}

但是,我得到的答案不是 6,而是 1。我在哪里失败了?

【问题讨论】:

  • 您只是从扫描仪读取第一个值。该值为“1”。
  • 为什么要使用next()'\n' 分隔符,而您可以只使用nextLine()

标签: java delimiter


【解决方案1】:

试试这个:

sc.useDelimiter(Pattern.compile("[\\r\\n,]+"));

您只需要 sc.next() 即可获取所有值(无需稍后在代码中使用 numbers.split()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    相关资源
    最近更新 更多