How to read integer values from text file [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java: Reading integers from a file into an array
I want to read integer values from a text file say contactids.txt. in the file i have values like
12345
3456778
234234234
34234324234
i Want to read them from a text file...please help

You might want to do something like this (if you're using java 5 and more)
Scanner scanner = new Scanner(new File("tall.txt"));
int [] tall = new int [100];
int i = 0;
while(scanner.hasNextInt())
{
tall[i++] = scanner.nextInt();
}
Via Julian Grenier from Reading Integers From A File In An Array

You can use a Scanner and its nextInt() method.
Scanner also has nextLong() for larger integers, if needed.

Try this:-
File file = new File("contactids.txt");
Scanner scanner = new Scanner(file);
while(scanner.hasNextLong())
{
// Read values here like long input = scanner.nextLong();
}

How large are the values? Java 6 has Scanner class that can read anything from int (32 bit), long (64-bit) to BigInteger (arbitrary big integer).
For Java 5 or 4, Scanner is there, but no support for BigInteger. You have to read line by line (with readLine of Scanner class) and create BigInteger object from the String.

use FileInputStream's readLine() method to read and parse the returned String to int using Integer.parseInt() method.

I would use nearly the same way but with list as buffer for read integers:
static Object[] readFile(String fileName) {
Scanner scanner = new Scanner(new File(fileName));
List<Integer> tall = new ArrayList<Integer>();
while (scanner.hasNextInt()) {
tall.add(scanner.nextInt());
}
return tall.toArray();
}

Related

Java - program skips Scanner(System.in) [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
public static char[] puzzleInput() {
printEnterPuzzleMessage();
Scanner puzzleS = new Scanner(System.in);
if(puzzleS.hasNext()) {
char[] puzzle = puzzleS.next().toCharArray();
while(!isLegalPuzzleStructure(puzzle)) {
printIllegalPuzzleMessage();
puzzleInput();
}
return puzzle;
}
puzzleS.close();
return null;
}
public static void main(String[] args) throws Exception{ //Q - 8
Scanner fileName = new Scanner(System.in);
if(!fileName.hasNext()) {
System.out.println("No argument has been received");
System.exit(0);
}
String filePath = fileName.nextLine();
fileName.close();
Scanner vocabulary = new Scanner(new File(filePath));
String[] vocabularyArr = scanVocabulary(vocabulary);
vocabulary.close();
printReadVocabulary(filePath, vocabularyArr.length);
printSettingsMessage();
printEnterPuzzleMessage();
char[] puzzle = puzzleInput();
Hi, a beginner in Java is here.
In the function puzzleInput, I open a Scanner to get an input from the user. For some reason, the program won't give me a chance to put in input, and therefor the argument (puzzle) gets a null as default, and later when puzzle is needed not as a null - throws a NullPointerException.
There are many other functions in the code, but most of them are just a print commands, and the ones who are not were being checked by me, and are OK.
The problem is just the scanner won't give me a chance to put in an input.
Some points I'd like to clarify further:
1. The first Scanner (fileName) is not being skipped by the program, and I'm able to give it an argument.
2. I made sure I closed all the other scanners i've opened before.
Can someone explain me what I'm doing wrong?
program won't give me a chance to put in input
Your problem is that you are closing your Scanner in main:
Scanner fileName = new Scanner(System.in);
...
fileName.close();
This in turn closes the System.in input-stream which then cannot be reused in your puzzleInput() method because it is already closed. The right thing to do here is to pass in the Scanner variable into your puzzleInput() method and continue to reuse it there and not try to open up a new Scanner.
public static char[] puzzleInput(Scanner scanner) {
printEnterPuzzleMessage();
if(scanner.hasNext()) {
...
// don't close it here
return null;
}
...
Scanner scanner = new Scanner(System.in);
...
puzzleInput(scanner);
Couple of other comments:
Calling a Scanner fileName is not a good pattern. Choosing good names for your variables will help make the code self-documenting. scanner would be a better name of course.
When dealing with any input/output, it is a good practice to wrap any opening method in a try/finally block so it gets close properly. See also the try-with-resources functionality added in Java 7.
If you want a chance to do something with the input with a prompt, why not assign it to a String variable? This allows you to manipulate the input however you want later on too.
String input = scannerName.nextLine();

How can I determine what I read from a file? Java

So I want to read a file, that contains numbers separated by spaces. For example, the file "try.txt" content is:
1 2 3
4 5 6
7 8 9
I know how to read this numbers and store them in an array with a Scanner, and two nested for loops.Ignore any possible sintax errors here. It would look like:
int i,j;
Scanner sc
for(i=0;i<array.length;i++){
for(j=0;j<array[i].length;j++){
array[i][j]=sc.nextInt();
}
}
So my question is, how can I check that what I am reading is actually an integer? What happens if nextInt() finds a letter, or another ASCII symbol?
Thank you.
Try this code
if (obj instanceof Integer)
{
// is a integer
}
else
{
// is not
}
At the end, I solved this problem using InputMissmatchException. Here is an example:
Scanner sc = new Scanner(System.in);
try{
int a = sc.nextInt();
}catch(java.util.InputMismatchException e) {
System.out.println("Invalid file content");
}

taking multiple inputs in a specific format as a single input in java [duplicate]

This question already has answers here:
Is there an equivalent method to C's scanf in Java?
(7 answers)
Closed 5 years ago.
I have been using the scanner so far for taking inputs in java but what i need for this particular task is setting values for 4 variables with a single line input i.e. 07:05:45PM
The C equivalent solution for this particular solution is as follows:
scanf("%d:%d:%d%s", &hh, &mm, &ss, t12) ;
I am looking for the java equivalent of this code.
You could use a Scanner instance by setting to it a delimiter such as "\\s*:\\s*".
It could give this code :
Scanner s = new Scanner("07:05:45PM").useDelimiter("\\s*:\\s*");
int hours = s.nextInt();
int minutes = s.nextInt();
String secondAndMeridiem = s.next();
int seconds = Integer.valueOf(secondAndMeridiem.substring(0, 2));
String meridiem = secondAndMeridiem.substring(2, 4);
You can try delimiter option in scanner, but it will not support multiple delimiters together. So it will not support your requirement of ""%d:%d:%d%s"" fully.
Please have a look at
How to read comma separated integer inputs in java
Just curious to know, why don't you look at the SimpleDateFormatter to parse the single string and get hour, minutes, seconds
The closest I could get is this but this would work only if there was some delimiter between 45 and PM in 07:05:45PM like 07:05:45 PM. Otherwise, the input needs to be taken as String and parsed.
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int hh, mm, ss;
String t12;
scanner.useDelimiter("[:\n ]");
hh = scanner.nextInt();
mm = scanner.nextInt();
ss = scanner.nextInt();
t12 = scanner.next();
System.out.println(hh);
System.out.println(mm);
System.out.println(ss);
System.out.println(t12);
}

Arrays: inputing data

this method is suppose to ask the user for the file name that is already created that contains list of numbers, if file does not exist i have to let the user know. im having trouble figuring out how to assign the numbers in the file to a new array?
public static int[] inputData() throws IOException
{
int count = 0;
System.out.print("enter input filename: ");
File myFile = new File("input.txt");
if(!myFile.exists())
{
System.out.print("file does not exist ");
System.exit(0);
}
Scanner inputFile = new Scanner(myFile);
while(inputFile.hasNext() && count < ARRAY_SIZE)
{
array[count++] = input.nextInt();
}
return array[];
}
You need to learn how to declare and allocate a new array, which you'll pass back. It looks like it'll be an array of int, and you'll make it a certain size (is ARRAY_SIZE defined somewhere already?) when you call new. See the official tutorial on arrays.
(As a note, it's usually a bad idea to use an external upper limit in a for loop over an array. The array comes with a built-in length you can use that will always be the correct size.)
Where are you defining the variable array?
your problem is going to be that you don't know how big you need the array to be. The best option is to use an ArrayList as this allows dynamic sizing. (As a result it needs to be a list of Integers rather than ints)
public static Integer[] inputData() throws IOException
{
List<Integer> fileData = new ArrayList<Integer>();
int count = 0;
System.out.print("enter input filename: ");
File myFile = new File("input.txt");
if(!myFile.exists())
{
System.out.print("file does not exist ");
System.exit(0);
}
Scanner inputFile = new Scanner(myFile);
while(inputFile.hasNext())
{
fileData.add(inputFile.nextInt());
}
return fileData.toArray(new Integer[fileData.size()]);
}

Scanner wont work [duplicate]

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 9 years ago.
I have problem with Scanner
When I run the program it skips this one after
System.out.println("name");
n1=s.nextLine();
This is the program "CEmploye " is a class
package Ex5_2;
import java.util.*;
public class XXXX {
public static void main(String[] args) {
int input;
int c1 ;
String n1;
Date d1 = null;
float p1;
float [] t = new float[3];
System.out.println("give nb of emp");
Scanner s = new Scanner(System.in);
input=s.nextInt();
Vector v = new Vector(input);
for(int i=0 ;i <input;i++)
{
System.out.println("cin");
c1=s.nextInt();
System.out.println("name");
n1=s.nextLine();
System.out.println("price");
p1=s.nextFloat();
for(int k=0 ; k<3;k++)
{
System.out.println("nb of hour");
CEmploye.tab[k]=s.nextFloat();
}
CEmploye emp = new CEmploye(c1,n1,d1,p1);
emp.CalculSalaire();
System.out.println(emp.salaire);
}
}
}
Can anyone give me solution ?
System.in's buffer isn't flushed until it gets a newline. So you can't use nextInt() or nextFloat() because they block until a newline.
You'll need to read everything on a line by itself then parse it (with some validation as needed):
cl = Integer.parseInt(s.nextLine());
and
pl = Float.parseFloat(s.nextLine());
and
CEmploye.tab[k]=Float.parseFloat(s.nextLine());
You can't use n1=s.nextLine(); with n1=s.nextInt(). Use n1=s.next();
nextInt() only reads the next integer available and leaves a newline character in the inputstream.
Your s.nextLine() then gets consumed thus not prompting for additional inputs.
Simply add another nextLine() to read more lines
c1=s.nextInt();
This just reads the integer value not the end of line. So when you do
n1=s.nextLine();
it just reads the end of line that you provided by pressing the enter while providing the integer input for the previous variable (c1) and thus seems like it skipped the input. (If you put an integer and some string in the same line when taking c1 input, you will get values for c1 and n1 both. You can check the same)
In order to fix it, either put nextLine() input after each nextInt(). Hope it helps.

Categories