Why does it print the file it reads on a single line? The txt file is not.
The file is like this:
Student N. 3
ID: 999
Surname: Spider
Name: Man
************
Subject N. 1 : d. Chart Reading
Homework 1: 89
Homework 2: 65
Homework 3: 32
Exam 1: 45
Exam 2: 56
Exam 3: 78
public static void main(String[] args) throws Exception {
Scanner data = new Scanner(new FileReader("StudData1.txt"));
while(data.hasNextLine())
{
System.out.print(data.nextLine());
}
Change System.out.print() to System.out.println() if you want to print in different line.
You should know the difference between these two. Follow this link.
Related
I'm reviewing practice assignments working up to my final and one thing my professor had us do was create and use a student class. Below I provided my code and what's in the text file I'm reading from.
String inputFileName = "quizScore.txt";
File inputFile = new File(inputFileName);
Scanner fileIn = new Scanner(inputFile);
ArrayList<Student> students = new ArrayList<Student>();
//Skip first two lines
fileIn.nextLine();
fileIn.nextLine();
int i =0;
while (fileIn.hasNextLine()){
//skip first number
fileIn.nextInt();
//Add student with quiz score
String newStudent = fileIn.next();
int quizScore = fileIn.nextInt();
Student student = new Student(newStudent);
students.add(student);
//Add quiz score
student.addQuiz(quizScore);
i++;
}
Skip this line
And this line
1 Michael 285
2 Christopher 236
3 Joshua 230
4 Brandon 208
5 Jacob 202
6 Daniel 196
7 Matthew 193
8 Anthony 188
9 Andrew 172
10 Joseph 171
I wrote the class but when I try to implement the class its says NoSuchElementException in the while loop for the fileIn.nextInt(); that's suppose to skip the line number. I don't know why it's giving me that exception. If I do a print statement to see if there is an int there is. Which is why I'm confused I get an error.
Change the condition of the while loop to fileIn.hasNextInt(). That way, if your file has a new line at the end, your loop will stop when the next line does not start with an integer.
Also you don't seem to be using the value of your i variable anywhere. You may want to get rid of it, unused variables are never a good idea.
I have been running through this array of objects trying to figure out what I am doing wrong and I can't see the error. This program runs through the first iteration bringing in Austria and all its subsequent information but will not move onto the second part of the array. I thought it might be that it's somehow taking each variable from the countries class and making it its own spot in the array but that can't be it because I have increased the array size to 64 and it still stops at the end of Austria. I have been able to get it to go a bit further by placing print statements after each item is added and it seems to be adding an unaccounted for blank line in it for some reason and I'm not sure why. any help that could be given would be greatly appreciated.
This is my test code with the data list:
import java.util.Scanner;
import java.io.*;
public class Test {
public static void main (String [] args) throws IOException {
final String INPUT_FILE = "CountriesInfo2.txt";
FileReader inputDataFile = new FileReader (INPUT_FILE);
Scanner read = new Scanner (inputDataFile);
Countries[] c = new Countries[8];
for (int i = 0; i < c.length; i++) {
c[i] = new Countries();
c[i].countryName = read.nextLine();
c[i].latitude = read.nextLine();
c[i].longitude = read.nextLine();
c[i].countryArea = read.nextInt();
c[i].countryPopulation = read.nextInt();
c[i].countryGDP = read.nextDouble();
c[i].countryYear = read.nextInt();
sop ("" + c[i].countryName + "\n" + c[i].latitude+"\n"+c[i].longitude+"\n"+c[i].countryArea+"\n"+
c[i].countryPopulation+"\n"+c[i].countryGDP+"\n"+c[i].countryYear);
}// end for
} // End Main
public static void sop (String s) {
System.out.println(s);
} // End sop
} // end class
Austria
47 20 N
13 20 E
83871 8754513 417.2 2016
Belgium
50 50 N
04 00 E
30528 11491346 509.5 2016
Czech Republic
49 45 N
15 30 E
7886
10674723
350.7
2016
France
46 00 N
02 00 E
643801
67106161
2734.0
2016
This list is supposed to be one line for each bit of information with lat-long having 2 sets of double digits and a letter each.
nextLine() automatically moves the scanner down after returning the current line. Rather I would advise you do as following
read each line using String data = scanner.nextLine();
split the data using space separator String[] pieces =
data.split("\\s+");
set the pieces to Country attributes by converting them in to
their appropriate type.
eg. c[i].countryName = pieces[0];
`c[i].latitude = piece[1];`
so I am very new to programming and have been trying out some exercises to better learn java.
Right now, I have a program that reads exam marks from a text file(contains only integers exclusively) and then passes that onto the arraylist.
Something like:
exammarks.txt file contains:
23 45 67 76 12
Scanner fileScan = new Scanner(new File("exammarks.txt");
ArrayList<Integer> marksArray = new ArrayList<Integer>();
while (fileScan.hasNextInt())
{
marksArray.add(fileScan.nextInt());
}
Print out: [23, 45, 67, 76, 12]
However I would like to modify this so that the exammarks.txt file contains:
name grade
NAME 56
NAME2 67
NAME3 43
and that the program reads this text file, ignores the first line, then splits the strings from the integers and then adds the integers onto the ArrayList.
Any help will be greatly appreciated
You can use your snippet and extend it to read the second .txt file aswell.
Your while loop now has to loop over lines.
fileScan.nextLine(); // skip first line
while (fileScan.hasNextLine())
{
marksArray.add(Integer.valueOf(fileScan.nextLine().split(" ")[1]));
}
So what happens here is that first you get the nextLine, split it by " " and get the second part where the Integer sits. But since nextLine returns a String which is split in two Strings you have to cast it to Integer or use the static method Integer.valueOf.
I'm writing a program that reads data from a text file with various basketball sports statistics. Each line (after the two header lines) corresponds to one particular game and the scores of each team, with some other strings in there. I'm trying to use scanners to read the int scores of each game, store them in variables, and then compare them to determine which team won that game so that I can increment the wins later in the program. I figured out how to read all the ints in sequence, but I can't figure out how to read two ints in a line, store them as variables, compare them, and then move on to the next line/game.
Here is the relevant method:
public static void numGamesHTWon(String fileName)throws FileNotFoundException{
System.out.print("Number of games the home team won: ");
File statsFile = new File(fileName);
Scanner input1 = new Scanner(statsFile);
String line = input1.nextLine();
Scanner lineScan = new Scanner(line);
input1.nextLine();
input1.nextLine();
while (input1.hasNext()) {
if (input1.hasNextInt()) {
int x = input1.nextInt();
System.out.print(x);
input1.next();
} else {
input1.next();
}
}
A few lines from the text file:
NCAA Women's Basketball
2011 - 2012
2007-11-11 Rice 63 #Winthrop 54 O1
2007-11-11 #S Dakota St 93 UC Riverside 90 O2
2007-11-11 #Texas 92 Missouri St 55
2007-11-11 Tennessee 76 Chattanooga 56
2007-11-11 Mississippi St 76 Centenary 57
2007-11-11 ETSU 75 Delaware St 72 O1 Preseason NIT
read the file line by line. then split the line into a String[]. since you know where the scores are located on each line, you can then easily parse those values from the array and compare. can you please share a few lines form your input? then i can show you the exact code
you can try something like
String[] parts = str.split("\\D+");
where str is the line that you just read. now parts array will have all the numbers in your string. just read through the array, parse to int and make the comparison. note that the first three entries in this array would correspond to the date, so just ignore those.
for example
String[] parts = "2007-11-11 Mississippi St 76 Centenary 57".split("\\D+");
for (String g: parts)
System.out.println(g);
prints out
2007
11
11
76
57
so now you can just take the last two values and compare
while (input1.hasNextLine()) {
String line = input1.nextLine();
String[] parts = line .split("\\D+");
int score1 = Integer.parseInt(parts[parts.length-2]);
int score2 = Integer.parseInt(parts[parts.length-1]);
/*now compare score1 and score2 and do whatever...*/
}
I need to do an assignment where I have to write a while loop with a condition like:
while (not end of stream) {
}
I'm confused about the "not end of stream part". How do I make it so it stop reading when there is no integer input in the console? It will be entered like this: 1 2 3 4 5 6 7 8 9.
I am using the Scanner class my code is something like this:
Scanner myScanner = new Scanner(System.in);
int inputValue = userInput.nextInt();
while(not end of stream) {
if (.......) {
....
} else {
....
}
}
Thanks!
Don't let the word stream confuse you, when reading from System.in, there is no continuous 'flow' of numbers coming.. The user can type what ever he wants to and as long as he wants to. Until he hits 'Enter' nothing will happen.
That said, the scenario is more like this:
1 user types 71 2 30 5 1 and hits Enter
2 userInput.nextInt(); will return the first int it finds so here 71
3 now you could do something like this: [EDITED]
public static void main(String[] args) {
System.out.print(">");
Scanner userInput = new Scanner(System.in);
int inputValue = userInput.nextInt();
while (userInput.hasNextInt()) {
System.out.println("you just wrote: " + userInput.nextInt());
}
userInput.close();
}
So until the scanner doesn't find any input that is not an int the loop will continue. In other words, when the user types for example an 'b' the loop terminates.
Now it all depends on what you have to do in your while-loop. You could test for userInput.hasNext() to see if anything comes, or userInput.nextLine() which will wait for an Enter .. or what ever you need.
When I run the above main and type in:[ 1 Enter 2 Enter 3 Enter 4 Enter a Enter ], this is the output:
>1 // <-- this is the number before the while loop
2 // <-- now another number
you just wrote: 2 // <-- and the while loop makes its first iteration
3 // <-- then it waits for you to input the 3rd number
you just wrote: 3 // <-- to make its next iteration
4 // <-- and the 4th
you just wrote: 4 // <-- 4th iteration
a // <-- until you type something else
// end of program
The user always has to hit Enter – otherwise the operation system won't give the typed input to the Java program. This has to do with the settings of the Shell / Console that your operation system provides for the Java program to run. So, Java won't see anything of the input until you hit enter.