If I copy and paste into a program It only takes the first line for instance I copy a few blocks from Microsoft Excel and Paste it pastes the codes like this:
72LYY-785B9-0WQD9
88CXK-4E8BB-TA2GD
JLEIZ-0KYKP-PY2E4
LV5TL-A6CLB-P59GX
My program only takes 72LYY-785B9-0WQD9, but I want the scanner to take all until it is empty.
I am using
String userData = takeInput.nextLine();
I put it into a String and then turn it into an array of chars.
Any help?
Did you try any other approach?
Scanner stdin = new Scanner(new BufferedInputStream(System.in));
while (stdin.hasNext()) {
System.out.println(stdin.nextLine());
}
Related
I'm coding a program that takes in lines from an input text file.
It is supposed to be a set of strings on a single line separated by the newline character. So, my input file looks like this:
0110\n011\n0111\n100001
However, when I go to print out each line, it comes out as one entire string, including the new line characters - '0110\n011\n0111\n100001'
This is my code - it works fine for Scanner when it's a static string, but not when it's from a file.
File input = new File(input.txt);
Scanner scanner = new Scanner(input);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
When I change the scanner to read a String s, like Scanner scanner = new Scanner(s) for a String s = "0110\n011\n0111\n100001", it works correctly and prints out 4 lines, which means it recognizes the \n character, as such:
String s = "0110\n011\n0111\n100001";
Scanner scanner = new Scanner(s);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
The only thing that's holding me back is that we have to separate the input file strings by \n. That's a requirement for our project.
Any idea why this happens? Is my text file wrong, is there a way to split it up by \n? Does Scanner read lines in files differently than just static strings? Should I just switch to BufferedReader? I can't wrap my head around this. I read through some forums and manuals and I couldn't find anything on it. If I can do anything, or provide anything else, please let me know.
\n is a new line symbol, which when in a string is interpreted as such, but in your file you should just hit the enter key, which will make a new line for you and the scanner will read everything right.
Here is the data that I am extracting from a txt:
1|Fred|Fish|fredfish#gamer.net|Ithroeann|19770322
2|Laurie|Nash|laurieeenash#gmail.com|Mazzzap|19820828
3|Conrad|Washington|fredfish#gamer.net|Crayonbreath|19720712
Here is the code for scanner to read the content from the txt:
File file = new File("players.txt");
Scanner s = new Scanner(file);
while (s.hasNextLine()) {
String line = s.nextLine();
s.close();
I was wondering is there any way to merge each individual line from the scanner into a single string output.
The string output will then be used by my other method to split it into different player objects.
Thank you in advance.
You can create an object of StringBuilder. As you fetch a line from the file you can use its append() method. Once you read and append all the lines you can get the String object by invoking toString() on the object of StringBuilder.
Also note that you can use + on Simple String objects but as objects of class String are immutable hence doing so will result in lot of String objects which will be a performance kill. Hence StringBuilder is preferably better choice.
I have a string that I want to read line by line:
"8688642986379252 Michael_Thompson 816 2500.0
8904000405634912 Barbara_Martin
8610835007621519 Charles_Jackson 1019 52800.0"
It goes on on and on in that format.
I tried separating it using for loops, charAt() and reducing the size of the string using substring() but I failed miserably.
I'm sure it's something simple but I just can't get it. Any ideas?
I would suggest using str.split("\n"). It will produce an array of strings, one index for each line. This is assuming you can read the whole thing into a string. If the input is large, this won't work.
Use Scanner to read line by line using nextLine. Then, split every String by blank space" ":
Scanner scanner = new Scanner(stringWithBreaklines);
while (scanner.hasNext()) {
String line = scanner.nextLine();
String[] content = line.split(" ");
//do what you want/need with content
}
If the String is inside a file, then read the file directly using Scanner:
Scanner scanner = new Scanner(new File("file.txt"));
//same code as above...
Use the java.util.Scanner class to read tokens one by one.
http://docs.oracle.com/javase/tutorial/essential/io/scanning.html
Ok another question about my program that I'm writing called "Flight." In my tester I am creating an object from the Flight class called myFlight. The object has several fields (flight name, miles traveled, etc) but what I'm doing is reading the data from a file called input.txt and trying to put it into the object that I created. There are five lines of information on the file that I'm reading. For some reason I can't quite get it right, if anyone could help me fix this problem I would greatly appreciate it.
Here is the Constructor that has all the fields from my Flight class:
public Flight(String name, int num, int miles, String origin, String destination)
{
Airlinename = name;
flightnumber = num;
numofmiles = miles;
Origincity = origin;
Destinationcity = destination;
}
And the part of my program where I created the object and try to read the data from the file. I had created a blank constructor in my class too because I wasn't sure if I was supposed to put anything in the object when I created it.
Flight myFlight = new Flight();
File myFile = new File("input.txt");
Scanner inputFile = new Scanner(myFile);
while (inputFile.hasNext())
{
myFlight = inputFile.nextLine();
}
inputFile.close();
}
}
Just in case you use special characters, you need to modify your program so you can read them correctly.
Scanner inputFile = new Scanner(myFile, "UTF-8");
On the other hand, if the text file contains the following, possibly subsequent calls to nextInt() generate a runtime exception.
Gran EspaƱa
1
1001
New York
Los Angeles
If that were the case, the reading should be different.
myFlight = new Flight(inputFile.nextLine(),
Integer.parseInt(inputFile.nextLine()),
Integer.parseInt(inputFile.nextLine()),
inputFile.nextLine(),
inputFile.nextLine());
As with any program, when adding more conditions to improve the model, it needs more and more code.
Good luck.
try
myFlight = new Flight(inputFile.next(), inputFile.nextInt(),
inputFile.nextInt(), inputFile.next(), inputFile.next());
You can't directly assign a string line to an object, you need to parse the line into parts and assign values to variables one by one.
How is your input text organized? The Scanner's nextLine() method is returning a String object and definitely you cannot assign that to a type Flight. There are different methods to get the different values in the Scanner like nextInt(), nextFloat().
Basically you can try like this
Flight myFlight = new Flight();
myFlight.setFlightName(inputFile.next());
myflight.setMiles(inputFile.nextInt();
etc.
This is just a sample, you need to check the format you have in the input.txt file.
I have college project where i have to read the first word of every line from text file which looks as follow:
23123123213 Samuel classA
23423423423 Gina classC
23423423423 John classD
The text file will be updated with through 3 JTextField which i am able to figure out.
but now i have to populate the JCombobox with first word(23123123213,23423423423 and 23423423423) of all the lines.
I am new to java, i dont even have hint of how about doing it.
I know how to read and write to text files.
Please could someone help me do this?
The code so far i came up with is as follows:
import java.io.*;
public class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("RokFile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
String[] delims = strLine.split(" ");
String first = delims[0];
System.out.println("First word: "+first);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
With u guys help I was successfully able to extract the first string from each line
but now how could i populate it in Jcombobox, I mean should i save it somewhere first?
Thanks in Advance
I'm not "down" with Java, however I can give you a few pointers:
You can read files, and presumably can read a line.
Each line is (presumably) separated with spaces so what you need to look up is a String.split function
Once you've split a string you will be able to use array index 0 to get the information you need.
Then it's just a case of adding split_string[0] to the JComboBox.
The documents are a great help:
String
JComboBox
You can get the first word using String.split(), or by using indexOf and substring.
There is a tutorial about JComboBox.
The Java Swing classes are based on Model/View, so you have to fill the strings into the Model of the JCombobox.
EDIT: In response to your edit, suppose you have retrieved the values. Then you can indeed save them to a specific data structure. It would be preferable to make the code that retrieves those values into a separate method. The values returned from that method (in, for example, a List<String>) can then be put into the JComboBox.
If you know how to read lines from a text file you can split each line by a delimiter, using the String.split function. In that case you get an array, with which you can get the first string by a normal array indexer, the [] operator that is.
String hello = "Hello world";
String[] delims = hello.split(" ");
String first = delims[0];
To answer your edit, you populate the JComboBox using one of its constructors, for instance the one that takes an Object array, or using the JComboBox.addItem(Object) function.
The latter has an example. Regarding the one with the constructor you can either build an array of objects yourself, or use an arraylist to which you add all your elements and then get an array using the ArrayList.toArray() function.