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 + " ");
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
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);
}
This question already has answers here:
How do I reverse an int array in Java?
(47 answers)
Closed 3 years ago.
If my input is 1 2 3 the output is also coming out as 1 2 3, how do I make these numbers to display 3 2 1?
public static void main(String[] args) {
// TODO code application logic here
Scanner s = new Scanner(System.in);
String text = s.nextLine();
String[] entries = text.split(" ");
int[] nums = new int[entries.length];
for(int i = 0; i < entries.length; i++){
nums[i] = Integer.parseInt(entries[i]);
}
for(int i = 0; i < entries.length; i++){
System.out.println(nums[i]);
}
}
}
If you want to store numbers in reverse order:
for(int i = 0; i < entries.length; i++)
{
nums[i] = Integer.parseInt(entries[entries.length-i-1]);
}
If you want to just display numbers in reverse order(they'll remain same order in list:
for(int i = entries.length-1; i >= 0; i--)
{
System.out.println(nums[i]);
}
Try below code:
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
String text = s.nextLine();
String[] entries = text.split(" ");
for(int i = entries.length-1; i >= 0; i--)
{
System.out.print(Integer.parseInt(entries[i])+ " ");
}
}
If you want Java 8 version, here is the code
Scanner s = new Scanner(System.in);
String text = s.nextLine();
String[] entries = text.split("\\s");
List<Integer> integers = Arrays.stream(entries)
.map(Integer::valueOf)
.collect(Collectors.toList());
Collections.reverse(integers);
integers.forEach(integer -> System.out.print(String.format("%d ", integer)));
\\s indicates 'white space' and I suggest you to close Scanner at the end.
You could loop through your entries array backwards. This would involve starting int i at the length of entries minus 1 (as that is your last index in your array - ie your last number). It would also require that you keep looping while i >= 0. Lastly, instead of incrementing your i variable, you need to decrement it. This way your counter i will go from the end of your loop to the start of your array (eg: if you enter "1 2 3", i will go from indexes: 2, 1, 0)
See example below:
public static void main(String[] args) {
// TODO code application logic here
Scanner s = new Scanner(System.in);
String text = s.nextLine();
String[] entries = text.split(" ");
int[] nums = new int[entries.length];
for(int i = 0; i < entries.length; i++) {
nums[i] = Integer.parseInt(entries[i]);
}
for(int i = entries.length-1; i >= 0; i--) {
System.out.println(nums[i]);
}
}
The main question will be at the bottom. From the text file below, lets say the first integer is a, second is b, and third is c and so forth. the program takes a,b and c, parses them, puts them into myCalculations method which returns a string with two integers. The string is parsed, a and b are replaced the integers in said returned string, then the next iteration of the loop will take the new values for a and b, and integer d. This will continue until the end where a and b are printed to the user.
The input from a two text files is as follows:
The format of the text file is as follows:
200 345
36
45
36
21
Here is the reading in from the file, it works as intended, I put it here for context. tl;dr is results[] is an integer array for the first line. (int a and b)
public class conflictTrial
{
BufferedReader in;
public static void conflictTrial() throws FileNotFoundException
{
System.out.print('\u000c');
System.out.println("please enter the name of the text file you wish you import. Choose either costs.txt or lotsacosts.txt Nothing else");
Scanner keyboard = new Scanner(System.in);
String filename = keyboard.nextLine();
File file = new File(filename);
BufferedReader in = new BufferedReader(new FileReader(file));
String element1 = null;
try {
element1 = in.readLine();
}catch (Exception e) {
// handle exception
}
String[] firstLine = element1.split(" ");
Arrays.stream(firstLine).forEach(fl -> {
//System.out.println("First line element: \t\t\t" + fl);
});
int[] results = new int[100];
for (int i = 0; i < firstLine.length; i++)
{
try {
int stuff = Integer.parseInt(firstLine[i]);
results[i] = stuff;
}
catch (NumberFormatException nfe) {
// handle error
}
}
The bufferreader reads in the file, the for loop parses the integers into array results[]. Next, the remaining lines are parsed and method myCalculations is called:
String otherElement = null;
int[] aliveSoldiers = new int[100];
int [] things = new int [100];
int[] newResults = new int[100];
try {
while ((otherElement = in.readLine()) != null) { // main loop
System.out.println("Line to process:\t\t\t" + otherElement);
String[] arr = otherElement.split(" ");
for (int k = 0; k <arr.length; k++)
{
int thingsResult = Integer.parseInt(arr[k]);
things[k] = thingsResult;
System.out.println("number of days: \t\t\t"+things[k]);
aliveSoldiers[0] = results[0];
aliveSoldiers[1] = results[1];
String returnAliveSoliders = myCalculations(aliveSoldiers[0], aliveSoldiers[1], things[k]);
System.out.println("return soldiers alive: \t\t"+returnAliveSoliders);
String[] newItems = returnAliveSoliders.split(" ");
for (int f = 0; f < newItems.length; f++)
{
int newParse = Integer.parseInt(newItems[f]);
newResults[f] = newParse;
aliveSoldiers[0] = newResults[0];
aliveSoldiers[1] = newResults[1];
}
k++;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
Currently the code does the following: first of the main loop iteration takes integer a, b and c, second iteration takes the same integers a and b (200 and 345, the initial values) with integer d, the third iteration takes the same values for and a and b with integer e. I have attempted to address this issue with the following code:
aliveSoldiers[0] = newResults[0];
aliveSoldiers[1] = newResults[1];
I need to take the integers from the method myCalculations (parsed in the k-modifier loop), and overwrite them into aliveSoldiers[0] and aliveSoldiers [1] so the program reads the next line, takes the new integers, and continues until there are no more days remaining.
I honestly haven't understood what the whole exercise should do, but the code You enlighted could be wrong due to the indexes You use: those indexes are always 0 and 1, even if cycles are performed through some other indexes. At the end of the second code snippet, the f-for modify the array "newResults" at the increasing index "f", but that array is read always at the same index: 0 and then 1. So, if "f" gets higher values than "1" then the "aliveSoldiers"'s elements are left unchanged.
In particular, aliveSoldiers is modified only on the first two indexes, the other indexes are not used at all.
Do you need a stack-like or queue-like behaviour?
i am writing a code that reads input from a file and writes into another after some processing ofcourse.
now, my input file is,
4
0 1
0 2
0
0 3
3
0
0
0
E
and what i need to do is copy elements on left to an array in first column and elements on right to second column.
i used scanner but it does not recognize end of line.
help me!!!!
this is what i tried.
i tried copying lines and then modifying it.
for (i = 0; i < size; i++) {
if (!f1.hasNext(endPage)) {
String temp1 = f1.next();
String temp2 = f1.next();
int a[] = new int[4];
a[0] = (int) temp1.charAt(temp1.length() - 1);
a[1] = (int) temp2.charAt(temp1.length() - 1);
a[2] = (int) temp1.charAt(temp1.length() - 2);
a[3] = (int) temp1.charAt(temp1.length() - 2);
scales[i].weightOnLeft = a[0];
scales[i].weightOnRight = a[1];
scales[i].left = scales[a[2]];
scales[i].right = scales[a[3]];
}
}
Try this way:
Scanner input = new Scanner(new File("..."));
while(input.hasNextLine())
{
String data = input.nextLine();
}
Try to use the Scanner to read line by line and then split(on space, in your case) your line to get the tokens.
Scanner f1 = new Scanner(new File("yourFileName.extn"));
while(input.hasNextLine()) {
String line = f1.nextLine();
String[] tokens = line.split(" "); // Splitting on space
// Do what you want with your tokens
// Since not all lines have equal no. of tokens, you need to handle that accordingly
}
Try like this below:-
In your first column it will store on array[0] and second column value will store on array[1]. Also for second column you need to check the condtion as written below. Please follow:-
File file=new File("/Users/home/Desktop/a.txt");
String[] aa=new String[2];
try {
Scanner sc=new Scanner(file);
while (sc.hasNextLine())
{
String ss=sc.nextLine();
aa=ss.split("\\s");
//it will store left column value in this index
System.out.println("aa[0]"+aa[0]);
if(aa.length>1)
{
//it will store right column value in this index
System.out.println("aa[1]"+aa[1]);
}
}
}