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?
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 want to design a code that can read a file that looks like this:
Jake 12.00 13.24 6
Sarah 11.23 24.01 8
Alex 10.65 19.45 4
I need to make separate arrays for the Strings, the first float, the second float, and the int.
How do I go about doing this?
This is what I have so far: I'm not sure how to make separate arrays for the two floats. I also keep getting an exception IndexOutOfBoundsException: 0 at EmployeePay.main..
import java.util.Scanner;
import java.io.*;
public class EmployeePay {
public static void main(String[] args) throws FileNotFoundException {
if (args.length != 1) {
final String msg = "Usage: EmployeePay name_of_input file";
System.err.println(msg);
throw new IllegalArgumentException(msg);
}
final String inputFileName = args[0];
final File input = new File (inputFileName);
final Scanner scanner = new Scanner(new BufferedReader(new FileReader(input)));
String Id = "Employee Id:";
String Hours = "Hours worked:";
String WageRate = "Wage Rate:";
String Deductions = "Deductions:";
System.out.printf("%s %-10s %-20s %-30s", Id, Hours, WageRate, Deductions);
int lineNumber = 0;
while (scanner.hasNextLine()){
lineNumber =lineNumber +1;
String [] Identification= new String [lineNumber-1];
int [] TotalDeductions = new int [lineNumber-1];
float [] WorkTime = new float[lineNumber-1];
if(scanner.hasNextInt()){
TotalDeductions[lineNumber-1] = scanner.nextInt();
System.out.println(TotalDeductions[lineNumber-1]);
}
else if (scanner.hasNextFloat()){
WorkTime[lineNumber-1]= scanner.nextFloat();
}
else {
Identification[lineNumber-1] = scanner.next();
System.out.println(Identification[lineNumber-1]);
}
}
}
}
I will assume your String value doesn't contain space. This is kind of pseudo code, Try yourself and explore each line why I did so:
String s[] = new String[size];
float f1[] = new float[size];
float f2[] = new float[size];
for(int i=0; i<numberOfLines;i++) {
String x = "Jake 12.00 13.24 6";
String[] arr = x.split(" ");
s[i] = arr[0];
f1[i] = Float.valueOf(arr[1]);
f2[i] = Float.valueOf(arr[2]);
}
This error exception IndexOutOfBoundsException: 0 at EmployeePay.main. is occuring due to this statement if (args.length != 1).
It should be if(args.length!=0)
If no arguements are passed at command prompt then args.length is 0. So, this statement will throw an exception final String inputFileName = args[0];
Thus, you need to check for args.length
If your data file is indeed as you show in your post with blank lines between the data lines then you will need to take care of those as well while reading the file and processing the information obtained. You obviously want to skip past those particular lines. If this isn't the case then it only goes to show you how important it is to provide full and accurate information when asking a question here. No one here wants to really assume anything.
When creating arrays it's always nice to know how big an array needs to be beforehand so that you can properly initialize it to its required size. This is where List or ArrayList is better, you can just add to them when needed. Never the less, to properly initialize all your different arrays (String[], float[], float[], and int[]) you need to know how many valid data line are contained within your data file. By valid data lines I mean lines that actually contain data, not blank lines. So the first natural step would be to count those lines. Once you have the count then you can initialize all your arrays to that line count.
Now all you need to do is re-read the file data line by line, split each line to acquire the data segments , then convert each numerical segment to its respective Array data type. Once you have all your arrays filled from the file you can then do whatever you like with the data contained within those arrays. The code to carry out this task might look something like this:
String inputFileName = "MyDataFile.txt";
Scanner scanner;
int linesCount = 0;
try {
// Count the total number of valid data lines
// within the file (blank line are skipped).
scanner = new Scanner(new File(inputFileName));
while (scanner.hasNextLine()) {
String strg = scanner.nextLine().trim();
if (!strg.equals("")) { linesCount++; }
}
// Declare our different Arrays and size them to
// the valid number of data lines in file.
String[] employeeID = new String[linesCount];
float[] hours = new float[linesCount];
float[] wageRate = new float[linesCount];
int[] deductions = new int[linesCount];
// Read through the file again and place the data
// into their respective arrays.
scanner = new Scanner(new File(inputFileName));
int counter = 0;
while (scanner.hasNextLine()){
// Get the next line in file...
String strg = scanner.nextLine().trim();
// If the file line is blank then skip it.
if (strg.equals("")) { continue; }
// otherwise split the line by its space
// delimiter ("\\s+" takes care of 1 OR more
// spaces just in case).
String[] values = strg.split("\\s+");
// Add to the employeeID string array.
employeeID[counter] = values[0];
// Control what is placed into the elements of each
// float or integer array. If there is no value data
// supplied in file for the employee Name then make
// sure 0.0 (for floats) or 0 (for integers) is placed
// there after all, you can't parse a null string ("").
if (values.length >= 2) { hours[counter] = Float.parseFloat(values[1]); }
else { hours[counter] = 0.0f; }
if (values.length >= 3) { wageRate[counter] = Float.parseFloat(values[2]); }
else { wageRate[counter] = 0.0f; }
if (values.length == 4) { deductions[counter] = Integer.parseInt(values[3]); }
else { deductions[counter] = 0; }
counter++;
}
scanner.close();
// Now that you have all your arrays you can
// do whatever you like with the data contained
// within them:
String Id = "Employee Id:";
String Hours = "Hours worked:";
String WageRate = "Wage Rate:";
String Deductions = "Deductions:";
System.out.printf("%-15s %-15s %-15s %-15s%n", Id, Hours, WageRate, Deductions);
for (int i = 0; i < employeeID.length; i++) {
System.out.printf("%-15s %-15s %-15s %-15s%n", employeeID[i], hours[i], wageRate[i], deductions[i]);
}
}
catch (FileNotFoundException ex) { ex.printStackTrace(); }
I need to store a text file into a linked list. I am given a text file like:
1
2
3
4
5
When I try to say scanner.next it says there is a no element exception.
But I also need to account for a file like this:
Michael
Hannah
Josephus
Ruth
Matthew
So I can't just say nextInt because it could be a string.
How can I check if its integers or strings?
Thanks!
My code:
Scanner sc = new Scanner(f);
int k = 1;
String line = new String(sc.next());
ListNode nodes = new ListNode(n, null);
while(k < n - 1)
{
line = sc.nextLine();
nodes.setNext(new ListNode(n, null));
}
line = sc.nextLine();
ListNode last = new ListNode(n, null);
nodes.setNext(last);
return nodes;
You could use Scanner.next() for all tokens, then simply do Integer.parseInt() for tokens with integers.
Here is an example:
File f = new File("myfile.txt");
Scanner scn = new Scanner(f);
String s = "";
while(scn.hasNext()) {
s=scn.next();
try {
Integer.parseInt(s);
//if the code made it to this line, s is an int, handle at as such
} catch(NumberFormatException e) {
//s is a string, handle it as such
}
}
Just a word of advice, hasNext() will be true even if the next token is an integer. As such, you can't use hasNext() to determine if the file is composed of Ints or Strings. However, if you know in advanced that the file is of one type (no mixed cases), the following would also work:
if(scn.hasNextInt()) { //if true, you know that this file is ints
while(scn.hasNextInt()) {
int i = scn.nextInt(); //handle all as ints
}
} else { //otherwise the file is strings
while(scn.hasNext()) {
String s = scn.next();
//handle all as strings
}
}
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]);
}
}
}
I am fairly new to Java and am struggling with this concept. As I have said I am trying to make a comparison between 2 sets of integer values, one set I have retrieved from the website using HTML parsing and stored in an array (Integer [] numbers = new Integer[split.length]).
The other set of values I have retrieved from user input and have stored in the array userNumbers (int userNumbers = new int [SIZE]). I attempted to use the if condition to make the comparison i.e. if (userNumber[count] == number [0]).
However I am getting errors and the IDE is not allowing me to enter the number array part of the comparison. Can anyone help me to understand why this is or instruct me as to what I may be doing wrong? Here is the code in full.
Help is very much appreciated in advance.
public class lotteryNumbers
{
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args)
{
//link to the intended web site
try {
Document doc = Jsoup.connect("http://www.national-lottery.co.uk/player/p/drawHistory.do").get();
Elements elements = doc.getElementsByClass("drawhistory");
Element table = elements.first();
Element tbody = table.getElementsByTag("tbody").first();
Element firstLottoRow = tbody.getElementsByClass("lottorow").first();
Element dateElement = firstLottoRow.child(0);
System.out.println(dateElement.text());
Element gameElement = firstLottoRow.child(1);
System.out.println(gameElement.text());
Element noElement = firstLottoRow.child(2);
System.out.println(noElement.text());
String [] split = noElement.text().split(" - ");
// set up an array to store numbers from the latest draw on the lottery web page
Integer [] numbers = new Integer [split.length];
int i = 0;
for (String strNo : split) {
numbers [i] = Integer.valueOf(strNo);
i++;
}
for (Integer no : numbers) {
System.out.println(no);
}
Element bonusElement = firstLottoRow.child(3);
Integer bonusBall = Integer.valueOf(bonusElement.text());
System.out.println("Bonus ball: " + bonusBall);
//Elements elementsHtml = doc.getElementsByTag("main-article-content");
} catch (IOException e) {
e.printStackTrace();
}
final int SIZE = 7;
//array to store user numbers
int [] userNumbers = new int[SIZE];
//array to check if user number is present with web numbers
boolean [] present = new boolean[7];
int counter = 0;
while (counter<SIZE)
{
System.out.println("enter your numbers");
userNumbers[counter]=keyboard.nextInt();
counter++;
}
for (int count: userNumbers)
System.out.println(count);
if (userNumbers[0] == )
The numbers local variable is declared in the try{...} block. Thus it is not accessible outside it.
If you declare it before the try{ line it will work:
Integer[] numbers;
try {
...
// set numbers here
...
} catch (IOException e) {
...
}
// can use numbers here
If it is the only value you need from the HTML-parsing code you may even refactor the try/catch structure to a method returning the data for numbers.
And by the way, I advise you not to try int == Integer, prefer int == int. It is usually clearer and you won't have to guess if the int will be boxed or the Integer unboxed.