English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

How do I make a text file like numbers.txt and then use it to be read into my program into an integer ArrayList? The text file consists of integers and the number of integers is unknown.
Please answer clearly and in detail.
Thank you

2007-03-21 17:54:57 · 4 answers · asked by π∑∞∫questionqueen 3 in Computers & Internet Programming & Design

4 answers

Here you go:

import java.util.ArrayList;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;

public class Main {

public static void main(String[] args)
{
ArrayList numbersList = new ArrayList();

String line = null;
String fileName = "c:\numbers.txt";
int number = 0;

try
{
BufferedReader inputStream =
new BufferedReader(new FileReader(fileName));

line = inputStream.readLine();
while(line != null)
{
number = Integer.parseInt(line);
numbersList.add(number);
line = inputStream.readLine();
}
}
catch(FileNotFoundException e)
{
System.out.println("File: " + fileName + " was not found " +
"or couldn't be opened");
System.out.println();
}
catch(IOException e)
{
System.out.println("Error reading from file: " + fileName);
System.out.println();
}
}
}

Notes:

1) To create the numbers.txt file use notepad

2) The code is assuming that you saved your numbers.txt file directly in the c drive "c:\numbers.txt". If the file is placed elsewhere, then change the directory of the file.

3) The program is assuming that your numbers.txt file has a single number on each line as follows:

num1
num2
num3

If you have multiple numbers on each line as follows:
num1 num2 num3 num4 ......

the programs becomes a little bit more complicated but i am willing to help, so if you need to know how to do that just ask me to.

I hope this helps!!

2007-03-21 19:00:07 · answer #1 · answered by Silver_Sword 3 · 1 0

There are many ways, but probably the easiest is to create the text file using Notepad. Write in the numbers with a specific character betwen them. The easiest is probably a space character.

Then it depends on which language you are using, but it should be easy to open the file and read in the numbers. The space character will delimit between each number. Make a loop that reads a number and adds it to the array, and then exits when the end of file is reached.

2007-03-22 01:04:52 · answer #2 · answered by Just Helping 4 · 0 0

Use Notepad or Save as Text from other programs
Go here
http://java.sun.com/docs/books/tutorial/essential/io/file.html
and wander through line input.

2007-03-22 01:10:52 · answer #3 · answered by Mike1942f 7 · 0 0

System.out.println(Hi, I don't know the answer);

2007-03-23 20:57:38 · answer #4 · answered by Anonymous · 0 0

fedest.com, questions and answers