JavaFX InputMismatchException - Label from Scanner - java

problems will be there cause i want make Labels from text file and then put it into VBOX and i getting inputmismatchexception and it dont make new Object
VBox vertikalBox = new VBox();
try (Scanner s = new Scanner("rebricek.txt")) {
while (s.hasNext()) {
//InputMismatchException
vertikalBox.getChildren().addAll(new Label(""+ s.nextInt() + " " + s.next() + " " + s.nextInt()));
s.nextLine();
}
} catch (Throwable t) {
// inputmismatchexception - PROBLEM
// this is for NoSuchElementException
System.err.println("Vyskytla sa chyba pri praci zo suborom");
}
FILE content :
1 nikto 10
2 nikto 0
3 nikto 0
4 nikto 0
5 nikto 0
6 nikto 0
7 nikto 0
8 nikto 0
9 nikto 0
10 nikto 0

Your scanner is reading the string "rebrickek.txt" not a file
File file = new File("rebricek.txt");
if(file.exist())
{
Scanner s = new Scanner(file);
.
.
.
}
else
{
System.out.println("The file does note exist!");
}

Related

Java read .txt file and sum the strings/int value in ASCII

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

Parsing input file

This is my input file:
0 I 4325 <4214, 6> <4718, 9> <1203, 11>
18 L 4214 12 <4325, 6> <4718, 5> <1483, 9>
35 F 4109
I am trying to write a method that will read in the first column, second column (either I, L or F) and store all the pairs in each row e.g., (4214, 6), (4718, 9). What I've done is used the delimiter from the scanner class to get rid of '<', ',' and '>', and it does but when I try calling temp.next(), I keep on getting an error. My code is below (sometime the error goes away when I use skip(" "):
public void parseFile(Scanner input) {
int prevSeqNo = -1;
while (input.hasNextLine()) {
String line = input.nextLine();
if (!line.startsWith("#") && !line.isEmpty()) { // ignore comments
// and blank lines
Scanner temp = new Scanner(line).useDelimiter("<|,| |>"); // ignore all '<', ',' and '>'
// while(temp.hasNext())
// System.out.print(" " + temp.next() );
// System.out.println();
int timeStamp = temp.nextInt();
System.out.println("Timestamp: " + timeStamp);
temp.skip(" ");
String event = temp.next();
System.out.println("Event: " + event);
if (event.equals("I")) {
temp.skip(" ");
startNode = temp.nextInt();
System.out.println("starting node: " + startNode);
// while (temp.hasNext()) {
temp.skip(" ");
int node = temp.nextInt();
System.out.println(node);
temp.skip("");
int weight = temp.nextInt();
System.out.println(weight);
// System.out.println("<" + node + ", " + weight + ">");
// }
} else if (event.equals("L")) {
int currSeqNo = temp.nextInt();
System.out.println("Sequence number: " + currSeqNo); // discard if LSP has smaller or equal sequence number to max seen so far
if (currSeqNo >= prevSeqNo) {
prevSeqNo = currSeqNo; // update the previous sequence
// number
} else { // else if event == "F"
}
}
}
}
input.close();
}
After removing symbols:
0 I 4325 4214 6 4718 9 1203 11
18 L 4214 12 4325 6 4718 5 1483 9
29 L 4109 78 4718 3 1483 2
35 F 4109
Here is the error message:
Timestamp: 0
Event: I
starting node: 4325
4214
java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
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 LinkedStateRouting.parseFile(LinkedStateRouting.java:41)
at LinkedStateRouting.main(LinkedStateRouting.java:88)

How to count valid and invalid lines in file

