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.
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
My question is what they do " smallest" variable and the if statement. I know what the program do but it cost me to understand well the flow execution of this part .
import java.util.Scanner;
import java.util.ArrayList;
public class IndexOfSmallest {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<>();
while(true){
int numbers = Integer.valueOf(reader.nextLine());
if(numbers == 9999){
break;
}
list.add(numbers);
}
int index;
int smallest = list.get(0);
for (int i = 0; i < list.size();i++){
int number = list.get(i);
if ( smallest > number){
smallest = number;
}
}
System.out.println(smallest);
}
}
This is a rather simple console application. You should try to read your code line by line when you are starting to learn a new language.
This way you can show some effort and ask more clear and concise questions. Here is an example to go about reading your code line by line. If you don't know what some function is doing, look up that function.
Just take your time, you'll get used to the syntax and it will get easier every time.
Scanner reader = new Scanner(System.in); // Create scanner taking console inputs
ArrayList<Integer> list = new ArrayList<>(); // Create list
while(true){ // Endlessly loop
// Keep reading input from console until user inputs 9999, then break
int number = Integer.valueOf(reader.nextLine());
if(number == 9999){
break;
}
list.add(number); // Add number to list
}
/* int index; // This is worthless, not used again */
int smallest = list.get(0); // Variable to store smallest number
for (int i = 0; i < list.size();i++){ // Increase i until list size is reached
int number = list.get(i); // Get number for position i in list
if ( smallest > number){ // Compare
smallest = number; // Set new smallest number
}
}
System.out.println(smallest); // Print
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);
}
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 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.