I keep getting this error when reading from a text file it gets the first few numbers but then does this there also shouldnt be 0's in there, tried a lot of things not sure what to do. I have to be able to read the file numbers and then multiply specific ones could use some help thanks. (I was using the final println to check what numbers it was getting). Sorry forgot the error is this output
4
32
0
38
0
38
0
16
0
Error: For input string: ""
Here is my file:
Unit One
4
32 8
38 6
38 6
16 7
Unit Two
0
Unit Three
2
36 7
36 7
Unit Four
6
32 6.5
32 6.5
36 6.5
36 6.5
38 6.5
38 6.5
Unit Five
4
32 6.5
32 8
32 7
32 8
Unit Six
5
38 7
30 6.5
24 8
24 8
24 8
Unit Seven
0
Unit Eight
1
40 12
Unit Nine
5
24 8
24 6.5
30 6.5
24 7
32 7
And here is my code:
package question;
import java.io.*;
import java.util.Scanner;
public class Weight
{
public static void main(String[] args)//main method
{
try
{
Scanner input = new Scanner(System.in);
//System.out.print("Please enter proposed weight of stock : ");
// int proposedWeight = input.nextInt();
File file = new File("MathUnits.txt");
System.out.println(file.getCanonicalPath());
FileInputStream ft = new FileInputStream(file);
DataInputStream in = new DataInputStream(ft);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strline;
while((strline = br.readLine()) != null)
{ int i = 0;
if (strline.contains("Unit"))
{
continue;
}
else {
String[] numstrs = strline.split("\\s+"); // split by white space
int[] nums = new int[numstrs.length];
nums[i] = Integer.parseInt(numstrs[i]);
for(int f = 0; f <numstrs.length; f++)
{
System.out.println(""+ nums[f]);
}
}
i ++;
}
//int x = Integer.parseInt(numstrs[0]);
// int m = Integer.parseInt(numstrs[1]);
// int b = Integer.parseInt(numstrs[2]);
// int a = Integer.parseInt(numstrs[3]);
int a = 0;
// System.out.println("this >>" + x + "," + m +"," + b + "," + a);
// if(proposedWeight < a)
// {
// System.out.println("Stock is lighter than proposed and can hold easily");
// System.exit(0);
// }
// else if ( a == proposedWeight)
// {
// System.out.println("Stock is equal to max");
// System.exit(0);
// }
// else
// {
// System.out.println("stock is too heavy");
// System.exit(0);
// }
in.close();
}
catch(Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
}
One probable error I see
You're not taking newlines into consideration, especially when you're doing a nums[i] = Integer.parseInt(numstrs[i]); on an empty string
Also, I don't think you're getting the numbers into the array correct since you're getting only one int from each line, when some lines have two
Related
I need load file .txt with strings and int.
When it is loaded, the program prints the sum of ASCII values that was calculated using a method (I wrote already). My problem is sum all The strings and int.
It necessary to sum all rows, except the last line that shows the sum in ASCII.
NOTICE: There is 2 groups (colors) with same info
This the file. In yellow is the sum of all the info in .txt
My code:
System.out.println("Enter Path To File:");
File fileName = new File("Game.txt");
Scanner sFromFile = new Scanner(fileName);
String size = sFromFile.nextLine();
int sizeBoard = Integer.parseInt(size);System.out.println("Board size loading size= "+size+"X"+size);
String team = sFromFile.next();
// int numOfSoliders = sFromFile.nextInt();
Point arrSol []= new Point[sizeBoard];for(
int i = 0;i<arrSol.length;i++)
{
arrSol[i] = new Point(sFromFile);
System.out.println("Solider created successfully!");
}
// int numOfDragon = sFromFile.nextInt();
Point arrDragon[] = new Point[sizeBoard];for(
int i = 0;i<arrDragon.length;i++)
{
arrDragon[i] = new Point(sFromFile);
System.out.println("Dragon created successfully!");
}
// ALSO DID THE SAME TO OTHER GROUP...
// THE LAST LINE READING INPUT
int fileHashCode = sFromFile.nextInt();System.out.println("HashCode loading...\n Loaded hashCode= "+fileHashCode);
// TRY USE STRING METHOD
// while (sFromFile.hasNext()) {
// String str = sFromFile.nextLine();
// System.out.print(str + ". ");
// }
sFromFile.close();
// ALSO TRY OUTSIDE METHOD
public static String readFile(String fName) throws FileNotFoundException {
File f = new File(fName);
Scanner sFromFile = new Scanner(f);
for (int i = 0; i < board.length; i++) {
while (sFromFile.hasNext()) {
String str= sFromFile.nextLine();
String sum+=str;
// System.out.print(str + ". ");
}
}
sFromFile.close();
return sum;
}
It means to sum all characters (except line breaks) of the first 7 lines of text.
Proof
String input = "8\r\n" +
"RED\r\n" +
"8 0 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7\r\n" +
"8 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7\r\n" +
"BLUE\r\n" +
"8 7 0 7 1 7 2 7 3 7 4 7 5 7 6 7 7\r\n" +
"8 6 0 6 1 6 2 6 3 6 4 6 5 6 6 6 7\r\n" +
"6139";
try (Scanner sc = new Scanner(input)) {
int sum = 0;
for (int i = 0; i < 7; i++)
sum += sc.nextLine().chars().sum();
System.out.println("Calculated: " + sum);
System.out.println("Last line : " + sc.nextLine());
}
Output
Calculated: 6139
Last line : 6139
This question already has answers here:
Reading only the integers from a txt file and adding the value up for each found
(5 answers)
Closed 5 years ago.
I'm working on a project that reads in grades from a file but the file contains student names and the class they are in as well, some have 3 grades and some have 4. I'm struggling with getting a divide by 0 error when I try to run the program and cant figure it out after much googling, beginner with java. I'm fine with opening the file but I'm struggling with how to get it to read the average of the first line then continue to all the other ones as well returning the value in the println.
File contents(with three grades):
//Happy CS145 81 85 91
//Sneezy CS145 67 75 75
//Doc CS145 92 97 89
//Dopey CS111
//Grumpy CS145 75 65 66
//Bashful CS145 81 82 81
//Sleepy CS145 71 74 71
import java.io.FileReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class MainClass {
public static void main(String args[]){
int numTestScores = 0;
int sum = 0;
int average = 0;
Scanner input = null;
try {
input = new Scanner(new File("PA2data2.txt"));
} catch (FileNotFoundException ex) {
System.out.println("Cannot open file - " + ex);
}
while (input.hasNext()) {
while (input.hasNextInt()){
sum += input.nextInt();
numTestScores++;
}
average = sum / numTestScores;
System.out.println(average);
}
System.out.println("Average is " + sum / numTestScores);
input.close();
}
}
You should use nextLine() rather than nextInt()
while (input.hasNext()) {
String line = input.nextLine();
String[] brokenLine = line.split(" ");
//do stuff with your array of {Happy, CS145, 81, 85, 91}
...
...
}
Also, your also going to want to use doubles rather than int for average, you will get average of 0 otherwise.
Just keep your division operation inside an if statement:
if(numTestScores > 0) {
average = sum / numTestScores;
System.out.println(average);
}
I just want to preface this by saying that I am a coding noob. This is probably the most advanced code I have written.
I am trying to test numbers in the Collatz conjecture. My input variable is supposed to increase by 1 after the loop gets to 1. If it isn't 1, then it goes to the other 2 functions. If the number is even, it is divided by 2. If it is odd it is multiplied by 3 and has 1 added to it.
The reason this math equation is so interesting is that we do not know if all numbers get too one given enough times run through this equation.
I also know that there is no break; in the loop, but that is not the problem. My problem is the output. Here is my code:
public class class1 {
static int output = 0;
static int input = 1;
static int turn = 0;
public static void main(String[] args) {
output = input;
for (;;) {
if(input != 1){
if (input % 2 == 0) {
even(input);
System.out.println("output = " + input + " turn = " + turn);
} else if (input % 2 == 1) {
odd(input);
System.out.println("output = " + input + " turn = " + turn);
}
}else{
System.out.println("done in " + turn + " turns");
turnsTested++;
turn = 0;
output = input;
}
turn++;
}
}//end main
public static int even(int input2) {
input = input / 2;
return input;
}
public static int odd(int input2) {
input = (input * 3);
input++;
return input;
}
}//end class
The Output for a run of this code below:
output = 2734 turn = 105
output = 1367 turn = 106
output = 4102 turn = 107
output = 2051 turn = 108
output = 6154 turn = 109
output = 3077 turn = 110
output = 9232 turn = 111
output = 4616 turn = 112
output = 2308 turn = 113
output = 1154 turn = 114
output = 577 turn = 115
output = 1732 turn = 116
output = 866 turn = 117
output = 433 turn = 118
output = 1300 turn = 119
output = 650 turn = 120
output = 325 turn = 121
output = 976 turn = 122
output = 488 turn = 123
output = 244 turn = 124
output = 122 turn = 125
output = 61 turn = 126
output = 184 turn = 127
output = 92 turn = 128
output = 46 turn = 129
output = 23 turn = 130
output = 70 turn = 131
output = 35 turn = 132
output = 106 turn = 133
output = 53 turn = 134
output = 160 turn = 135
output = 80 turn = 136
output = 40 turn = 137
output = 20 turn = 138
output = 10 turn = 139
output = 5 turn = 140
output = 16 turn = 141
output = 8 turn = 142
output = 4 turn = 143
output = 2 turn = 144
output = 1 turn = 145
done in 146 turns
So I have an error. I can't find my problem.
if (input % 2 == 0) {
// transforming a primitive method argument in a function is
// *NOT* reflected on the variable passed as argument:
// a call to the function will pass *the value* of the variable
// and not the reference to the variable
input = even(input);
System.out.println("output = " + input + " turn = " + turn);
} else if (input % 2 == 1) {
// see above
input = odd(input);
System.out.println("output = " + input + " turn = " + turn);
}
Edit
Here is the updated code, I got the string to be loaded up with the matches but now how do I match the strings with the second file.
The strings contain this for reference:
String 1
1913 2016 1 1913 186 2016 1711 32843 2016 518
3 1913 32843 32001 4 250 5 3500 6 7
8 27 73 9 10 1711 73 11 2
12 1913 19 1930 20 21 1947
22 1955 23 1961 23 1969 27 1995 26 27
1962 28 29 30 1970 31 31
String 2
1.4 33.75278 84.38611
And I need to see how many times each number matches with this string
1913
2016
32843
31
27
1.4
4
7
2
23
public static void main(String[] args) throws FileNotFoundException {
Scanner INPUT_TEXT = new Scanner(new File("C:\\Users\\josep\\OneDrive\\Classes\\Programming\\assignment3_1.txt"));
INPUT_TEXT.useDelimiter(" ");
int count = 0;
ArrayList<String> integerInFirstFile =new ArrayList<>();
ArrayList<String> decimalsInFirstFile =new ArrayList<>();
while (INPUT_TEXT.hasNext()) {
String TempString = INPUT_TEXT.next();
String temp1 = TempString.replaceAll("[\\,]", "");
String pattern1 = "[0-9]+\\.{1}[0-9]+";
Pattern r1 = Pattern.compile(pattern1);
Matcher m1 = r1.matcher(temp1);
String pattern2 = "[0-9]+";
Pattern r2 = Pattern.compile(pattern2);
Matcher m2 = r2.matcher(temp1);
if (!(m1.find())) {
while (m2.find()) {
count++;
String number = m2.group(0);
integerInFirstFile.add(number);
if (count % 10 == 0) {
System.out.println(number);
} else
System.out.print(number + " ");
}
} else {
count++;
String number = m1.group(0);
decimalsInFirstFile.add(number);
System.out.println("Next File");
if (count % 10 == 0) {
System.out.println(number);
} else
System.out.print(number + " ");
}
}
Scanner INPUT_TEXT2 = new Scanner(new File("C:\\Users\\josep\\OneDrive\\Classes\\Programming\\assignment3_2.txt"));
INPUT_TEXT2.useDelimiter(" ");
System.out.println("");
System.out.println("Next File");
while (INPUT_TEXT2.hasNext()) {
String TempString1 = INPUT_TEXT2.next();
if (decimalsInFirstFile.equals(TempString1) || integerInFirstFile.equals(TempString1)) ;
{
System.out.println(TempString1);
}
}
INPUT_TEXT.close();
INPUT_TEXT2.close();
}
}
The first file contains a bunch of text and numbers that why I had to use the matcher to remove the commas and other text. My question is how do I then match to the other text file and display how many times a number in the 2nd file appears in the first file. Do I use the match class or do I use .match nextLine or something similar. Also where is the best place to put in the code, I don't want to mess up the loops already in place.
Once you got one number, store it for a future use, don't just display it.
Scanner INPUT_TEXT = new Scanner(new File("C:\\Users\\josep\\Downloads\\assignment3_1.txt"));
INPUT_TEXT.useDelimiter(" ");
int count=0;
// ** Creating the storage for the numbers (as strings)
ArrayList<String> numbersInFirstFile=new ArrayList<>();
Then when you find one, store it:
while(INPUT_TEXT.hasNext()){
String TempString=INPUT_TEXT.next();
String temp1 = TempString.replaceAll("[\\,]", "");
// other things that are needed where here, put them back
if(!(m1.find())){
while(m2.find( )) {
count++;
String number = m2.group(0);
// *********************************
// Hey, I found one, let's store it:
numbersInFirstFile.add(number);
// Do the same in other places where you find numbers in the first file
As you now have the numbers in the first file, whenever you get a number from the second file, you have something to search into.
I wrote this code that was intended to read a file with integer values. If the integer values are >= 0 and <=100 I need to give the average of the grades. If there are any values out of the specified range 0-100 then I need to count the incorrect integer grades, inform the user of the incorrect grades, and inform how many incorrect grades there were. I attempted the code but I keep getting the error code:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Project9.main(Project9.java:26)
Code sample:
public static void main(String[] args) throws IOException{
String file;
int readInts;
Scanner k = new Scanner(System.in);
System.out.println("Enter filename: ");
file = k.nextLine();
int counterWrong = 0;
int counterRight = 0;
int sum = 0;
double average = 1.0 * sum/counterRight;
File fileReader = new File(file);
if (fileReader.exists()) {
Scanner input = new Scanner(fileReader);
while (input.hasNext()) {
readInts = input.nextInt();
System.out.println(readInts);
String a = input.next();
int a2 = Integer.parseInt(a);
if (a2 <= 100 && a2 >= 0){
counterRight++;
sum = sum + a2;
System.out.println("Score " + a2 + " was counted.");
} else {
counterWrong++;
System.out.println("The test grade " + a2 + " was not scored as it was out of the range of valid scores.");
System.out.println("There were " + counterWrong + " invalid scores that were not counted.");
}
}
if (counterRight > 0){
System.out.println("The average of the correct grades on file is " + average + ".");
}
} else {
System.out.println("The file " + file + " does not exist. The program will now close.");
}
}
}
You are doing a single check hasNext but then you read twice from scanner using nextInt() and next().
There may be two issues with your code I see.
file = k.nextLine(); // Depending on how your file is set up k.nextLine() or k.next() or maybe k.nextInt() may be useful.
while (input.hasNext()) {
readInts = input.nextInt(); // input.hasNext() assumes the next value the scanner is reading has a string value which would make readInts = input.nextInt(); impossible to use without parsing (or some other method).
I thought it'd be fun to try out this exercise (didn't want to ruin it for you). Check out my code and hopefully you'll pick up on some of the concepts I was talking about.
Note: My program reads integer values like 95 185 23 13 90 93 37 125 172 99 54 148 53 36 181 127 85 122 195 45 79 14 19 88 34 73 92 97 200 167 126 48 109 38. Which uses hasNext() & next() to get every token listed. So using nextLine() wouldn't be useful for the given input.
package cs1410;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JFileChooser;
public class Grader {
public static void main(String[] args) throws IOException {
int count = 0;
int sum = 0;
double ave = 0;
int incorrectCount = 0;
String correctGrades = "";
String incorrectGrades = "";
// Read file input
JFileChooser chooser = new JFileChooser();
if (JFileChooser.APPROVE_OPTION != chooser.showOpenDialog(null)) {
return;
}
File file = chooser.getSelectedFile();
// Scan chosen document
Scanner s = new Scanner(file);
// While the document has an Int
while (s.hasNextInt()) {
// Convert our inputs into an int
int grade = Integer.parseInt(s.next());
if (grade >= 0 && grade <= 100) {
// adds sum
sum += grade;
// increments correct count
count++;
// displays valid grades
correctGrades += Integer.toString(grade) + "\n";
} else {
// increments incorrect count
incorrectCount++;
// displays invalid grades
incorrectGrades += Integer.toString(grade) + "\n";
}
}
// Created average variable
ave = sum / count;
// bada bing bada boom
System.out.println("The number of correct grades were " + correctGrades);
System.out.println("The average score on this test was " + ave + "\n");
System.out.println("The number of incorrect grades were " + incorrectCount + "\n");
System.out.println("The incorrect values for the grades were " + "\n" + incorrectGrades);
}
}
Use hasNextInt() instead of hasNext().
hasNext() only means there is another token, not necessarily that there is another integer which you are assuming when you wrote nextInt().
Here's the documentation for hasNext() and hasNextInt()
You also want to do a check before this line:
String a = input.next();