Using Buffered Reader to add user input to an array - java

I use a buffered reader to read in the input and then it adds it to an array. But for some reason it only adds the last input to the array. I also want to check if the first input is zero... so thats what I am doing with the check variable. But the main problem is that it doesn't add it to the array.
public static void main (String[] Args) throws IOException
{
int[] numbers = new int[100];
Scanner scan = new Scanner(System.in);
InputStreamReader isReader = new InputStreamReader(System.in);
BufferedReader bReader;
bReader = new BufferedReader(isReader);
int intNumber = Integer.parseInt(bReader.readLine());
int check = scan.nextInt();
while (check != 0)
{
int i = 0;
numbers[i] = Integer.parseInt(bReader.readLine());
check = intNumber;
i++;
}
bReader.close();
}

move int i = 0 outside of while loop. In each iteration i is getting initialized to 0 so your array is having only one value and that is in 0th index

Related

Reading data from file without manually inputing the length it the array

Please I will like to adjust this code that reads integers from a file.
I will like the code to detect the number (n) of the dataset instead of having to put in figures manually as done below (4000 )
double[] tall = new double[4000];
public class Extracto {
public static void main(String[] args) throws IOException {
File fil = new File("C:\\Users\\Desktop\\kaycee2.csv");
FileReader inputFil = new FileReader(fil);
BufferedReader in = new BufferedReader(inputFil);
double[] tall = new double[4000];
String s = in.readLine();
int i = 0;
while (s != null) {
// Skip empty lines.
s = s.trim();
if (s.length() == 0) {
continue;
}
tall[i] = Double.parseDouble(s); // This is line 19.
// System.out.println(tall[i]);
s = in.readLine();
i++;
}
I am expecting the adjusted code to obtain the data length without manually putting it in like in as shown in the code below for the 4000 length.
double[] tall = new double[4000];
As Thomas mentioned, use a list, instead of an array.
File fil = new File("C:\\Users\\Desktop\\kaycee2.csv");
FileReader inputFil = new FileReader(fil);
BufferedReader in = new BufferedReader(inputFil);
ArrayList<Double> tall = new ArrayList<>();
while(in.ready()){
String s = in.readLine().trim();
if(!s.isEmpty()){
tall.add(Double.parseDouble(s);
}
}
your codes can be further compacted if you use a list.
also do add a try-catch in the event when the String read is not a number.

How can I read only one thing in from a textfile?

I can read in from the file and am able to change the amount of lines given by changing the number in the for loop but I don't want all the numbers in my file displayed side by side like that. I need them all going down one by one randomly.
public class Assignment2 {
public static void main(String[] args) throws IOException
{
// Read in the file into a list of strings
BufferedReader reader = new BufferedReader(new FileReader("textfile.txt"));
List<String> lines = new ArrayList<String>();
String line = reader.readLine();
while( line != null ) {
lines.add(line);
line = reader.readLine();
}
// Choose a random one from the list
Random r = new Random();
for (int p = 0; p<3; p++)
{
String randomString = lines.get(r.nextInt(2));
System.out.println(lines);
}
}
}
I think what you want to print is
String randomString = lines.get(r.nextInt(2));
System.out.println(randomString);
To display only the first 20 random lines from this list of maybe 100
for (int i = 0; i < 20; i++) {
int rowNum = r.nextInt(lines.size ());
System.out.println(lines.get(rowNum);
}

Java Sort Data From A File Using Arrays

I have to write a method that reads the file integers.txt and return an array of integers. I have to convert each line of data from text to an integer.
However, I cannot figure out why I am getting an error when I try to assign the array x to the integers within the file and when I convert the data to integers. I am also getting an error with my return statement.
public static int[] processFile (String filename) throws IOException, FileNotFoundException {
double number;
double average;
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream("integers.txt")));
String line;
while ((line = inputReader.readLine()) != null) {
number = Int.parseInt(line);
int[] x = (number);
inputReader.close();
}
return int[] x;
}
There are multiple issues with your code:
You are using return int[] x; instead of simply return x;
x is only assigned inside the while, so you can't return it outside
x = (number); isn't a correct method for adding a value to the array
The int[] x; is never initialized
You use double number at the top of the method, but then assign it with an int here: number = Int.parseInt(line);
My suggestions is to use this instead, which will give an ArrayList<int> as output.
public static ArrayList<Integer> processFile (String filename) throws IOException, FileNotFoundException
{
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream("integers.txt")));
String line;
ArrayList<Integer> list = new ArrayList<>();
while ((line = inputReader.readLine()) != null) {
int number = Int.parseInt(line);
list.add(number);
}
inputReader.close();
return list;
}
If you really need an int[] instead, you'll have to give it a size first like this: int[] x = new int[size_here]; For example:
public static int[] processFile (String filename) throws IOException, FileNotFoundException
{
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream("integers.txt")));
String line;
int[] array = new int[100]; // Example size of 100
int index = 0;
while ((line = inputReader.readLine()) != null) {
int number = Int.parseInt(line);
array[index++] = number;
}
inputReader.close();
return array;
}
And if you need an int[] instead, AND don't know the size beforehand, try this instead:
public static int[] processFile (String filename) throws IOException, FileNotFoundException
{
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream("integers.txt")));
String line;
ArrayList<Integer> list = new ArrayList<>();
while ((line = inputReader.readLine()) != null) {
int number = Int.parseInt(line);
list.add(number);
}
inputReader.close();
return convertIntegers(list);
}
public static int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
Iterator<Integer> iterator = integers.iterator();
for (int i = 0; i < ret.length; i++)
{
ret[i] = iterator.next().intValue();
}
return ret;
}
Firstly it's Integer.parseInt()
number = Int.parseInt(line);
int[] x = (number);
number will contain a single int not an array of ints. so this int[] x = (number); assignment is wrong.
return int[] x; this is also invalid syntax.
There are a few problems here. To answer your question, you can't assign an int to an int array. Next, unless you entered your code incorrectly, you are closing the inputReader inside the while loop that is doing the reading. Also, you are returning int[] x. That is wrong. Return x.

