Reputation: 31
Lets say the lines in a file are:
Code:
String string = input.nextLine();
int index=0;
System.out.println(string);
if(string.contains(" "))
{
while(string.contains(" "))
{
int random = string.indexOf(" ");
String temp6 = string.substring(index,random);
ps.print(pig(temp6)+" ");
int temp8 = temp6.length();
String temp7 = string.substring(temp8+1,string.length());
string=temp7;
}
ps.print(pig(string));
}
else
{
ps.println(pig(string));
//}
}
For input:
Hello
Bob
How would I get scanner to skip the line after Hello? Or how do I remove that blank line?
Upvotes: 1
Views: 4963
Reputation: 146
In case of both an empty line or an empty line with blank spaces, we can use the following code:-
File file = new File("D://testFile.txt");
Scanner sc;
try {
sc = new Scanner(file);
while(sc.hasNextLine())
{
String text = sc.nextLine();
// remove mulitple empty spaces from the line
text = text.replaceAll("[ ]+", " ");
// check whether the length is greater than 0
// and it's just not an empty space
if(text.length()>0 && !text.equals(" ")) {
System.out.println(text);
}
}
sc.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Input is:- Blob
Random
Carrie
Jason
Output:- Blob Random Carrie Jason
Upvotes: 0
Reputation: 2079
Look for this
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> list = new ArrayList<>();
File file = new File("someFileHere.txt");
Scanner scanner = new Scanner(file);
String line = "";
while (scanner.hasNext()) {
if (!(line = scanner.nextLine()).isEmpty()) {
list.add(line);
}
}
scanner.close();
System.out.println(list);
}
And assume that the someFileHere.txt contains:
Hello
Bob
As you mentioned, they store in the list'Hello' and 'Bob' without any blank line.
Upvotes: 3