把逗号分隔的整数

把逗号分隔的整数

本文介绍了Java的 - 把逗号分隔的整数,从文本文件到一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个基于赋值我工作的一个简单的问题。

我有这样的号码列表中的文本文件:

  5,8,14
7,4,2

和我需要他们插入到一个数组这样

 乔[5] [8] = 14;
乔[7] [4] = 2;

有麻烦这个工作,感谢人谁可以给我一个手。

- 编辑 -

这是code现在我有

 文件f =新的文件(solution.txt);
扫描仪SC =新的扫描仪(F);而(sc.hasNextLine())
{
    如果(sc.hasNextInt())
        X = sc.nextInt();    如果(sc.hasNextInt())
        Y = sc.nextInt();    如果(sc.hasNextInt())
        乔[X] [Y] = sc.nextInt();
}


解决方案

以整条生产线的分割线将使用该方法的String数组拆分举例如下。然后取String数组的每个元素和使用方法的Integer.parseInt()将其转换为 INT 。您code应该是这个样子:

 文件f =新的文件(solution.txt);
扫描仪SC =新的扫描仪(F);而(sc.hasNextLine())
{
    串行= sc.nextLine();
    的String []号= line.split();
    INT X =的Integer.parseInt(数[0]);
    INT Y =的Integer.parseInt(号[1]);
    乔[X] [Y] =的Integer.parseInt(数[2]);
}

Had a quick question based on an assignment I'm working on.

I have a list of numbers like this in a text file:

5, 8, 14
7, 4, 2

And I need them inserted into an array as such

joe[5][8] = 14;
joe[7][4] = 2;

Having trouble getting this done, thanks to anyone who can give me a hand.

-Edit-

This is the code I have now

File f = new File("solution.txt");
Scanner sc = new Scanner(f);

while(sc.hasNextLine())
{
    if(sc.hasNextInt())
        x = sc.nextInt();

    if(sc.hasNextInt())
        y = sc.nextInt();

    if(sc.hasNextInt())
        joe[x][y] = sc.nextInt();
}
解决方案

Take an entire line an split the line into a String array using the method split as exemplified below. Then take each element of the String array and convert it to an int using the method Integer.parseInt( ). Your code should look something like:

File f = new File("solution.txt");
Scanner sc = new Scanner(f);

while(sc.hasNextLine())
{
    String line = sc.nextLine();
    String[] number = line.split(", ");
    int x = Integer.parseInt(number[0]);
    int y = Integer.parseInt(number[1]);
    joe[x][y] = Integer.parseInt(number[2]);
}

这篇关于Java的 - 把逗号分隔的整数,从文本文件到一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 02:03