Read text file and convert rows to Integer arrays [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I try to read text file such this one:
23 0 5 6
28 1 9 5 4 0 3
90 3 6 4 7
-1
I want to read and convert each row individually as integer vector and stop reading when value = -1. I get this code:
importjava.io.FileReader;
importjava.io.IOException;
importjava.util.Scanner;
public class T3 {
public static void main(String[] args) throws IOException {
FileReader file = new FileReader("e:\\test.txt");
int[] integers = new int[100];
int[] I = new int[100];
int i = 0;
try {
Scanner input = new Scanner(file);
while (input.hasNext()) {
integers[i] = input.nextInt();
i++;
}
input.close();
} catch (Exception e) {
e.printStackTrace();
}
for (i = 0; i < 10; i++) {
System.out.println(integers[i]);
}
}
}
But it is useless. Please, I need help.

Modify the while as shown below
Scanner s = new Scanner("file path");
while (s.hasNextLine()) {
//read each line in the file and split the line content on the basis of space
String[] eachLine = s.nextLine().split("\\s+");
}
Once you have the eachLine String array - use it to initialize the Integer vector. Also, following this approach you can avoid the -1 which you are putting explicitly to tell the Scanner the end of line/ file/ input.
Use eachLine.lenght to define the length of each Vector.
For example,
28 1 9 5 4 0 3
90 3 6 4 7
Scanner s = new Scanner("file path");
while (s.hasNextLine()) {
String[] eachLine = s.nextLine().split("\\s+");
//import java.util.Arrays;
System.out.println(Arrays.toString(eachLine));
}

Path path = get("test.txt");
List<int[]> list = new ArrayList<>();
try (BufferedReader reader = newBufferedReader(path)) {
String line;
while ((line = reader.readLine()) != null && !line.contains("-1")) {
if (line.isEmpty()) continue;
String[] strings = line.split(" ");
int[] integers = new int[strings.length];
for (int i = 0; i < strings.length; i++) {
integers[i] = parseInt(strings[i]);
}
list.add(integers);
}
}
Edit:
import static java.nio.file.Files.newBufferedReader;
import static java.lang.Integer.parseInt;
import static java.nio.file.Paths.get;

Lets get you on the right track.
I think the problem with your code is that you assume each next character is an integer. Which is not the case as you have spaces as delimiter.
An approach I would do is read in line by line with the nextLine method. Then use a StringTokenizer to cut all integers apart from eachother by specifying the delimiter (space in your case).
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
public class EgoStroker {
private static final String DELIMITER = " ";
private static final int MINUS_ONE = -1;
private static final String INPUT_FILE_NAME = "input.txt";
public static void main(String[] args) {
// List containing the integers read.
final List<Integer> integers = new ArrayList<>();
FileReader fileReader = null;
try {
fileReader = new FileReader(INPUT_FILE_NAME);
} catch (FileNotFoundException exc) {
exc.printStackTrace();
}
final Scanner scanner = new Scanner(fileReader);
// Boolean that will become false when -1 is encountered and
// is then used to stop the reading process.
boolean cont = true;
while(cont && scanner.hasNextLine()) {
final String line = scanner.nextLine();
final StringTokenizer tokenizer = new StringTokenizer(line, DELIMITER);
while(cont && tokenizer.hasMoreTokens()) {
final int number = Integer.parseInt(tokenizer.nextToken());
if(number == MINUS_ONE) {
cont = false;
} else {
integers.add(number);
}
}
}
int index = 0;
for(int integer : integers) {
++ index;
System.out.println(index + ". " + integer);
}
}
}
You could replace the List with an array but you don't know in advance how many objects you will have at most so its more safe to use a dynamic List.

Related

what wrong with my code always print answer : null+word,what is null?

We have file with a few words, try safe word with word have 2,4,6 or 8 letters in array but then save in screen write null and null+good word.
What did I write wrong, and why does it show null?
public static void lyginis () throws IOException {
Path path = Paths.get("words.txt");
Scanner scanner = new Scanner(path);
int kiek = 0;
while (scanner.hasNext()) {
scanner.next();
kiek++;
}
Scanner scanner1 = new Scanner(path);
String[] atrinkti = new String[kiek];
String scan = "";
for (int i = 0; i < kiek; i++) {
scan = scanner1.next();
if (scan.length() % 2 == 0) {
atrinkti[i] += scan ;
}
System.out.println(atrinkti[i]);
}
}
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Hello {
public static void main(String[] args) throws IOException {
File file = new File("words.txt");
Scanner scanner = new Scanner(file);
int kiek = 0;
while (scanner.hasNext()) {
scanner.next();
kiek++;
}
Scanner scanner2 = new Scanner(file);
String[] atrinkti = new String[kiek];
String word = "";
for (int i = 0; i < kiek; i++) {
word = scanner2.next();
if (word.length() % 2 == 0) {
atrinkti[i] = word;
System.out.println(atrinkti[i]);
}
}
}
}
Output
$ cat words.txt
hi
hello
whats up
chicken
duck
goose
$ javac Hello.java; java Hello
hi
up
duck
The issues were:
Path was used instead of File
The += was used within the if statement instead of just =
The System.out.println() function was called outside of the if statement so when the word's length was not divisible by 2, the current array element would print the default initialized value of the array of null

How to read integers from a text file without using hasNextInt() Java

So I'm new to programming and we have to do this lab where we read from a text file that has only one line with numbers. We then have to put those integers into an array. I know how to read the numbers when they are in separate lines but not when they are in one line. I also know how to put numbers into an array, so I don't need help with that.
The only methods we are allowed to use are:
hasMoreTokens()
hasMoreLines()
readDouble()
readInt()
readLine()
readToken()
Is there a way to do such while using only these methods?
Here is the code:
import chn.util.FileInput;
import chn.util.FileOutput;
public class Compact {
public Compact (FileInput inFile, FileOutput outFile){
int[] compactArray = new int [21];
int numZeroes = 0;
int num;
int length = compactArray.length;
for (int i = 0; i < length; i++) { //making the array for the integers in the list
compactArray[i] = 0;
}
while (inFile.hasMoreLines()) {
num = 0;
num = inFile.readInt(); //reads the integers per line
compactArray[num]++;
}
for(int i = 0; i < length; i++) {
if(compactArray[i] == 0) {
length--;
for(int j = i; j < length; j++) {
compactArray[j] = compactArray[j+1];
}
i--; // Decrement i to check the value that was shifted
} else {
numZeroes++;
}
}
// now print the array without 0
for(int i = 0; i < numZeroes; i++) {
outFile.print(" " + compactArray[i]);
}
outFile.close();
}
For some reason it's simply returning a string of zeroes. I was thinking it may have to do with the way I read the code.
Input: numbers_line.txt which has one line:
1 8 3 43 4 56
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
public class ReadIntFromFile {
public static void main(String []args){
String fileName = "numbers_line.txt";
List<String> numbersArrayList = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) {
numbersArrayList = Arrays.asList(line.split(" "));
}
} catch (IOException e) {
e.printStackTrace();
}
String[] numbersStringArray = new String[numbersArrayList.size()];
numbersStringArray = numbersArrayList.toArray(numbersStringArray);
int[] numbersIntArray = new int[numbersStringArray.length];
for(int i = 0;i < numbersStringArray.length;i++) {
numbersIntArray[i] = Integer.parseInt(numbersStringArray[i]);
}
for(int x : numbersIntArray)
System.out.println(x);
}
}
Output:
1
8
3
43
4
56

