There are 26 numbers in the numbers.txt file. Those 26 numbers are supposed to be read to arr but instead I get 26 zeroes in my array.
Scanner scanner = new Scanner(new File("numbers.txt"));
int n = 0;
int i = 0;
while (scanner.hasNextInt()) {
scanner.next();
n++;
} // n is now 26
int[] arr = new int[n];
while (scanner.hasNextInt()) {
for (i = 0; i < arr.length; i++) {
arr[i] = scanner.nextInt();
}
}
System.out.print(Arrays.toString(arr));
zeroes are default value for array. a scanner is "single-use", it's single-pass. you used it once, you have to create another (maybe by earlier having the File object in a variable and then using it to create both Scanners?) or somehow reverse its state. the second loop has zero iterations, it never hasNextInt anymore
MichaĆ is right -- you need to repeat the scanner = new Scanner(...) after your // n is now 26 line.
Or, better, use an ArrayList<Integer>() rather than int[], then you only need a single pass:
public static void main(String[] args) throws Exception {
List<Integer> numbers = new ArrayList<>();
Scanner scanner = new Scanner(new File("numbers.txt"));
while (scanner.hasNextInt()) {
numbers.add(scanner.nextInt());
}
System.out.print(numbers);
}
Related
I have a data file that consists of a calorie count.
the calorie count it separated by each elf that owns it and how many calories are in each fruit.
so this represents 3 elves
4323
4004
4070
1780
5899
1912
2796
5743
3008
1703
4870
5048
2485
1204
30180
33734
19662
all the numbers next to each other are the same elf. the separated ones are seperate.
i tried to detect the double line break like so
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String [] args) throws FileNotFoundException
{
int[] elf = new int[100000];
int cnt = 0;
Scanner input = new Scanner(new File("Elf.dat"));
while(input.hasNext())
{
elf[cnt] += input.nextInt();
if (input.next().equals("\n\n"));
{
cnt++;
}
}
int big = elf[0];
for (int lcv = 0; lcv < elf.length; lcv++)
{
if (big < elf[lcv])
{
big = elf[lcv];
}
}
System.out.println(big);
}
}
I'm trying this to detect the double line break
if (input.next().equals("\n\n"));
but its giving me errors. how would i detect it
Here is another alternative way to do this sort of thing. read comments in code:
public static void main(String[] args) throws FileNotFoundException {
List<Integer> elfSums; // Can grow dynamically whereas an Array can not.
int sum;
// 'Try With Resources' used here to auto close the reader and free resources.
try (Scanner input = new Scanner(new File("Elf.dat"))) {
elfSums = new ArrayList<>();
String line;
sum = 0;
while (input.hasNextLine()) {
line = input.nextLine();
if (line.trim().isEmpty()) {
elfSums.add(sum);
sum = 0; // Reset sum to 0 (new elf comming up)
}
// Does the line contain a string representation of a integer numerical value?
if (line.matches("\\d+")) {
// Yes...add to current sum value.
sum += Integer.parseInt(line);
}
}
}
if (sum > 0) {
elfSums.add(sum);
}
// Convert List to int[] Array (There are shorter ways to do this)
int[] elf = new int[elfSums.size()];
for (int i = 0; i < elfSums.size(); i++) {
elf[i] = elfSums.get(i);
// For the heck of it, display the total sum for this current Elf
System.out.println("Elf #" + (i+1) + " Sum: -> " + elf[i]);
}
/* The elf[] int array now holds the data you need WITHOUT
all those empty elements with the array. */
}
Welcome to Advent of Code 22.
As a good rule, never mix nextXXX methods with any other next.
To break up the Blocks you have 2 good options:
Read line by line and fill a new list when you encounter a empty/blank line
Read the whole text fully, then split by the \n\n Combination
I am reading in from a file numbers spaced out by _ (1-9) and then with each number you do something to a stack. I'm just trying to get my case to read each item in the array and do something for each number but i can't seem to get it to work.
public static void main(String[] args) throws FileNotFoundException {
FileReader file = new FileReader("textfile.txt");
int[] integers;
integers = new int[100];
int i = 0;
try (Scanner input = new Scanner(file)) {
while (input.hasNext()) {
integers[i] = input.nextInt();
i++;
}
Stack<Integer> nums = new Stack<>();
int number = integers[i];
switch (number) {
case '1':
nums.push(5);
System.out.println(nums.peek());
break;
}
} catch (Exception e) {
}
}
In your switch statement, take the single quotes out from the number 1.
'1' is of type char
1 is of type int
Also, when you try to get a number here:
int number = integers[i];
It's always going to be 0 because i is now an index greater than what you've actually populated in your array.
Assume that i have 4 grades in testgrades.txt I don't know why this wont work.
public static void main(String[] args) throws FileNotFoundException {
File file1= new File("testgrades.txt");
int cnt = 4;
int[] grades = new int[cnt];
String line1;
for (int i=0; i<cnt; i++) {
Scanner inputFile2 = new Scanner(file1);
line1 = inputFile2.nextLine();
int grades2 = Integer.parseInt(line1);
grades[i] = grades2;
}
System.out.print(grades);
First of all, you should note that arrays in java hold fixed-size elements of the same type.
You can initialize them in one of two ways (not very sure if there are other ways).
//First method
int[] anArray = new int[10];
// Second method
int[] anArray = {1,2,3,4,5,6,7,8,9,10};
In either case, the array is of size 10 elements. Since you are fetching the data from the text file, I'll suggest you count number of lines into a variable and use that value to initialize the array. Then you can use a loop to fill the values this way:
// Assuming you have cnt as your total count of grades.
int[] grades = new int[cnt];
String line1;
for (int 1=0; i<cnt; i++) {
line1 = inputFile2.nextLine();
int grades2 = Integer.parseInt(line1);
grades[i] = grades2;
}
This is coming off my head so let me know if you face any problem.
You can do like this
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
File file= new File("testgrades.txt");
Scanner scan = new Scanner(file);
int arr[] = new int[100];
int i = 0;
do{
String line1 = scan.nextLine();
int grades2 = Integer.parseInt(line1);
arr[i++] = grades2;
}while(scan.hasNextLine());
for(int j = 0; j < i; j++){
System.out.println(arr[j]);
}
}
I have a file with numbers. It looks as follows:
1 2
3 4
5 6
7 8
9 10
The problem occurs while reading the numbers into Array.
Here is a piece of code:
Scanner file1 = new Scanner( new File("file1.txt") );
int lengt_h = 0;
// Here Eclipse crashes...
while( file1.hasNext() ) lengt_h++;
int[] numberArray = new int[lengt_h];
for(int i=0; i<numberArray.length; i++) {
numberArray[i] = file1.nextInt();
}
for(int n: numberArray) System.out.print(numberArray[n] + " ");
Even if I change a hasNext() function into constant length (e.g 10), then numbers in numberArray Array looks as follows:
1 1 1 2 1 1 5 5 1 3
Why the code does not work properly?
problem with you code is you are not moving the Sacanner pointer in while loop so it were infinite loop.
In your last for loop you are trying to access element from numberArray[n] which is wrong because n itself is a number from your array numberArray.
you can try this :
public static void main(String args[]) throws FileNotFoundException {
Scanner file1 = new Scanner(new File("d:\\data.txt"));
int lengt_h = 0;
while (file1.hasNext()) {
lengt_h++;
file1.next();
}
file1 = new Scanner(new File("d:\\data.txt")); // again put file pointer at beginning
int[] numberArray = new int[lengt_h];
for (int i = 0; i < numberArray.length; i++) {
numberArray[i] = file1.nextInt(); // read integer from file
}
for (int n : numberArray)
System.out.print(n + " ");
}
while( file1.hasNext() ) lengt_h++; // infi loop
hasNext method returns true if and only if this scanner has another token
public boolean hasNext()
You are not reading next token and hence hasNext() will always return true
[EDIT]
If you don't know the size of array in advance, its better to use ArrayList
[1] http://www.tutorialspoint.com/java/util/java_util_arraylist.htm
Check the hasNext method here http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNext%28%29
it says "The scanner does not advance past any input."
So to move it further you should move to next token.
Try this:
List<Integer> numberArray = new ArrayList<Integer>();
while (file1.hasNext())
numberArray.add(file1.nextInt());
for (Integer n : numberArray)
System.out.print(n + " ");
I'm cating a file using the cat text-file | Java my-program on my terminal
the result when I print the lines after i store it into a array results in null
can someone explain why?
Scanner scan2 = new Scanner(System.in);
Scanner scan = new Scanner(System.in);//create new scanner object
int index = 0;//create index to increment through array
while(scan.hasNextLine()){//while looop to execute if file has length
String line = scan.nextLine();//store line into string input
count++;
}
if(count < BUFSIZE){
stringArray = new String[count];
}
else{
stringArray = new String[BUFSIZE];
}
while(scan2.hasNextLine()){
String line2 = scan2.nextLine();
if(index > stringArray.length-1)
{
stringArray = expandArray(stringArray,BUFSIZE);//call method to increase array length
}
stringArray[index] = line2;//store line into array at given index
index++;//increment index
}
/*while(sorted){
sorted = false;
for(int i = 0; i < stringArray.length-1; i++){
if(stringArray[i].compareTo(stringArray[i+1]) > 0){
temp = stringArray[i];
stringArray[i] = stringArray[i+1];
stringArray[i+1] = temp;
sorted = true;
}
}
}*/
for(int i = 0; i < stringArray.length; i++){
System.out.println(stringArray[i]);
}
}
}
private static String [] expandArray(String [] array, int extend){
String newArray [] = new String[array.length+extend];//create new array with given array and int as length to extend
//for loop to copy data from old array into new created array
for( int i = 0; i < array.length; i++){
newArray[i] = array[i];
}
return newArray;//return newly created array
}
}
the program bubble sorts the array of strings. If I read in the file through Scanner file its fine, but why I cat it doesn't. The expand array method is to dynamically expand the array every-time it reaches max capacity. Thank you
The following is wrong:
Scanner scan2 = new Scanner(System.in);
Scanner scan = new Scanner(System.in);//create new scanner object
Basically, each scanner grabs the System.in stream, but streams can only be read once. You should change your code to use only one scanner, and then only use it once.
When you wrote the program to use a file, the Scanner would actually open two streams to the file so that it can be read twice, but this won't work when all you have is one stream.
EDIT:
Here is a version where you use only one Scanner (and thus one stream) :
Scanner scan = new Scanner(System.in);//create new scanner object
int count = 0;
stringArray = new String[BUFSIZE];
while (scan.hasNextLine()){//while looop to execute if file has length
String line = scan.nextLine();//store line into string input
if (count >= stringArray.length) {
//call method to double array length
stringArray = expandArray(stringArray, stringArray.length);
}
stringArray[count] = line;
count++;
}
// Shrink array to required size
String[] temp = stringArray;
stringArray = new String[count];
System.arraycopy(temp, 0, stringArray, 0, count);
Please note I didn't test it, but this is conceptually how you could do it.
The other alternative is to use an ArrayList<String> which will automatically expand and shrink.
Scanner scan = new Scanner(System.in);
List<String> list = new LinkedList<>();
while(scan.hasNext()) list.add(scan.next());
scan.close();
Collections.sort(list);
for(String line : list) System.out.println(line);
lol
UPDATE #JBert:
System.out.println(StringUtils.join(Ordering.<String>natural().sortedCopy(IOUtils.readLines(System.in)), "\r\n"));
looool
In this code
while(scan2.hasNextLine()){
String line2 = scan2.nextLine();
if(index > stringArray.length-1)
you are doing something if index is greater than the length of the array, but no doing anything otherwise.