I have the following code:
public class generator {
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(new File("results.txt"));// creates a scanner to
// scan from a file
String line;
String HomeTeam, AwayTeam;
while (s.hasNext()) {
line = s.nextLine(); // reads the next line from the file
line = line.trim(); // trims the line
String[] elements = line.split(":"); // splits the line
if (elements.length == 4) {
HomeTeam = elements[0].trim(); // trims home team
AwayTeam = elements[1].trim(); // trims away team
elements[2] = elements[2].trim();
elements[3] = elements[3].trim();
if (HomeTeam.length() != 0 && AwayTeam.length() != 0) { // check if position is present
try { // "try" is a special statement which allows us to deal with "exceptions"
int HomeScore = Integer.parseInt(elements[2]); // attempt to convert the String into an Integer type value
int AwayScore = Integer.parseInt(elements[3]);
System.out.println(HomeTeam + " ["+ HomeScore +"]" + " | " + AwayTeam + " ["+AwayScore+"]");
}
catch (NumberFormatException e) {
}
}
}
}
}
}
Now my question is: how do I count the valid and invalid lines as well as total number of score in entire file?
Sample input file is:
Leeds United : Liverpool : 1 : 2
Chelsea : Manchester City : 1 : 1
Aston Villa : Middlesbrough : 3 : 1
Tottenham Hotspur : Stoke City : 0 : 0
West Ham United : Wigan Athletic :2 : 1
Fulham : Liverpool : 1 : 2
Wigan Athletic : Leeds United : 2 : 2
Arsenal Liverpool :2:2
Hull City: Tottenham Hotspur : 3 : 5
Everton : Portsmouth:4 : 2
Stoke City : West Bromwich Albion : 5 : 4
Leeds United : Liverpool : 1: 10
Blackburn Rovers : Fulham : 1 : 1
West Ham United : Newcastle United : 0 : 0
Manchester United : Wigan Athletic : 1 : 2
Hull City : Sunderland : 2 : 3
Chelsea : Manchester City :1
Fulham : Leeds United : 1 : 2
Wigan Athletic : Tottenham Hotspur : 2 : 2
Hull City : Everton : 3 : 5
: :2:0
Sunderland : Blackburn Rovers : 4 : 2
Stoke City : West Bromwich Albion : 5 : 4
Hull : Liverpool : 5: x
Blackburn Rovers : Fulham : 1 : 1
Chelsea : Everton : a : 1
Sunderland : Newcastle United : 0 : 0
Hull : :2:3
Sunderland : Blackburn Rovers : 1 : 2
Hull City : Everton : 2 : 3
Leeds United : Chelsea : 1 : 2
Chelsea : Manchester City : 1 : 1
Aston Villa:Fulham:3:1
Manchester City : Stoke City : 0 : 0
West Ham United : Middlesbrough : 2 : 1
Actually You check validity so what's the problem with counting? Create two variables: ValidNumb and InvalidNumb. Increase ValidNumb after System.out.println(). Increase InvalidNumb if elements.length not equal 4, lenght of team names equal 0 or You catch exception during conversions scores to integers.
To count all scores: create one more variable allScores and add them to HomeScore and AwayScore in try block.
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(new File("results.txt"));// creates a scanner to
// scan from a file
String line;
String HomeTeam, AwayTeam;
Int ValidNumb = 0, InvalidNumb = 0; //counters of valid and invalid lines
Int AllScores = 0; //sum of all goals
while (s.hasNext()) {
line = s.nextLine(); // reads the next line from the file
line = line.trim(); // trims the line
String[] elements = line.split(":"); // splits the line
if (elements.length == 4) {
HomeTeam = elements[0].trim(); // trims home team
AwayTeam = elements[1].trim(); // trims away team
elements[2] = elements[2].trim();
elements[3] = elements[3].trim();
if (HomeTeam.length() != 0 && AwayTeam.length() != 0) { // check if position is present
try { // "try" is a special statement which allows us to deal with "exceptions"
int HomeScore = Integer.parseInt(elements[2]); // attempt to convert the String into an Integer type value
int AwayScore = Integer.parseInt(elements[3]);
AllScores = AllScores + HomeScore + AwayScore; //sum up scores
System.out.println(HomeTeam + " ["+ HomeScore +"]" + " | " + AwayTeam + " ["+AwayScore+"]");
ValidNumb++; //line is valid
}
catch (NumberFormatException e) {
InvalidNumb++; //scores are not integers
}
}
else {InvalidNumb++;} //HomeTeam or AwayTeam are empty
}
else {InvalidNumb++;} //not enough elements in line
}
}
So you would need counter variables for every metrics that you need.So before your while loop define them as:
int totalAwayScore = 0, totalHomeScore = 0, invalidLines = 0, totalLines = 0;
Within while loop, increment totalLines as
totalLines++;
which means you have next line to read. Your try catch is where you know how much is score so keep on adding to metrics that you defined above like:
try { // "try" is a special statement which allows us to deal with "exceptions"
int HomeScore = Integer.parseInt(elements[2]); // attempt to convert the String into an Integer type value
int AwayScore = Integer.parseInt(elements[3]);
totalAwayScore += AwayScore;
totalHomeScore += HomeScore;
System.out.println(HomeTeam + " ["+ HomeScore +"]" + " | " + AwayTeam + " ["+AwayScore+"]");
} catch (NumberFormatException e) {
invalidLines++;
}
Here if you get number format exception, you get to know that it's invalid line and hence increment the value of variable that holds invalid lines in a file.
At the end of the while loop you print the stats like:
System.out.println("Total home score is " + totalHomeScore + " totalAway score is " + totalAwayScore + " invalid lines were " + invalidLines + " of total " + totalLines);
I'm not sure I understood but:
you need to increment a counter of invalid lines in the catch
section. It indicates that the line is wrong because the number is
not a number;
you need to increment a counter of invalid lines in an else section
of the if
if (elements.length == 4)
it means that you have too much or too many arguments;
you need to increment a counter of invalid lines if HomeTeam and
AwayTeam are =="" because you don't have the name of the team;
Cheers
You can add two counters - one for all (allCounter) and one for wrong lines (wrongCounter):
at the beginning of every loop iteration increment allCounter:
while (s.hasNext()) {
allCounter++;
line = s.nextLine(); // reads the next line from the file
...
if something is wrong, increment wrongCounter and continue to next iteration of loop
if (elements.length != 4) {
++wrongCounter;
continue; //breaks this iteration and moves to next one
}
//otherwise proceed normally
homeTeam = elements[0].trim(); // trims home team
awayTeam = elements[1].trim(); // trims away team
...
Similarly in second if and catch clause:
catch (NumberFormatException e) {
++wrongCounter;
}
And of course:
int correctCounter = allCounter - wrongCounter;
One more thing: By Java convention you should write all variable/method names with camelCase, i.e start with small letter and then start every new word with capital letter:
Example: not HomeTeam, but homeTeam

Error when reading from text file

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

Saving the result to file - JAVA

I have a very stupid problem... I cannot get know how to save the results in output file that second array is save in a lower line.
This is how it saves:
dist[0 10 13 10 6 18 ] pred[-15 2 5 1 4 ]
I want it to save like this:
dist[0 10 13 10 6 18 ]
pred[-15 2 5 1 4 ]
CODE:
try{
outputFile = new File("Out0304.txt");
out = new FileWriter(outputFile);
out.write("\n" + "dist[");
out.write("\n");
for (Top way : tops){
out.write(way.shortest_path + " ");
}
out.write("]\n");
out.write("\n");
out.write("\n" + "pred[");
for (Top ww : tops){
if (ww.previous != null) {
out.write(ww.previous.number + " ");
}
else{
out.write("-1");
}
}
out.write("] \n ");
out.close();
}
catch (IOException e){
System.out.println("Blad: " + e.toString());
}
}
}
In Windows you need "\r\n" for new line
You can use the following to write to file:
PrintWriter pw = new PrintWriter(new FileWriter("fileName"),true);
pw.println("[");
for(int i=0;i<pred.length;i++)
{
pw.println(pred[i]+" ");
}
pw.println("]");
pw.close();

Categories

Resources