How can I print my array in a certain way? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
So I'm wanting to print my arrays in a list. That will look like this.
Word: Count:
Myths 2
Of 15
Babylonia 25
I can't seem to figure out how to print it the correct way, here is the code I have so far. Any help is appreciated, thanks!
package program6;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
public class Program6 {
static String[] stringArray = new String[100];
static int[] intArray = new int[100];
static String fileName = "myths.txt";
static int currentWordIndex = 0;
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File(fileName));
while (input.hasNext()){
String word = input.next();
boolean alreadyExists = false;
for (int i = 0; i < currentWordIndex; i++) {
if(stringArray[i].equals(word)){
alreadyExists = true;
intArray[i]++;
break;
}
}
if(!alreadyExists && currentWordIndex <100){
stringArray[currentWordIndex] = word;
intArray[currentWordIndex++] = 1;
}
}
System.out.println("Myths of Babylonia and Assyria");
System.out.println("Word: Count:");
System.out.println(Arrays.toString(stringArray));
System.out.println();
System.out.println(Arrays.toString(intArray));
}
}
Use a format and use a loop
System.out.println("Myths of Babylonia and Assyria");
System.out.println("Word:\t\tCount:");
for (int i = 0; i < stringArray.lengthl i++){
System.out.printf("%s\t\t%d\n", stringArray[i], intArray[i]);
}
Edit with right aligntment
System.out.println("Myths of Babylonia and Assyria");
System.out.printf("%10s%10s\n", "Word", "Count");
for (int i = 0; i < array1.length; i++) {
System.out.printf("%10s%10d", array1[i], array2[i]);
System.out.println();
}
Edit: Using a method for other books
public static void main(String[] args) throws FileNotFoundException{
printCounts("myth.txt", "Babylonia and Assyria");
System.out.println();
printCounts("someOther.txt", "Some Other Title");
System.out.println();
printCounts("another.txt", "Another Title");
System.out.println();
}
public static void printCounts(String filename, String title) throws FileNotFoundException {
String[] stringArray = new String[100];
int[] intArray = new int[100];
int currentWordIndex = 0;
Scanner input = new Scanner(new File(filename));
while (input.hasNext()) {
String word = input.next();
boolean alreadyExists = false;
for (int i = 0; i < currentWordIndex; i++) {
if (stringArray[i].equals(word)) {
alreadyExists = true;
intArray[i]++;
break;
}
}
if (!alreadyExists && currentWordIndex < 100) {
stringArray[currentWordIndex] = word;
intArray[currentWordIndex++] = 1;
}
}
System.out.println(title);
System.out.printf("%10s%10s\n", "Word", "Count");
for (int i = 0; i < stringArray.length; i++) {
System.out.printf("%10s%10d", stringArray[i], intArray[i]);
System.out.println();
}
}
When you are doing
System.out.println();
it is actually printing a new line at the end of your output.
Try using
System.out.print("foo ");
System.out.println("bar");
Have look at this page which explains the use of System.printf to align columns.
System.out.printf( "%-15s %15s %n", heading1, heading2);
Your arrays have 100 elements, so lots of Zeros get printed, use Arrays.copyOf to create smaller arrays.
For table format, use printf.
So you should replace the following code:
System.out.println("Word: Count:");
System.out.println(Arrays.toString(stringArray));
System.out.println();
System.out.println(Arrays.toString(intArray));
with:
String[] stringArray2 = Arrays.copyOf(stringArray, totalWordCount);
int[] intArray2 = Arrays.copyOf(intArray, totalWordCount);
stringArray = null;
intArray = null;
System.out.println("Myths of Babylonia and Assyria");
System.out.printf("\n%15s%15s", "Word:","Count:");
for (int i = 0; i < stringArray2.length; i++){
System.out.printf("\n%15s%15d", stringArray2[i], intArray2[i]);
}
You have to right justify your columns. According to this stackoverflow question, columns left justified with a negative sign in front of them and right justfified without. You want your print statement to look something like this:
System.out.printf("%60s %3d", stringArray[i], intarray[i]));
You can vary the column width this way.
In addition: Someone mentioned you can avoid printing a line at the end of each statement by using print instead of println.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Program6 {
static String fileName = "myths.txt";
private static Scanner input;
public static void main(String[] args) throws FileNotFoundException {
input = new Scanner(new File(fileName));
Map<String, Integer> map = new HashMap<String, Integer>();
while (input.hasNext()){
String word = input.next();
if ( map.containsKey(word) ){
int temp = map.get(word) + 1;
map.put(word, temp);
} else {
map.put(word, 1);
}
}
// get all the set of keys
Set<String> keys = map.keySet();
// iterate through the key set and display key and values
System.out.printf("%-10s\t\t%s\n", "Word", "Count:");
for (String key : keys) {
System.out.printf("%-10s\t\t%d\n", key, map.get(key));
}
}
}

