I have a textfile that i am reading out of that looks like this:
pizza, fries, eggs.
1, 2, 4.
I am scannning this .txt using the Scanner class and i want to insert the input into an ArrayList. I know that there is a method to split Strings and use the "," as a Delimiter but i cannot seem to find how and where to apply this. Note: The . is used as its own Delimiter so the scanner know it needs to check the next Line and add that to a different ArrayList.
Here is my corresponding code from the class with the ArrayList Setup:
public class GrocerieList {
static ArrayList<String> foodList = new ArrayList<>();
static ArrayList<String> foodAmount = new ArrayList<>();
}
And here is the code from the class scanning the .txt input:
public static void readFile() throws FileNotFoundException {
Scanner scan = new Scanner(file);
scan.useDelimiter("/|\\.");
scan.nextLine(); // required because there is one empty line at .txt start
if(scan.hasNext()) {
GrocerieList.foodList.add(scan.next());
scan.nextLine();
}
if(scan.hasNext()) {
GrocerieList.foodAmount.add(scan.next());
scan.nextLine();
}
}
Where can i split the strings? And how? Perhaps my approach is flawed and i need to alter it? Any help is greatly appreciated, thank you!
Use nextLine() to read a line from the file, then eliminate the ending period, and split on comma.
And use try-with-resources to close the file correctly.
public static void readFile() throws FileNotFoundException {
try (Scanner scan = new Scanner(file)) {
scan.nextLine(); // required because there is one empty line at .txt start
GrocerieList.foodList.addAll(Arrays.asList(scan.nextLine().replaceFirst("\\.$", "").split(",\\s*")));
GrocerieList.foodAmount.addAll(Arrays.asList(scan.nextLine().replaceFirst("\\.$", "").split(",\\s*")));
}
}
Usually you would save the read out from the nextLine method, and use the split method to decompose the list into an array, then store it to your target. If conversion is needed, such as from string to integer, do it separately.
String lineContent = scan.nextLine();
String[] components = lineContent.split(","); //now your array has "pizza", "fries", "eggs" etc.
The easiest way to do this would be to use String#split.
Also you don't want 'next', but nextLine
GrocerieList.foodList.addAll(Arrays.asList(scan.nextLine().replaceFirst("\\.$", "").split(", ")));
(Should work but didn't test it).
For more informations about the scanner class refer to https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Related
I have a csv file that contains values that im trying to put into an arraylist but the last value of a line merges with the first value of the second line.
See:
I have data like this,
Account Number,Investment Account,Bank Number,Gender,Balance
2544434, Y, 145556, F,1000
2544578, N, 254309, M, 20000
2544230, N, 150365, F, 500000
and my code so far is this,
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO code application logic here
List<String> list = new ArrayList<String>();
try {
Scanner sc = new Scanner(new File("data.csv"));
sc.useDelimiter(",");
sc.nextLine();
while(sc.hasNext()) {
list.add(sc.next());
}
System.out.println(list.get(4))
}
The output looks like this,
1000
2544578
with both the last and first value of their respective rows merging into one when i'd like to keep it separate. I've searched for similar questions and could not find any so i wonder if anyone here can possible help. I'd like this to be done using Scanner module.
In this case, you have already pointed out that a new line does not separate each element of the CSV format.
To fix this you can use the overloaded method of useDelimiter to supply a pattern, wherein the delimiter is either a comma followed by a space or a new line.
Some regex like so:
,\W|[\n]
I am brand new to Java (2 weeks), basically I am trying to do a Triangle problem. I need to input a text file that looks like this:
2 2 2
3 3 2
3 x 4
I can make it read the file and display it correctly, however I need it to display "Equilateral" " Isosceles" "Scalene" or not a triangle because... I cannot figure out how to get my outputs based on the input from the text file. Here is what I have so far.
public static void main(String[] args) throws Exception
{
File file =
new File("input.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
System.out.println(sc.nextLine());
}
}
Which is basically nothing. I know I need 3 arrays. Can someone jumpstart me in the right direction?
Thanks
You need to set sc.nextLine() to a variable to use instead of printing it out as an output immediately. If the sets of three numbers come in a single line, you may want to utilize the split() method, which is pretty easy to use when you understand arrays.
To get you started:
public static void main(String[] args) throws Exception
{
File file =
new File("input.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
String firstLine = sc.nextLine();
String[] sides = firstLine.split(" ");// Get the numbers in between the spaces
// use the individual side lengths for the first triangle as you need
// Next iteration works through the next triangle.
}
You're headed in the right direction. I suggest checking out the following methods:
String.split() docs here
Integer.parseInt() docs here
Those, combined with a little bit of your own logic, should be enough to get you across the finish line.
I have to write a program which prints the String which are inputed from a user and every letter like the first is replaced with "#":
mum -> #u#
dad -> #a#
Swiss -> #wi## //also if it is UpperCase
Albert -> Albert //no letter is like the first
The user can input how many strings he wants. I thought to split the strings with the Split method but it doesn't work with the ArrayList.
import java.util.*;
public class CensuraLaPrima {
public static void main(String[] args) {
Scanner s= new Scanner (System.in);
String tdc;
ArrayList <String> Parolecens= new ArrayList <String>();
while (s.hasNextLine()) {
tdc=s.nextLine();
Parolecens.add(tdc);
}
System.out.println(Parolecens);
}
}
If you want to read in single words you can use Scanner.next() instead. It basically gives you every word, so every string without space and without newline. Also works if you put in two words at the same time.
I guess you want to do something like this. Feel free to use and change to your needs.
import java.util.*;
public class CensuraLaPrima {
public static void main(String[] args) {
Scanner s= new Scanner (System.in);
String tdc;
while (s.hasNext()) {
tdc=s.next();
char c = tdc.charAt(0);
System.out.print(tdc.replaceAll(Character.toLowerCase(c) +"|"+ Character.toUpperCase(c), "#"));
}
}
}
Edit:
Basically it boils down to this. If you want to read single words with the scanner use .next() instead of .nextLine() it does consider every word seperated by space and newline, even if you put in an entire Line at once.
Tasks calling for replacing characters in a string are often solved with the help of regular expressions in Java. In addition to using regex explicitly through the Pattern class, Java provides a convenience API for using regex capabilities directly on the String class through replaceAll method.
One approach to replacing all occurrences of a specific character with # in a case-insensitive manner is using replaceAll with a regex (?i)x, where x is the initial character of the string s that you are processing:
String result = s.replaceAll("(?i)"+s.charAt(0), "#");
You need to ensure that the string is non-empty before calling s.charAt(0).
Demo.
Assuming that you've successfully created the ArrayList, I'd prefer using the Iterator interface to access each elements in the ArrayList. Then you can use any String variable and assign it the values in ArrayList . Thereafter you can use the split() in the String variable you just created. Something like this:
//after your while loop
Iterator<String> it = Parolecens.iterator();
String myVariable = "";
String mySplitString[];
while(it.hasNext()) {
myVariable = it.next();
mySplitString = myVariable.split(//delimiter of your choice);
//rest of the code
}
I hope this helps :)
Suggestions are always appreciated.
for the below input im expecting all the strings delimited with "|" to be available in an array. but only first string is available and the next string is partially available.the rest is not at all available. please help me in understanding it. i explored all the help docs and previous stackoverflow stuff but not able to solve it. i tried with split(String regex,int limit)as well but no use. I dont want to replace the whitespace as i need to retain that.
input "1|New York|1345|134|45634"
Expected output is: 1,New York,1345,134,45634
Actual output is:1,New
public class test1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String strinp=scanner.next();
//System.out.println(strinp.replaceAll(" ", ""));
String[] strArr=strinp.split("\\|");
//System.out.println(Arrays.deepToString(strArr));
for (String s:strArr) {
System.out.println(s);
}
}
}
scanner.next() splits on spaces itself. So your first scanner.next() call reads 1|New which you then split.
Use scanner.nextLine() to read the whole line, it will be split successfully.
Change:
String strinp = scanner.next();
To:
String strinp = scanner.nextLine();
Or you can declare scanner as:
Scanner scanner = new Scanner(System.in).useDelimiter("\\n");
Im working on the question below and am quite close but in line 19 and 32 I get the following error and cant figure it out.
foreach not applicable to expression type
for (String place: s)
Question:
Tax inspectors have available to them two text files, called unemployed.txt and taxpayers.txt, respectively. Each file contains a collection of names, one name per line. The inspectors regard anyone who occurs in both files as a dodgy character. Write a program which prints the names of the dodgy characters. Make good use of Java’s support for sets.
My code:
class Dodgy {
public static void main(String[] args) {
HashSet<String> hs = new HashSet<String>();
Scanner sc1 = null;
try {sc1 = new Scanner(new File("taxpayers.txt"));}
catch(FileNotFoundException e){};
while (sc1.hasNextLine()) {
String line = sc1.nextLine();
String s = line;
for (String place: s) {
if((hs.contains(place))==true){
System.out.println(place + " is a dodgy character.");
hs.add(place);}
}
}
Scanner sc2 = null;
try {sc2 = new Scanner(new File("unemployed.txt"));}
catch(FileNotFoundException e){};
while (sc2.hasNextLine()) {
String line = sc2.nextLine();
String s = line;
for (String place: s) {
if((hs.contains(place))==true){
System.out.println(place + " is a dodgy character.");
hs.add(place);}
}
}
}
}
You're trying to iterate over "each string within a string" - what does that even mean?
It feels like you only need to iterate over each line in each file... you don't need to iterate within a line.
Secondly - in your first loop, you're only looking at the first file, so how could you possibly detect dodgy characters?
I would consider abstracting the problem to:
Write a method to read a file and populate a hash set.
Call that method twice to create two sets, then find the intersection.
Foreach is applicable for only java.lang.Iterable types. Since String is not, so is the error.
If your intention is to iterate characters in the string, then replace that "s" with "s.toCharArray()" which returns you an array that is java.lang.Iterable.