How to skip a character when using Scanner - java

I want to read words from a text file which looks like:
"A","ABILITY","ABLE","ABOUT","ABOVE","ABSENCE","ABSOLUTELY","ACADEMIC","ACCEPT","ACCESS","ACCIDENT","ACCOMPANY", ...
I read the words using split("\",\"") so I have them in a matrix. Unfortunately I cannot skip reading the first quotation mark, which starts my .txt file, so as a result in my console I have:
"A
ABILITY
ABLE
ABOUT
ABOVE
Do you know how can I skip the first quotation mark? I was trying both
Scanner in = new Scanner(file).useDelimiter("\"");
and parts[0].replace("\"", "");, but it doesn't work.
package list_1;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class exercise {
public static void main(String[] args) throws FileNotFoundException{
File file = new File("slowa.txt");
Scanner in = new Scanner(file).useDelimiter("\""); //delimiter doesn't work!
String sentence = in.nextLine();
String[] parts = sentence.split("\",\"");
parts[0].replace("\"", ""); //it doesn't work!
for (int i=0; i<10 ; i++){
System.out.println(parts[i]);
}
}
}

Strings are immutable which means that you can't change their state. Because of that replace doesn't change string on which it was invoked, but creates new one with replaced data which you need to store somewhere (probably in reference which stored original string). So instead of
parts[0].replace("\"", "");
you need to use
parts[0] = parts[0].replace("\"", "");
Anyway setting delimiter and using nextLine doesn't make much sense because this method is looking for line separators (like \n \r \r\n), not your delimiters. If you want to make scanner use delimiter use its next() method.
You can also use different delimiter which will represent " or ",". You can create one with following regex "(,")?.
So your code could look like
Scanner in = new Scanner(file).useDelimiter("\"(,\")?");
while(in.hasNext()){
System.out.println(in.next());
}

You can use this regular expression. It works for me:
Scanner in = new Scanner(file).useDelimiter("\"(,\")?");
while(in.hasNext()){
System.out.println(in.next());
}

Related

Java error in useDelimiter() [duplicate]

This question already has answers here:
How do I use a delimiter with Scanner.useDelimiter in Java?
(3 answers)
Closed 4 years ago.
This is what I have been working so far for reading a text file,
Scanner file = new Scanner(new File("sample.txt")).useDelimiter(".");
ArrayList<String> arr = new ArrayList<>();
while (file.hasNextLine()) {
strList.add(file.nextLine());
}
file.close();
for (int i = 0; i < arr.size(); i++) {
System.out.println(arr.get(i));
}
and my text file looks like this,
I love you. You
love me. He loves
her. She loves him.
I want a result of the code like,
I love you
You love me
He loves her
She loves him
But the result is same as the text file itself. Isn't that "useDelimiter(".")" suppose to separate the text file with period(".")?
I've also tried to use hasNext() and next() instead of hasNextLine() and nextLine(), but it prints out empty 30ish new lines.
That's because useDelimiter accepts a pattern. The dot . is a special character used for regular expressions meaning 'any character'. Simply escape the period with a backslash and it will work:
Scanner file = new Scanner(new File("sample.txt")).useDelimiter("\\.");
EDIT
The problem is, you're using hasNextLine() and nextLine() which won't work properly with your new . delimiter. Here's a working example that gets you the results you want:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Test {
final static String path = Test.class.getResource("sample.txt").getPath();
public static void main(String[] args) throws IOException {
Scanner file = new Scanner(new File(path)).useDelimiter("\\.");
List<String> phrases = new ArrayList<String>();
while (file.hasNext()) {
phrases.add(file.next().trim().replace("\r\n", " ")); // remove new lines
}
file.close();
for (String phrase : phrases) {
System.out.println(phrase);
}
}
}
by using hasNext() and next(), we can use our new . delimiter instead of the default new line delimiter. Since we're doing that however, we've still go the new lines scattered throughout your paragraph which is why we need to remove new lines which is the purpose of file.next().trim().replace("\r\n", " ") to clean up the trailing whitespace and remove new line breaks.
Input:
I love you. You
love me. He loves
her. She loves him.
Output:
I love you
You love me
He loves her
She loves him

Reverse a string with spaces.going through for loop

In this exercise I am to reverse a string. I was able to make it work, though it will not work with spaces. For example Hello there will output olleH only. I tried doing something like what is commented out but couldn't get it to work.
import java.util.Scanner;
class reverseString{
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scan.next();
int length = input.length();
String reverse = "";
for(int i = length - 1; i >= 0; i--){
/*if(input.charAt(i) == ' '){
reverse += " ";
}
*/
reverse += input.charAt(i);
}
System.out.print(reverse);
}
}
Can someone please help with this, thank you.
Your reverse method is correct, you are calling Scanner.next() which reads one word (next time, print the input). For the behavior you've described, change
String input = scan.next();
to
String input = scan.nextLine();
You can also initialize the Scanner this way:
Scanner sc = new Scanner(System.in).useDelimiter("\\n");
So that it delimits input using a new line character.
With this approach you can use sc.next() to get the whole line in a String.
Update
As the documentation says:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
An example taking from the same page:
The scanner can also use delimiters other than whitespace. This example reads several items in from a string:
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();
prints the following output:
1
2
red
blue
All this is made using the useDelimiter method.
In this case as you want/need to read the whole line, then your useDelimiter must have a pattern that allows read the whole line, that's why you can use \n, so you can do:
Scanner sc = new Scanner(System.in).useDelimiter("\\n");

How to take integer and remove other data types from the file java?