How to input relation into two dimensional array?

I have a problem in my project math.
My project is to write a program that reads a set of elements and its relations. Your input data will be from a text file. (SetRelation).
{1,2,3} {(1,1),(2,2),(3,3),(1,2),(1,3),(2,3)}
I have no problem reading the text file into the program but I'm stuck when I want to try to put the relation into the two dimensional array.
For example: {(1,1),(2,2),(3,3),(1,2),(1,3),(2,3)}
The two dimensional array would have to be like this:
col[0][1][2]
[0] 1 1 1
[1] 1 1
[2] 1
I don't know how to set one into two dimensional array because there are various relations in the text file.
This is my coding.
import javax.swing.*;
import java.util.ArrayList;
import java.io.*;
import java.util.StringTokenizer;
import java.lang.*;
import java.util.*;
public class tests
{
public static int s1[][];
public static int s2[][];
public static int s3[][];
public static int s4[][];
public static int s5[][];
public static int s6[][];
public static int s7[][];
public static int s8[][];
public static int s9[][];
public static int s10[][];
public static void main(String[] args) throws IOException, FileNotFoundException
{
BufferedReader infile = null;
ArrayList arr1 = new ArrayList();
ArrayList arr2 = new ArrayList();
ArrayList arr3 = new ArrayList();
ArrayList arr4 = new ArrayList();
try
{
infile = new BufferedReader (new FileReader ("numbers.txt"));
String indata = null;
while ((indata = infile.readLine())!= null)
{
StringTokenizer st = new StringTokenizer(indata," ");
String set = st.nextToken();
arr1.add(set);
String relation = st.nextToken();
arr2.add(relation);
}
for(int i =0; i < arr2.size(); i++)
{
String r = arr2.get(i).toString();
String result = r.replaceAll("[{}(),; ]", "");
arr3.add(result);
}
for(int i = 0; i < arr3.size(); i++)
{
System.out.println(arr3.get(i).toString());
}
for(int i =0; i < arr1.size(); i++)
{
String s = arr1.get(i).toString();
String result = s.replaceAll("[{}(),; ]", "");
arr4.add(result);
}
int set1 = Integer.parseInt(arr4.get(0).toString());
String ss1 = arr4.get(0).toString();
int a = ss1.length();
s1 = new int[a][a];
int sA[][];
/*for(int row=1;row< a;row++)
{
for(int col=0;col < a;col++)
{
sA = new int[row][col];
int firstNo = Integer.parseInt(arr3.get(row).toString());
int secondNo = Integer.parseInt(arr3.get(col).toString());
sA = new int [firstNo][ secondNo] ;
System.out.print(sA);
}
System.out.println();
}*/
char arrA;
char indOdd=' ',indEven=' ';
char[] cArr = arr3.get(0).toString().toCharArray();
//System.out.println(arr3.get(0).toString().length());
int l = arr3.get(0).toString().length();
int arr10[][] = new int[(l/2)][2];
for(int i=0;i< 2;i++)
{
for(int row = 0; row < (l/2);row++)
{
for(int gh = 0;gh < l;gh++)
{
if(i%2==0)
{
indEven = cArr[gh];
System.out.println(indEven);
arr10[row][i] = indEven;
//System.out.println(arr10[row][i]);
//row++;
}
else
{
indOdd = cArr[gh+1];
System.out.println(indOdd);
arr10[row][i] = indOdd;
//row++;
}
}
}
//arr10 = new int[indOdd][indEven];
//System.out.println(arr10);
}
}
catch (FileNotFoundException fnfe)
{
System.out.println("File not found");
}
catch (IOException ioe)
{
System.out.println(ioe.getMessage());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
infile.close();
}
}
But I'm stuck how to set one into the two dimensional array if the relation is {(a,b),(a,c),(b,a),(b,c),(c,c)}; and {(33,33),(45,45),(67,67),(77,77),(78,78)};
So, you have two problems: parsing the input and setting the array.
To parse the input, think about the format you're given. An opening curly brace, a bunch of ordered pairs, then a closing brace. Think about this pseudocode:
Read in a left curly brace
While the next character is not a right curly brace{
Read in a left parenthesis
Get the first number and put it in a variable!
Read in a comma
Get the second number and put it in a variable!
Read in a right parenthesis
Store your relation in the array!
}
Now your issue is just how to put it in the array. Your relations are practically already indexes into the grid! Note the 0-indexing, so just subtract 1 from both, and set the resulting coordinate equal to 1.
array[first number-1][second number-1]=1;
Just a TIP:
If your set is for example {b,c,e} and want to have somewhere stored relation elemnt <-> index like b<==>0, c<==>1, e<==>2 you can store that elements in List and then use method indexOf().
I mean something like this
List<String> list=new ArrayList<String>();
list.add("b");
list.add("c");
list.add("e");
System.out.println(list.indexOf("c"));//return 1
System.out.println(list.indexOf("e"));//return 2
System.out.println(list.indexOf("b"));//return 0
Now you just have to figure out how to use it to create your array.

Array Absurdity Challenge [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
So, I have been working on the following codeeval challenge problem.
Array Absurdity
Description:
Imagine we have an immutable array of size N which we know to be filled with integers ranging from 0 to N-2, inclusive. Suppose we know that the array contains exactly one duplicated entry and that duplicate appears exactly twice. Find the duplicated entry. (For bonus points, ensure your solution has constant space and time proportional to N)
Input sample:
Your program should accept as its first argument a path to a filename. Each line in this file is one test case. Ignore all empty lines. Each line begins with a positive integer(N) i.e. the size of the array, then a semicolon followed by a comma separated list of positive numbers ranging from 0 to N-2, inclusive. i.e eg.
5;0,1,2,3,0
20;0,1,10,3,2,4,5,7,6,8,11,9,15,12,13,4,16,18,17,14
Output sample:
Print out the duplicated entry, each one on a new line eg
0
4
Submit your solution in a file (some file name).(py| c| cpp| rb| pl| php| tcl| clj| js) | array_absurdity.java or use the online editor.
I find it rather easy. I coded it, tested it with various test cases on my computer and it seems to be working fine. But when I submit the problem on codeveal i keep getting a 0. I have thought of all possible test cases but idk why it keeps failing. I would appreciate if you guys could give some ideas. The following solution I coded is in java.
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Scanner;
public class array_absurdity {
public static int findDuplicate(int [] arr){
int sumAll = 0;
int sumEle = sumElements(arr.length-2);
for(int i = 0; i < arr.length; i++){
sumAll += arr[i];
}
if(sumAll < sumEle)
return 0;
else
return (sumAll - sumEle);
}
public static int sumElements (int length){
/*
if(length == 0)
return 0;
else
return length + sumElements(length - 1);
*/
return length* (length + 1)/2;
}
static String[][] readNumbers (String fileName)
{
String [][] arr;
try {
LinkedList<String> stringList = new LinkedList<String>();
Scanner scanner = new Scanner (new FileReader (fileName));
while(scanner.hasNext()){
String input = scanner.next();
stringList.add(input);
}
Iterator<String> iter = stringList.iterator();
arr = new String [stringList.size()][];
int i = 0;
while(iter.hasNext()){
arr[i] = new String[2];
try{
arr[i] = iter.next().split(";");
}
catch (Exception e){
System.out.println (e);
System.exit (0);
}
i++;
}
// Done.
return arr;
}
catch (IOException e) {
System.out.println (e);
System.exit (0);
return null;
}
catch( ArrayIndexOutOfBoundsException e ) {
System.out.println (e);
System.exit (0);
return null;
}
}
public static void main (String[] argv){
int [] iArr;
String [] ele;
Scanner sc = new Scanner(System.in);
String filename = sc.nextLine();
String [][] arr = readNumbers (filename);
int size = 0;
for(int i = 0; i< arr.length; i++){
try{
ele = arr[i][1].split(",");
size = Integer.parseInt(arr[i][0]);
iArr = new int[ele.length];
if(size == iArr.length){
int duplicate = 0;
for (int j=0; j < ele.length; j++) {
iArr[j] = Integer.parseInt(ele[j]);
duplicate = findDuplicate(iArr);
}
System.out.println(duplicate);
}
}
catch( ArrayIndexOutOfBoundsException e ) {
System.out.println (e);
System.exit (0);
}
catch (Exception e) {
System.out.println (e);
System.exit (0);
}
}
System.exit(0);
}
}
A shorter version in Java.
public static void main(String... args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(args[0]));
for (String line; ((line = br.readLine()) != null); ) {
String[] parts = line.split(";")[1].split(",");
int num = (parts.length - 2) * (parts.length - 1) / 2;
for (String part : parts) num -= Integer.parseInt(part);
System.out.println(-num);
}
}
Your program should accept as its first argument a path to a filename.
Your program looks like it reads the filename from System.in instead of from the command line. It does nothing with the command-line arguments.
I haven't looked carefully at the rest of the code, but this seems to be something that might disqualify it even if the logic of the primary problem is correct.
Here's a basic way to do it in perl.
#!/usr/bin/perl -w
use strict;
open FILE, $ARGV[0] or die $!;
local $| = 1;
local $, = '';
while (<FILE>) {
$_ =~ /(\d+);(.*)/;
my $len = $1;
my #nums = sort split /,/, $2;
for(0 .. $len) {
print $nums[$_], "\n" and last if $nums[$_] == $nums[$_ + 1];
}
}

Categories

Resources