random generator returning multiple results

The code reads from text file and goes true all 1000 words in txt. It then read each word calculate ist lenght and from that lenght gets random number (say lenght is 4 and random would be 2). It then replaces that random numbers character with "*". This would be later used as an sample into main program.
Problem is at the moment i am getting same as an result multiple times.
TXT:
http://textuploader.com/oyfi
public class random_2 {
public static void main(String[] args) {
int dolzina = 0;
Object s;
String outputFile = "random_2.txt";
ArrayList<String> list = new ArrayList();
try {
File file = new File("random1.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String vrstica;
while ((vrstica = bufferedReader.readLine()) != null) {
list.add(vrstica);
// dolzina=list.size();
// System.out.println(dolzina);
}
FileWriter fileWriter = new FileWriter(outputFile);
PrintWriter out = new PrintWriter(fileWriter);
for (int idx = 0; idx <= list.size(); ++idx) {
String test=list.get(idx);
dolzina=test.length();
Random randomGenerator = new Random();
for (int i = 0; i<= dolzina; ++i) {
int randomInt = randomGenerator.nextInt(dolzina);
StringBuilder beseda = new StringBuilder(test);
beseda.setCharAt(randomInt, '*');
System.out.println(beseda);
}
}
System.out.println("Done.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
You must use the constructor
Random(long seed)
A random generator can be view as an object that have a predefined list number, and returning at each call the next number into the list.
Using the Random(long seed) will give the first index to start with into the list.
Here into your code, you always start the random list at position 0.
Concretely, we use for the 'seed' parameter the actual time in millisecond. So each time you run your program, you will initalize the random generator with a different start index, and you will get a different result each run time.

Reading from a text file into an array

Hi im currently trying to do a hackerearth challenge sum of medians and it involves me reading from a text file and storing the values in an array. The first value has to be stored in a variable N which i am able to do but the the remaining values have to be stored in an array. This is where i become stuck. i have to read each value line by line and then store it in the array .
this is my code that i have been trying to get it working on but i just cant see where im going wrong.
import java.io.BufferedReader;
import java.io.InputStreamReader;
class TestClass {
public static void main(String args[] ) throws Exception {
// read number of data from system standard input.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int N = Integer.parseInt(line);
int i = 1;
int[] myIntArray = new int[N];
// median sum
long SumMedians = 0;
int median = 0;
while (i<N)
//read one line file and parse as an integer
//store the value in an array
{
myIntArray [i] = Integer.parseInt(line);
i = i + 1; // increment i so i is the total numbers read
}
so as i said i must increment through the text file storing each value on the line in an array. Any help would be amazing thanks
The text file will look like this
5
10
5
1
2
15
one string per line, which i have to pass into an integer.
what i will be doing is after i store the value from the line into the array i will be sorting it and finding its medium and then repeat this process until all the values from the text file have been read.
The problem which i am trying to do is this one
http://www.hackerearth.com/problem/algorithm/sum-of-medians-1/
If you're reading from a text file (and not from standard input which is what you're doing at the moment) then you want something like:
// Warning: this could fail if the filename is invaild.
BufferedReader br = new BufferedReader(new FileReader("inputFileName.txt"));
To then read in each line, you can use the following in the while loop:
// Warning: this will crash the program if the line contains anything other than integers.
myIntArray[i] = Integer.parseInt(br.readLine())
i = i + 1; // increment i so i is the total numbers read
You should also close the reader at the end:
try{
br.close();
} catch (IOException e)
{
System.out.println("Error, program exit!");
System.exit(1);
}
The import should be swapped from import java.io.InputStreamReader
to: import java.io.FileReader
Since you are only reading 1 line therefore I suspect it to be a single line delimited by colon/semicolon or other character.. try looking into StringTokenizer and Scanner classes
N = the number from parsing a string to a number
In the first part of your program it N = 5
Why are you using while(i<5)?
If anything you should be
r = number of lines in text file;
while (i< r)
{
readline;
parseline;
store in array;
}
and then sort
Adapting the example they gave you
import java.io.BufferedReader;
import java.io.InputStreamReader;
class TestClass {
public static void main(String args[] ) throws Exception {
/*
* Read input from stdin and provide input before running
*/
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int N = Integer.parseInt(line);
//create storage array
int[] myIntArray = new int[N];
//read remainder of file
for (int i = 0; i < N; i++) {
String line = br.readLine();
myIntArray[i] = Integer.parseInt(line);
}
// close file
br.close();
//Perform median calculations
int median = 0;
...
System.out.println(median);
}
}

Categories