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);
}
}
}
}
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
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 am attempting to write 100 random integers to one text file, sort them from least to greatest, and then write those numbers, sorted, to a separate text file. I understand how to write the numbers to one file, and how to sort them. Both files must be created by the program if they do not already exist. For instance if the "Numbers.txt" that I write the original 100 random integers on does not exist, the program will create the file for me, as same goes for the text file I am attempting to write the sorted numbers on. I am struggling to understand how to write the sorted numbers from one file to another.
I have attempted to take the same numbers from the integer array that the numbers are originally stored in, and sort it with the Arrays.sort command, and then write that information to the separate file which I wish to be called "Sorted.txt". I run into a problem there where I get an incompatible type error, stating void cannot be converted to int, but do not know how to fix this error in logic.
import java.util.*;
import java.io.*;
public class Numbers {
public static void main(String[] args) throws Exception {
//check if source file exists
File number = new File("Numbers.txt");
File sorted = new File("Sorted.txt");
if (!number.exists()) {
try ( // create the file
PrintWriter output = new PrintWriter(number);
) {
for (int i = 0; i <= 100; i++) {
output.print(((int)(Math.random() * 999) + 1) + " ");
}
}
}
try (
Scanner input = new Scanner(number);
) {
int[] numbers = new int[100];
for (int i = 0; i < 100; i++)
System.out.print(numbers[i] + " ");
System.out.println();
if (!sorted.exists()) {
try (
PrintWriter output = new PrintWriter(sorted)
) {
for (int i = 0; i < 100; i ++) {
output.print((int)Arrays.sort(numbers));
}
}
}
}
}
}
The expected result is that the first text file shows the numbers as they were when they were randomly created, while the second text file shows them after they are sorted. As of current, I can get the first file to show the numbers in a random order, but cannot even get the second text file to be created, let alone the numbers sorted and wrote on it.
Arrays.sort returns void (see doc).
What you could do is sort the array.
Arrays.sort(numbers);
And after write the result to a file.
for (int i = 0; i < 100; i ++) {
output.print(numbers[i] + " ");
}
Complete Example:
import java.io.File;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class Numbers {
public static void main(String[] args) throws Exception {
//check if source file exists
File number = new File("Numbers.txt");
File sorted = new File("Sorted.txt");
if (!number.exists()) {
try ( // create the file
PrintWriter output = new PrintWriter(number);
) {
for (int i = 0; i <= 100; i++) {
output.print(((int)(Math.random() * 999) + 1) + " ");
}
}
}
try (
Scanner input = new Scanner(number);
) {
int[] numbers = new int[100];
for (int i = 0; i < 100; i++) {
numbers[i] = input.nextInt();
}
if (!sorted.exists()) {
try (
PrintWriter output = new PrintWriter(sorted)
) {
Arrays.sort(numbers);
for (int i = 0; i < 100; i ++) {
output.print(numbers[i] + " ");
}
}
}
}
} }
I would suggest extracting to a method the code that writes to the file. Since it would only need a path and content it can be reused for both files and it will make your life way easier.
It is also very helpful if you include the line number where you get the error since it's not always clear where the exception is thrown.
From what I understood from your question the problem is about generating some numbers, write them to a file and lastly sort them and write them to another file. I wrote some code using the same approach but a bit more restructured. I hope it helps.
public static void main(String[] args) {
int[] randomData = new Random().ints(100).toArray();//just a short way to generate numbers. Use your own.
File numbers = writteArray("Numbers.txt", randomData);
Arrays.sort(randomData);
File sorted = writteArray("Sorted.txt", randomData);
}
public static File writteArray(String Path, int[] randomNumbers){
File numbers = new File(Path);
//if the file does not exist it will be created automatically
try(PrintWriter fileWritter = new PrintWriter(numbers)) {
//just an example of how to write them. Use your prefered format
//also you can use the append function to not lose the previous content
for (int e : randomNumbers)
fileWritter.printf(" %d", e);
fileWritter.println();
}
catch (FileNotFoundException e){
e.printStackTrace();
}
return numbers;
}
As an edit you can make the writeArray() function return void if you don't need the files after.
This is a program that takes these three arrays and sorts them using insertion sort and counting the number of comparisons and swaps performed for each array when sorted.
I'm now trying to test three other arrays that have been made on text files. The these three text files are just lists of numbers, the first text file is called "array4.txt" and its list of numbers contains 1 through 2000 in order.
The second file is called "array5.txt" and its list of numbers contains 2000 through 1 in descending order. Lastly, the third file is called "array6.txt" and its list of numbers contains a list of randomly mixed numbers from 1 to 2000, including 1 and 2000 with no repeats.
My goal is to read these files and put their values into an actual array and for my insertion sort method to read them, sort them, and count the number of comparisons and exchanges just as what I did with my first three arrays.
I'm very new to Java and don't know exactly how to do this.
import java.util.Scanner;
import java.io.*;
public class InsertionSort
{
public static void main(String args[]) throws IOException
{
int[] Array = {1,2,3,4,5,6,7,8,9,10};
int[] Array2 = {10,9,8,7,6,5,4,3,2,1};
int[] Array3 = {1,10,2,9,3,8,4,7,5,6};
System.out.println("Insertion Sort: ");
System.out.println();
System.out.println("Best Case Scenario: ");
printArray(Array);
insertionSort(Array);
System.out.println("Worst Case Scenario: ");
printArray(Array2);
insertionSort(Array2);
System.out.println("Average Case Scenario: ");
printArray(Array3);
insertionSort(Array3);
}
public static void insertionSort(int[] list)
{
int comps = 0, swaps = 0;
for(int i = 1; i < list .length; i++) {
int j = i;
// compare i with sorted elements and insert it
// sorted elements: [0..i-1]
while (j > 0 && list[j] < list[j - 1]) {
int temp = list[j];
list[j] = list[j - 1];
list[j - 1] = temp;
swaps++;
comps++; // loop condition true
j--;
}
comps++; // checking loop condition when false
}
//printArray(list);
System.out.println("Comparisons: " + comps
+ " Swaps: " + swaps);
System.out.println();
}
static void printArray(int[] array){
for(int i=0; i < array.length; i++)
{
System.out.print(array[i] + " ");
}
System.out.println();
}
}
This is what I came up with. Hope it helps!
package com.company;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
// Replace array.txt with the name of your txt file and your path
Scanner fileScanner = new Scanner(new File("array.txt"));
// Counter variable so we'll know the size of the array we'll need
int counter = 0;
// Iterate through the file counting the number of integers and incrementing the counter variable
while(fileScanner.hasNextInt()){
counter++;
fileScanner.nextInt();
}
// Reset the scanner to the beginning of the txt file
fileScanner = new Scanner(new File("array.txt"));
// Scan each integer into the array
int [] array = new int[counter];
for (int i = 0; i < array.length; ++i) array[i] = fileScanner.nextInt();
}
}
Here you go:
public void getIt() {
List<Integer> ints = new ArrayList(); //temporary holder
try (Scanner scanner = new Scanner("filename.txt")) { //open a scanner that will scan our file
scanner.forEachRemaining(line -> { //iterate through each line in our file
String[] numberStrings = line.split(","); // the comma is your presumed delimeter IF one exists
for (int x = 0; x < numberStrings.length; x++) { // loop through each item separated by a comma on each line
ints.add(Integer.parseInt(numberStrings[x])); // turn this string into an int and add it to your list
}
});
}
Integer[] integerArray = ints.toArray(new Integer[ints.size()]); //transform our list into an array
}
If it's only one number per line you don't need the for loop or the line.split inside of the forEachRemaining
This is supposed to be a Sudoku Puzzle solver and it is required I use a two dimensional ArrayList for the puzzle.
I'm trying to fill an ArrayList using numbers from a txt file. The code in my test class can make a 9x9 ArrayList and fill it with numbers 1-9 using the loop I made to test how filling a two dimensional ArrayList works.
import java.util.*;
import java.io.*;
public class test
{
public static void main(String args[])
{
ArrayList<ArrayList<Integer>> data = new ArrayList<ArrayList<Integer>>();
//Loop to add 9 rows
for(int i=1; i<=9; i++)
{
data.add(new ArrayList<Integer>());
}
//Loop to fill the 9 rows with 1-9
for(int k=0; k<9; k++)
{
for(int j=1; j<=9; j++)
{
data.get(k).add(j);
}
}
//Loop to print out the 9 rows
for(int r=0; r<9; r++)
{
System.out.println("Row "+(r+1)+data.get(r));
}
//Reads the file. Need to use this to set the array
File file = new File("F:\\Data Structures 244\\FINAL PROJECT\\SudokuSolver\\sudoku.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
My problem comes when I try to take the numbers I have stored in the txt file and use them to fill the ArrayList in the order they are read. I tried this code so that it would read the number from the txt file and place it into the ArrayList by having it repeat so it would do the first 9 numbers from the txt file into the first row of the ArrayList and then go to the next row in the txt file as well as the ArrayList to fill those numbers.
File file = new File("F:/Data Structures 244/FINAL PROJECT/SudokuSolver/sudoku.txt");
//Needs this try and catch
try {
Scanner solutionFile = new Scanner(file);
int cell=0;
while (solutionFile.hasNextInt())
{
//Loop to fill the 9 rows with the numbers from the sudoku.txt
for(int k=0; k<9; k++)
{
for(int j=1; j<=9; j++)
{
cell = solutionFile.nextInt();
data.get(k).add(cell);
}
}
}
solutionFile.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
for(int r=0; r<9; r++)
{
System.out.println("Row "+(r+1)+data.get(r));
}
I get an Exception in thread "main" java.util.NoSuchElementException
with this line cell = solutionFile.nextInt();
This is the sudoku.txt file
346791528
918524637
572836914
163257489
895143762
427689351
239415876
684372195
751968243
I tried it like that at first and get that error but then I try taking all of the numbers and putting them on one line so my for loops will only read them 9 numbers at a time but when I test to print the ArrayList or what should be in it after it adds them the entire ArrayList is blank.
What is the problem with it not reading the numbers from the file and putting them into the ArrayList so it will print?
An integer can be more than one character. You're reading the entire line as a single number and then failing after you finish the nine reads (1 for each line).
You can reformat your text file so that the numbers are broken up: (I believe a space will work if not a new line definitely will)
so like
3 4 6 7 9 1 5 2 8
...
Or you can read the whole number and parse it yourself
int temp = solutionFile.nextInt();
for(int i = 8; i > 0; i--) {
int cell = temp / (10 * i);
data.get(k).add(cell);
}
//add the last cell
int cell = temp % 10;
data.get(k).add(cell);
Or you could read the value as a string and parse it
String line = solutionFile.next();
for(int i = 0; i < line.length; i++) {
Integer cell = Integer.parseInt(line.substring(i, i+1));
data.get(k).add(cell);
}
This isn't a valid way to print a list of numbers (ArrayList's toString doesn't print the list for you you have to do it manually)
for(int r=0; r<9; r++)
{
System.out.println("Row "+(r+1)+data.get(r));
}
Should be something like
for(int r = 0; r < data.size(); r++)
{
System.out.print("Row " + (r+1) + ": ");
for(Integer num : data.get(r)) {
System.out.print(num + " ");
}
System.out.println(); //to end the line
}