I do not know how to take the integer and ignore the strings from the file using scanner. This is what I have so far. I need to know how to read the file token by token. Yes, this is a homework problem. Thank you so much.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ClientMergeAndSort{
public static void main(String[] args){
int length = 13;
try{
Scanner input = new Scanner(System.in);
System.out.print("Enter the file name with extention : ");
File file = new File(input.nextLine());
input = new Scanner(file);
while (!input.hasNextInt()) {
input.next();
}
int[] arraylist = new int[length];
for(int i =0; i < length; i++){
length++;
arraylist[i] = input.nextInt();
System.out.print(arraylist[i] + " ");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Take a look at the API for what you're doing.
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextInt()
Specifically, Scanner.hasNextInt().
"Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input."
So, your code:
while (!input.hasNextInt()) {
input.next();
}
That's going to look and see if input hasNextInt().
So if the next token - one character - is an int, it's false, and skips that loop.
If the next token isn't an int, it goes into the loop... and iterates to the next character.
That's going to either:
- find the first number in the input, and stop.
- go to the end of the input, not find any numbers, and probably hits an IllegalStateException when you try to keep going.
Write down in words what you want to do here.
Use the API docs to figure out how the hell to tell the computer that. :) Get one bit at a time right; this has several different parts, and the first one doesn't work yet.
Example: just get it to read a file, and display each line first. That lets you do debugging; it lets you build one thing at a time, and once you know that thing works, you build one more part on it.
Read the file first. Then display it as you read it, so you know it works.
Then worry about if it has numbers or not.
A easy way to do this is read all the data from file in a way that you prefer (line by line for example) and if you need to take tokens, you can use split function (String.split see Java doc) or StringTokenizer for each line of String that you are reading using a loop, in order to create tokens with a specific delimiter (a space for example) so now you have the tokens and you can do something that you need with them, hope you can resolve, if you have question you can ask.
Have a nice programming.
import static java.nio.file.Files.readAllBytes;
import static java.nio.file.Paths.get;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String args[]) throws IOException {
String newStr=new String(readAllBytes(get("data.txt")));
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(newStr);
while (m.find()) {
System.out.println("- "+m.group());
}
}
}
This code fill read the file and then using the regular expression you can get only Integer values.
Note: This code works in Java 8
I Think This will work for you requirement.
Before reading the data from the file initially,try to write some content to the file by using scanner and filewriter then try to execute the below code snippet.
File file = new File(your filepath);
List<Integer> list = new ArrayList<Integer>();
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String str =null;
while(true) {
str = bufferedReader.readLine();
if(str!=null) {
System.out.println(str);
char[] chars = str.toCharArray();
String finalInt = "";
for(int i=0;i<chars.length;i++) {
if(Character.isDigit(chars[i])) {
finalInt=finalInt+chars[i];
}
}
list.add(Integer.parseInt(finalInt));
System.out.println(list.size());
System.out.println(list);
} else {
break;
}
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
The final println statement will display all the integer in your file line by line.
Thanks

Java - Parsing CSV into ArrayList (Need to recognize line breaks)

Preface: This is for an assignment in one of my classes.
I need to parse through a CSV file and add each string to an ArrayList so I can interact with each string individually with pre-coded functions.
My problem is that the final string in each line (which doesn't end with a comma) is combined with the first string in the next line and recognized as being at the same index in the ArrayList. I need to learn how to either add a line break or do something else that will stop my loop at the end of each line and read the next line separately. Perhaps there is a built-in method in the scanner class that I'm unaware of that does this for me? Help is appreciated!
Here is the information in the CSV file:
Fname,Lname,CompanyName,Balance,InterestRate,AccountInception
Sally,Sellers,Seashells Down By The Seashore,100.36,3,7/16/2002
Michael,Jordan,Jordan Inc.,1000000000,3,6/12/1998
Ignatio,Freely,Penultimate Designs,2300.76,2.4,3/13/1991
Here is my code so far
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class InterestCalculator {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(new File("smalltestdata-sallysellers.csv"));
// Chomp off at each new line, then add to array or arraylist
scanner.useDelimiter("\n");
ArrayList<String> data = new ArrayList<String>();
while (scanner.hasNext()) {
// Grab data between commas to add to ArrayList
scanner.useDelimiter(",");
// Add grabbed data to ArrayList
data.add(scanner.next());
}
System.out.println(data.get(10));
scanner.close();
}
}
And here is the output
7/16/2002
Michael
It seems like you just need to do...
String s[] = scanner.nextLine().split(",");
Collections.addAll(data, s);

Read and split a text file (java)

I have some text files with time information, like:
46321882696937;46322241663603;358966666
46325844895266;46326074026933;229131667
46417974251902;46418206896898;232644996
46422760835237;46423223321897;462486660
For now, I need the third column of the file, to calculate the average.
How can I do this? I need to get every text lines, and then get the last column?
You can read the file line by line using a BufferedReader or a Scanner, or even some other techinique. Using a Scanner is pretty straightforward, like this:
public void read(File file) throws IOException{
Scanner scanner = new Scanner(file);
while(scanner.hasNext()){
System.out.println(scanner.nextLine());
}
}
For splitting a String with a defined separator, you can use the split method, that recevies a Regular Expression as argument, and splits a String by all the character sequences that match that expression. In your case it's pretty simple, just the ;
String[] matches = myString.split(";");
And if you want to get the last item of an array you can just use it's length as parameter. remembering that the last item of an array is always in the index length - 1
String lastItem = matches[matches.length - 1];
And if you join all that together you can get something like this:
public void read(File file) throws IOException{
Scanner scanner = new Scanner(file);
while(scanner.hasNext()){
String[] tokens = scanner.nextLine().split(";");
String last = tokens[tokens.length - 1];
System.out.println(last);
}
}
Yes you have to read each line of the file and split it by ";" separator and read third element.

Categories

Resources