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
Related
Here are the instructions:
Exercise 2
Write a program in a single file that:
Main:
Creates 10 random doubles, all between 1 and 11,
Calls a method that writes 10 random doubles to a text file, one number per line.
Calls a method that reads the text file and displays all the doubles and their sum accurate to two decimal places.
SAMPLE OUTPUT
10.6269119604172
2.737790338909455
5.427925738865128
1.3742058065472509
1.1858700262498836
4.180391276485228
4.910969998930675
5.710858234343958
7.790857007373052
3.1806714736219543
The total is 47.13
I have it all written but nothing is coming out on the txt file. I need help with the second method because I think I need to change something but I'm not sure what.
public class Program2 {
public static void main(String[] args) {
double[] nums = new double[10];
for (int i = 0; i < nums.length; i++) {
nums[i] = 1 + Math.random() * 11;
}
printNum(nums);
sumNum(nums);
}
public static void printNum(double[] values) {
try {
java.io.File randomNums = new java.io.File("Project1.txt");
randomNums.createNewFile();
java.io.PrintWriter output = new java.io.PrintWriter(randomNums);
for (int i = 0; i < values.length; i++) {
output.println(i);
}
}
catch (Exception ex) {
System.out.print("EX");
}
}
public static void sumNum(double[] ints) {
Scanner input = new Scanner("Project1.txt");
double sum = 0;
for (int i = 0; i < ints.length; i++) {
sum = sum + i;
}
System.out.printf("\n%-.2f", "The total is ", sum);
input.close();
}
}
Method printNum
There are two reasons why you may see no output in the file: Some error occurred or the file is not flushed/closed by the time you read from it.
Be sure to flush and close the PrintWriter before leaving the method:
output.flush();
output.close();
In case some error occurs, you just print EX, hiding what is actually going on. So use this catch block:
catch (Exception ex) {
System.out.print("EX");
ex.printStackTrace(System.out);
}
Read what the program is trying to tell you.
And last but not least: You are not printing the random numbers but the loop count. Use this:
for (int i = 0; i < values.length; i++) {
output.println(values[i]);
}
Method sumNum
You need to open the file for reading. Your line does not do it:
Scanner input = new Scanner("Project1.txt");
Use this instead:
Scanner input = new Scanner(new File("Project1.txt"));
Next, you are not reading from the scanner. Inside your loop use
sum = sum + input.nextDouble();
input.nextLine();
Finally you need to print the result, as mentioned by OldProgrammer:
System.out.printf("The total is %f", sum);
Main method
The random numbers you generate are not in the defined range. You can figure this out.
I have this code that prints out the max value of each row I have. But I am having trouble also printing out the row number for each output.I tried using i to add 1 to each row. Obviously this does not work with it, just wanted to show my attempt. Without the i the code works fine for finding the max value of my string from a text file. If there is another way to change my row number for each output it would be much appreciated. For example,
Row 1: 5
Row 2: 67
row 3: 43
is what i want. All i have been able to get is:
Row 1: 5
Row 1: 67
row 1: 43
My java code
import java.util.Scanner;
public class maxValue {
public static void main(String[] args) throws Exception {
int i=0;i<3;i++;
String fileName="C:\\Users\\Michael\\Documents\\input.csv";
File f = new File(fileName);
Scanner fileScan= new Scanner(f);
while(fileScan.hasNext()) {
String line=fileScan.nextLine();
System.out.println("ROW " + i + ": " + (extractMaximum(line)));
}
fileScan.close();
}
static int extractMaximum(String str) {
int num = 0;
int res = 0;
// Start traversing the given string
for (int i = 0; i<str.length(); i++) {
// If a numeric value comes, start converting
// it into an integer till there are consecutive
// numeric digits
if (Character.isDigit(str.charAt(i)))
num = num * 10 + (str.charAt(i)-'0');
// Update maximum value
else {
res = Math.max(res, num);
// Reset the number
num = 0;
}
}
// Return maximum value
return Math.max(res, num);
}
}
You need to increment i in the loop:
public static void main(String[] args) throws Exception
{
String fileName="C:\\Users\\Michael\\Documents\\input.csv";
File f = new File(fileName);
Scanner fileScan = new Scanner(f);
// One option: a for loop
for (int i = 1; fileScan.hasNext(); i++) {
String line = fileScan.nextLine();
// I prefer printf
System.out.printf("ROW %d: %d%n", i, extractMaximum(line));
}
fileScan.close();
}
// Re-written to use streams
// Even if you don't want to use stream,
// Using the regex to split the string is an improvement
static int extractMaximum(String str)
{
return Arrays.stream(str.split("\\D+"))
.map(x -> Integer.parseInt(x))
.max(Integer::compare)
.get();
}
I am trying to write a code which would count the number of words of a certain length in a file.
For example:
How are you?
would print:
Proportion of 3-letter words: 100% (3 words)
I want to count words of length 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13+
Can you please guide me?
I am NOT trying to find the number of words. I am already able to do with this code:
public static int WordCount() throws FileNotFoundException
{
File file = new File("sample.txt");
Scanner keyboard = new Scanner(new FileInputStream(file));
int count=0;
while(keyboard.hasNext())
{
keyboard.next();
count++;
}
return count;
}
I want to find words of a certain length.
UPDATE
I have written the following code:
public static int WordLengthCount() throws FileNotFoundException
{
File file = new File("hello.txt");
Scanner keyboard = new Scanner(new FileInputStream(file));
int count5 = 0;
int hell = 0; //This is just for the else command to compile
while(keyboard.hasNext())
{
if ( keyboard.next().length() == 5 )
{
count5++;
keyboard.next();
return count5;
}
} return hell;
}
You can use the length() method to count the number of characters in a string (word). From there on, it's just a matter of saving it somewhere. E.g., in Map:
public static Map<Integer, Integer> lengthCounts() throws FileNotFoundException
Map<Integer, Integer> countMap = new HashMap<>();
while(keyboard.hasNext())
{
String word = keyboard.next();
int length = word.length();
Integer currCount = countMap.get(length);
if (currCount == null) {
countMap.put (length, 1);
else {
countMap.put (length, currCount + 1);
}
}
return countMap;
}
Now you could check the number of words with any particular length, or even print all of them.
EDIT:
If the only thing you need is the percentage of words of a certain length, all you need are two counters - one for the words of that length, and one for all the words:
public static double lengthPercentage(int requiredLength) throws FileNotFoundException
int allWords = 0;
int requiredWords = 0;
while(keyboard.hasNext())
{
String word = keyboard.next();
int length = word.length();
if (length == requiredLength) {
++requiredWords;
}
++allWords;
}
// implicit assumption: there's at least on word in the file
return ((double) requiredWords) / allWords;
}
File file = new File("sample.txt");
Scanner keyboard = new Scanner(new FileInputStream(file));
int count=0;
while(keyboard.hasNext())
{
keyboard.next();
// Use a hash map
// Check the string length and add it to the hash map by checking it already exists. If already exists then get the actual value from hashmap and increment it by one and save it again to the map.
count++;
}
So that your final output will be of map with one letter string count, two letter string count etc..
The other answers are great, but if you are trying to find words of a specific length in a file and you don't like the answers above, then you could also try REGEX. You can test each word and then do what you want with it. If you are looking for a count of words in a file of each length, I think the answer above is better, but if you're looking to detect a word of a specific length you could use .length() or the regex below. Using a strings .lenght() function in my opinion is better, but I'm just giving you an alternative answer and example.
I'll put a small example below.
public class Words{
public static void main(String [] args){
String [] words = {"Pizzaaa", "Pizza", "Party"};
int fives = 0;
for( String s : words){
if(s.matches(".{5}")){
5++;
}
}
System.out.println(fives);
}
}
Or a better version:
public class Words{
public static void main(String [] args){
String [] words = {"Pizzaaa", "Pizza", "Party"};
int fives = 0;
for( String s : words){
if(s.length() == 5){
5++;
}
}
System.out.println(fives);
}
}
Edited Below: To demonstrate how it can be used in a file based loop
// other code needed
while(in.hasNext())
{
String s = in.next();
if(s.length() == 5)
fives++;
}
For example, I have text file named TextFile.txt at C:\ has content:
Ut porttitor libero sodales quam sagittis, id facilisis lectus semper.
and Java code:
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class Example {
public static void main(String[] args) throws IOException {
File file = new File("C:\\TextFile.txt");
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
if (dis.available() != 0) {
// Get the line.
String s = dis.readLine();
// Put words to array.
String[] sParts = s.split(" ");
// Initialize word longest length.
int longestLength = 1;
for (String strx : sParts) { // Go through each sPart, the next one is called strx
// If the document has word longer than.
if (longestLength < strx.length())
// Set new value for longest length.
longestLength = strx.length();
}
// Because array index from "0".
int[] counts = new int[longestLength + 1];
for (String str : sParts) {
// Add one to the number of words that length has
counts[str.length()] += 1;
}
// We use this type of loop since we need the length.
for (int i = 1; i < counts.length; i++) {
System.out.println(i + " letter words: " + counts[i]);
}
}
}
}
// Result:
// 1 letter words: 0
// 2 letter words: 2
// 3 letter words: 0
// 4 letter words: 1
// 5 letter words: 0
// 6 letter words: 2
// 7 letter words: 2
// 8 letter words: 0
// 9 letter words: 3
I have a quick question I have a program I am writing in java, it takes a .txt file reads what is inside it(this case it being a bunch of numbers) the program stores it in an array, then it sorts it from least to greatest it also finds the average as well as it tells me how many numbers in the array are bigger than the average. I have managed to do all of that but what I am having trouble with is now I want the program to print out another .txt file but this time with the results of my program. I want it to print out the sorted array the average the number of how many elements are in the array as well as the number of numbers bigger than the average. here is my code that i have:
import java.util.Scanner;
import java.util.Arrays;
class numberSorter{
public static void main (String[]args)throws Exception{
//calling the .txt file
java.io.File file= new java.io.File("numTestData.txt");
java.io.File file2=new java.io.File("dataOut.txt");
Scanner input = new Scanner(file);
//getting the numbers from the file
int num=input.nextInt();
//starting variables
int ct=0;
int bigger=0;
double average;
double track=0;
double[]numberArray=new double[num];
//filling in the rest of the numbers in the array
for(int i =0; i < numberArray.length; i++){
numberArray[i] = input.nextInt();
}
input.close();
//calling the sort method to sort the array
sort(numberArray);
//tracking how many elements are in the array
for(int i=0;i<numberArray.length;i++){
track+=numberArray[i];
}
//finding the average of the sorted array
average=track/numberArray.length;
//looking through the array to find which number is bigger than the average
for(int i=0;i<numberArray.length;i++)
{
if(numberArray[i]>average)
bigger++;
}
//checking to see of the .txt file exists
if(file2.exists()){
System.out.println("file exists");
System.exit(0);
}
//creating a file
try(
java.io.PrintWriter output=new java.io.PrintWriter(file2);
){
//printing out to the .txt file
output.println("Number of slots:");
output.println(numberArray.length);
output.println("sorted:");
for(int i =0; i < numberArray.length; i++){
output.println(numberArray[i]);
}
output.println("Average:");
output.println(average);
output.println("number of above average values: ");
output.println(bigger);
}
}
//sort method
public static void sort(double[]arrange)
{
//looking for the smallest number
for(int i=0;i<arrange.length-1;i++){
double currentMin=arrange[i];
int currentMinIndex=i;
//checking to see if the current number is smaller or bigger
for(int j=i+1;j<arrange.length;j++){
if(currentMin>arrange[j]){
currentMin=arrange[j];
currentMinIndex=j;
}
}
//will arrange the numbers if current number is not smaller
if(currentMinIndex!=i){
arrange[currentMinIndex]=arrange[i];
arrange[i]=currentMin;
}
}
}
}
Now my question is i keep getting this error, everything complies but when I try to run it i come across this:
----jGRASP exec: java numberSorter
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at numberSorter.main(numberSorter.java:26)
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
Ive tried to mees around with the code but I still keep getting this any help please? I am still learning java
To get rid of errors related to a not matching int in the first line, i would recommend not using this first int counting the numbers, you want to parse.
So your input file would be:
12345 23456 123 4567 123456 7654 999 3453 997733 43 654321
You could use an ArrayList instead of an array and then go through the file with input.hasNext().
I updated the parts in your code:
import java.util.ArrayList;
import java.util.Scanner;
public class NumberSorter {
public static void main(String[] args) throws Exception {
// calling the .txt file
java.io.File file = new java.io.File("numTestData.txt");
java.io.File file2 = new java.io.File("dataOut.txt");
Scanner input = new Scanner(file);
int bigger = 0;
double average;
double track = 0;
ArrayList<Double> numberArray = new ArrayList<Double>();
while (input.hasNext()) {
numberArray.add(input.nextDouble());
}
input.close();
// calling the sort method to sort the array
sort(numberArray);
// tracking how many elements are in the array
for (int i = 0; i < numberArray.size(); i++) {
track += numberArray.get(i);
}
// finding the average of the sorted array
average = track / numberArray.size();
// looking through the array to find which number is bigger than the
// average
for (int i = 0; i < numberArray.size(); i++) {
if (numberArray.get(i) > average)
bigger++;
}
// checking to see of the .txt file exists
if (file2.exists()) {
System.out.println("file exists");
System.exit(0);
}
// creating a file
try (java.io.PrintWriter output = new java.io.PrintWriter(file2);) {
// printing out to the .txt file
output.println("Number of slots:");
output.println(numberArray.size());
output.println("sorted:");
for (int i = 0; i < numberArray.size(); i++) {
output.println(numberArray.get(i));
}
output.println("Average:");
output.println(average);
output.println("number of above average values: ");
output.println(bigger);
}
}
// sort method
public static void sort(ArrayList<Double> arrange) {
// looking for the smallest number
for (int i = 0; i < arrange.size() - 1; i++) {
double currentMin = arrange.get(i);
int currentMinIndex = i;
// checking to see if the current number is smaller or bigger
for (int j = i + 1; j < arrange.size(); j++) {
if (currentMin > arrange.get(j)) {
currentMin = arrange.get(j);
currentMinIndex = j;
}
}
// will arrange the numbers if current number is not smaller
if (currentMinIndex != i) {
arrange.set(currentMinIndex, arrange.get(i));
arrange.set(i,currentMin);
}
}
}
}
This has been troubling me for a while now. I normally don't tend to ask help and do my research, but I couldn't find an answer.
How do I write a program that reads a text file, and calculate how many times a certain number shows up?
I'm a huge beginner in Java, and also programming in general.
Here's my code.
This code generates a text file that has 100 random numbers
import java.io.*;
public class Rolling
{
public static void main (String[] args) throws IOException
{
int randomNum;
PrintWriter fileout = new PrintWriter (new FileWriter ("randumnums.txt"));
for (int i= 0; i < 101; i++)
{
randomNum = (int) (Math.random() * 100);
fileout.println (randomNum);
}
fileout.close();
}
}
Now the trouble I'm having is that I need to read the file and write a code saying X number was rolled 3 times. e.g the number 4 appeared 5 times in the text file, so I would need it to print "the number 4 was rolled 5 times".
import java.io.*;
public class Reading
{
public static void main (String[] args) throws IOException
{
BufferedReader readFile = new BufferedReader (new FileReader ("randumnums.txt"));
int number = 0;
int inMarks [] = new int [100];
for (int i = 0; i < 100; i++)
{
inMarks [i] = Integer.parseInt(readFile.readLine());
}
}
}
You're actually pretty close. It's clear that you're going to have to keep track of your counts in some kind of list, and an array will do quite nicely here.
First, after instantiating inMarks, initialize every value in it to 0:
int inMarks [] = new int [100];
for (int i = 0; i < 100; i++)
{
inMarks [i] = 0;
}
Then change the loop below to this:
String nextLine = null;
while ((nextLine = readFile.readLine()) != null)
{
int thisInt = Integer.parseInt(nextLine);
inMarks[thisInt] = inMarks[thisInt] + 1;
}
inMarks now perfectly tracks how many times each distinct int was rolled in the file. I'm going to let you implement the print-out part of the assignment, since that will give you a better understanding of how this solution works.
I have the feeling you are looking for something like this (I haven't tested this code)
import java.io.*;
public class Reading {
public static void main (String[] args) throws IOException {
BufferedReader readFile = new BufferedReader (new FileReader("randumnums.txt"));
int number = 0;
int inMarks [] = new int [100];
String readNumber = "";
while ((readNumber = readFile.readline()) != null) {
number = Integer.parseInt(readNumber);
inMarks[number]++;
}
}
}
The code above basically has an array of 100 integers. We then start reading the file until nothing can be read anymore. Everytime we read a line, we parse into an integer (which normally you should wrap around a try...catch). We then increase by 1 the number of times we have read this number by increasing the corresponding index in the array. So if you want to know how many times the number '32' appeared, you would do System.print.out(inMarks[32]);