split the text only 5 times - java

i want to split the string ...i want spit to happen for just first 5 times then ...rest in 1 string
i tried this
public class FileRead
{
public static void main(String[] args) throws IOException
{
StringBuffer strBuff = new StringBuffer();
String str = null;
File file = new File("D:\\wokies\\5_dataset.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
String [] splitSt =line.split(" ");
System.out.println("split happing");
for (int i = 0 ; i < splitSt.length ; i++)
{
System.out.println(splitSt[i]);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

I won't write code for you, but the solution is very simple, one solution is to have a counter, initialize it to 0, increment it on each iteration. When it'll be 5, don't split1.
1 I assume you want to split each time on a new input and not the same one.

java.lang.String.split(String regex, int limit) accepts a limit: How often do you want to split the input?
If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.
So
line.split(" ", 5);
would solve your problem.

You can use split with limit split(regex, limit). Try maybe split(" ", 5), this will create array with max 5 elements and last element will not be split like "a b c d".split(" ", 3) will create ["a", "b", "c d"]

The split method of String can take a second parameter "limit" that "controls the number of times the pattern is applied and therefore affects the length of the resulting array".
Just call line.split(" ", 5);

Related

How to limit the number of words when reading a line from standard input?

I am new to Stackoverflow and this is my first time asking a question. I have searched my problem thoroughly, however, could not find an appropriate answer. I am sorry if this has been asked. Thank you in advance.
The question is from Hyperskill.com as follows:
Write a program that reads five words from the standard input and outputs each word in a new line.
First, you need to print all the words from the first line, then from the second (from the left to right).
Sample Input 1:
This Java course
is adaptive
Sample Output 1:
This
Java
course
is
adaptive
My trial to solve it
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
/* I have not initialized the "userInput" String.
* I know that String is immutable in Java and
* if I initialize it to an empty String ""
* and read a String from user.
* It will not overwrite to the "userInput" String.
* But create another String object to give it the value of the user input,
* and references the new String object to "userInput".
* I didn't want to waste memory like that.
*/
String userInput;
String[] userInputSplitFirstLine = new String[3];
String[] userInputSplitSecondLine = new String[2];
Scanner scan = new Scanner(System.in);
userInput = scan.nextLine();
userInputSplitFirstLine = userInput.split("\\s+");
userInput = scan.nextLine();
userInputSplitSecondLine = userInput.split("\\s+");
for(String firstLineSplitted: userInputSplitFirstLine) {
System.out.println(firstLineSplitted);
}
for(String secondLineSplitted: userInputSplitSecondLine) {
System.out.println(secondLineSplitted);
}
scan.close();
}
}
If you try the sample input above, the output will match the sample output above. However, if you write more than 3 words to the first line and/or more than 2 words to the second line, the userInputSplitFirstLine array of size 3 will store more than 3 words. Same goes with the userInputSplitSecondLine array also. My first question is how can an array of size 3 (userInputSplitFirstLine) and an array of size 2 (userInputSplitSecondLine) can hold more than 3 and 2 elements, respectively? My second question is that how can I restrict/limit the number of words that the user can insert in a line; for example, the first line only accepts 3 words and the second line only accepts 2 words?
Also the answer to this question suggested by Hyperskill.com is as follows:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String wordOne = scanner.next();
String wordTwo = scanner.next();
String wordThree = scanner.next();
String wordFour = scanner.next();
String wordFive = scanner.next();
System.out.println(wordOne);
System.out.println(wordTwo);
System.out.println(wordThree);
System.out.println(wordFour);
System.out.println(wordFive);
}
}
You can use next method of scanner object to read string and then it can be printed easily on new line.
while(true){
if(scanner.hasNext()){
System.out.println(scanner.next());
}
else{
break;
}
}
I think this should do the work. Don't hesitate to ask, if you have some questions.
import java.util.Scanner;
class App {
public static void main(String[] args) {
final StringBuffer line = new StringBuffer();
final StringBuffer words = new StringBuffer();
try (final Scanner sc = new Scanner(System.in)) {
while (sc.hasNextLine()) {
final String currentLine = sc.nextLine();
line.append(currentLine).append(System.lineSeparator());
for (final String word : currentLine.split("\\s+")) {
words.append(word).append(System.lineSeparator());
}
}
} finally {
System.out.println(line.toString());
System.out.println();
System.out.println(words.toString());
}
}
}
My first question is how can an array of size 3 (userInputSplitFirstLine) and an array of size 2 (userInputSplitSecondLine) can hold more than 3 and 2 elements, respectively?
The array here:
String[] userInputSplitFirstLine = new String[3];
is not the same one as the one you got from split:
userInputSplitFirstLine = userInput.split("\\s+");
When you do the above assignment, the old array that was in there is basically "overwritten", and now userInputSplitFirstLine refers to this new array that has a length independent of what the old array had. split always return a new array.
My second question is that how can I restrict/limit the number of words that the user can insert in a line; for example, the first line only accepts 3 words and the second line only accepts 2 words?
It really depends on what you mean by "restrict". If you just want to check if there are exactly three words, and if not, exit the program, you can do this:
userInputSplitFirstLine = userInput.split("\\s+");
if (userInputSplitFirstLine.length != 3) {
System.out.println("Please enter exactly 3 words!");
return;
}
You can do something similar with the second line.
If you want the user to be unable to type more than 3 words, then that's impossible, because this is a command line app.
By the way, the code in the suggested solution works because next() returns the next "word" (or what we generally think of as a word, anyway) by default.
hope this will help you!
public class pratice1 {
public static void main (String[]args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String input1 = sc.nextLine();
char[]a =input.toCharArray();
char[]a1 = input1.toCharArray();
System.out.println(input +""+ input1);
int a2=0;
if(input!=null) {
for(int i=0;i<input.length();i++) {
if(a[i]==' ') {
a2=i;
for(int j=0;j<a2;j++) {
System.out.println(a[i]);
a2=0;
}
}
else System.out.print(a[i]);
}System.out.println("");
for(int i=0;i<input1.length();i++) {
if(a1[i]==' ') {
a2=i;
for(int j=0;j<a2;j++) {
System.out.println(a1[i]);
a2=0;
}
}
else System.out.print(a1[i]);
}
}
}
}
To solve the problem:
Write a program that reads five words from the standard input and
outputs each word in a new line.
This was my solution:
while(scanner.hasNext()){
System.out.println(scanner.next());
}

Hanging Letter Program

I was practicing problems in JAVA for the last few days and I got a problem like this:
I/p: I Am A Good Boy
O/p:
I A A G B
m o o
o y
d
This is my code.
System.out.print("Enter sentence: ");
String s = sc.nextLine();
s+=" ";
String s1="";
for(int i=0;i<s.length();i++)
{
char c = s.charAt(i);
if(c!=32)
{s1+=c;}
else
{
for(int j=0;j<s1.length();j++)
{System.out.println(s1.charAt(j));}
s1="";
}
}
The problem is I am not able to make this design.My output is coming as each character in each line.
First, you need to divide your string with space as a delimiter and store them in an array of strings, you can do this by writing your own code to divide a string into multiple strings, Or you can use an inbuilt function called split()
After you've 'split' your string into array of strings, just iterate through the array of strings as many times as your longest string appears, because that is the last line you want to print ( as understood from the output shared) i.e., d from the string Good, so iterate through the array of strings till you print the last most character in the largest/ longest string, and exit from there.
You need to handle any edge cases while iterating through the array of strings, like the strings that does not have any extra characters left to print, but needs to print spaces for the next string having characters to be in the order of the output.
Following is the piece of code that you may refer, but remember to try the above explained logic before reading further,
import java.io.*;
import java.util.*;
public class MyClass {
public static void main(String args[]) throws IOException{
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Scanner sc = new Scanner(System.in);
String[] s = sc.nextLine().split(" ");
// Split is a String function that uses regular function to split a string,
// apparently you can strings like a space given above, the regular expression
// for space is \\s or \\s+ for multiple spaces
int max = 0;
for(int i=0;i<s.length;i++) max = Math.max(max,s[i].length()); // Finds the string having maximum length
int count = 0;
while(count<max){ // iterate till the longest string exhausts
for(int i=0;i<s.length;i++){
if(count<s[i].length()) System.out.print(s[i].charAt(count)+" "); // exists print the character
else System.out.print(" "); // Two spaces otherwise
}
System.out.println();count++;
}
}
}
Edit: I am sharing the output below for the string This is a test Input
T i a t I
h s e n
i s p
s t u
t

Why is my word counter sometimes off by one?

Most of the time it works correctly. Rarely it counts off by one. Any guess?
public static int countWords(File file) throws FileNotFoundException, IOException{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
List<String> strList = new ArrayList<>();
while ((line=br.readLine())!=null){
String[] strArray= line.split("\\s+");
for (int i=0; i<strArray.length;i++){
strList.add(strArray[i]);
}
}
return strList.size();
}
Particularly in the example below it gives 3 instead of 2:
\n
k
I guess the second line is split into two string, "" and "k". See the code below:
import java.util.Arrays;
public static void main(String[] args) {
String str = " k";
String[] array = str.split("\\\s+");
System.out.println("length of array is " + array.length); // length is 2
System.out.println(Arrays.toString(array)); //array is [, k]
}
If you are using Java 8, you can use Streams and filter what you consider as a "word". For example:
List<String> l = Files.lines(Paths.get("files/input.txt")) // Read all lines of your input text
.flatMap(s->Stream.of(s.split("\\s+"))) // Split each line by white spaces
.filter(s->s.matches("\\w")) // Keep only the "words" (you can change here as you want)
.collect(Collectors.toList()); // Put the stream in a List
In this specific case, it will output [k].
You can of course do the same in Java 7 by adapting your code and add this condition in your for loop:
if(strArray[i].matches("\\w"))
strList.add(strArray[i]); // Keep only the "words" - again, use your own criteria
It is just more cumbersome.
I hope it helps.

Print out prime Number less than a given number N

Print out the prime numbers less than a given number N. For bonus points your solution should run in N*log(N) time or better. You may assume that N is always a positive integer.
Input sample:
Your program should accept as its first argument a path to a filename. Each line in this file is one test case. Each test case will contain an integer n < 4,294,967,295.
E.g.
10
20
100
Output sample:
For each line of input, print out the prime numbers less than N, in ascending order, comma delimited. (There should not be any spaces between the comma and numbers) E.g.
2,3,5,7
2,3,5,7,11,13,17,19
2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97
Here is my solution:
public class problem1 {
public static void main(String [] args) throws Exception
{
File f=new File("C://Users/Rahul/Documents/Projects/r.txt");
FileReader fr=new FileReader(f);
List<Integer> l=new ArrayList<>();
int p;
BufferedReader br = new BufferedReader(fr);
String s;
while( (s= br.readLine()) != null ) {
int a=Integer.parseInt(s);
for(int i=2;i<a;i++)
{
p=0;
for(int j=2;j<i;j++)
{
if(i%j==0)
p=1;
}
if(p==0)
l.add(i);
}
String st=l.toString();
st=st.replaceAll("\\[", "").replaceAll("\\]", "").replace(", ", ",");
System.out.print(st);
System.out.println("\t");
}
fr.close();
}
}
My input is :
10
50
And output is :
2,3,5,7
2,3,5,7,2,3,5,7,11,13,17,19,23,29,31,37,41,43,47
But when i submit this solution they are not accepting this solution.
But when i put content in document like this:
10 50
30
I am trying that java program ignore this 50. How to do it ?
Any better solution then this ?
Give me some idea!
To ignore the extra number in your file you can take only the first number of each line.
Your solution is probably not accepted because in your second line you have printed 2,3,5,7 twice (i.e. the primes of the previous line)
See the example below to fix both problems
while( (s= br.readLine()) != null ) {
String [] numbers = s.split(" "); // split the line
int a = Integer.parseInt(numbers[0]); // take only the first one
....
System.out.print(st);
System.out.println("\t");
l.clear(); // clear the list before trying to find primes for the new line
}
"Your program should accept as its first argument a path to a filename"
You have a hardcoded filename in your solution - use args[0] instead.
Othwerwise, your solutions looks OK, although there is some room for improvements regarding the efficiency.

Java - Importing text file into array when lines are not consistent

I have an assignment that pretty much has me stumped early on, the remainder of which is fairly easy (sorting the data once its imported and then saving it again under a different name).
We need to import data from a .txt file into 3 separate Arrays ( name, mascot, alias ) however the lines are not consistent. By consistent I mean one line may have:
Glebe,G Shield,Glebe District
While another line may have:
St George,Knight & Dragon,Saints,Dragons,St George Illawarra
Everything before the first , belongs to the name array.
Everything after the first , but before the second , belongs to the mascot array.
Everything after the second , till the end of the line belongs to the alias array.
I've been able to work out how to import the .txt file where it contains the entire line, which I was then able to convert into importing everything before a "," and new line (using Delimiters). However the lines that contain more then 3 sets of data ruin the import as the alias array only ends up holding 1 not everything else.
Thus does anyone know of and can show me a code that pretty much does:
name = Everything before the first ,
Mascot = Everything after the first , but before the second ,
Alias = Everything after the second , till the end of the line
That I could use as a base to work into mine?
After a day of research I've constantly come up with dead ends. They all generally involve splitting up at each comma but that breaks the import (lines with more then 1 alias, the second alias is put into the name array, ect)
This is the code I came up with that imports the entire line into an array:
public static void LoadData() throws IOException
{
String clubtxt = ("NRLclubs.txt");
String datatxt = ("NRLdata.txt");
int i, count;
File clubfile = new File(clubtxt);
File datafile = new File(datatxt);
if (clubfile.exists())
{
count = 0;
Scanner inputFile = new Scanner(clubfile);
i = 0;
while(inputFile.hasNextLine())
{
count++;
inputFile.nextLine();
}
String [] teamclub = new String[count];
inputFile.close();
inputFile = new Scanner(clubfile);
while(inputFile.hasNext())
{
teamclub[i] = inputFile.nextLine();
System.out.println(teamclub[i]);
i++;
}
inputFile.close();
}
else
{
System.out.println("\n" + "The file " + clubfile + " does not exist." + "\n");
}
if (datafile.exists())
{
count = 0;
Scanner inputFile = new Scanner(datafile);
i = 0;
while(inputFile.hasNextLine())
{
count++;
inputFile.nextLine();
}
String [] teamdata = new String[count];
inputFile.close();
inputFile = new Scanner(datafile);
while(inputFile.hasNext())
{
teamdata[i] = inputFile.nextLine();
System.out.println(teamdata[i]);
i++;
}
inputFile.close();
}
else
{
System.out.println("\n" + "The file " + datafile + " does not exist." + "\n");
}
}
Look at String.split method with the parameter limit.
When you have your input line in a variable called line, you can can call
String[] tokens = line.split(',', 3);
This will split the line on the commas, while making sure that it will not return more than 3 tokens. It returns an array of String in which the first element will be what is before the first comma, the second will be what is between the first and second commas, and the third element will be what is after the second comma.
Since you only want to parse on the first 2 commas, you can use String split with a limit.
If you prefer, you can use the String indexOf method to find the first 2 commas, then use the String substring method to get the characters between the commas.
You want to be able to handle a line with one comma, or no commas at all.
Here's one way to parse the String line
public List<String> splitLine(String line) {
List<String> list = new ArrayList<String>();
int firstPos = line.indexOf(",");
int secondPos = line.indexOf(",", firstPos + 1);
if (firstPos >= 0) {
if (secondPos >= 0) {
list.add(line.substring(0, firstPos));
list.add(line.substring(firstPos + 1, secondPos));
list.add(line.substring(secondPos + 1));
} else {
list.add(line.substring(0, firstPos));
list.add(line.substring(firstPos + 1));
list.add("");
}
} else {
list.add(line);
list.add("");
list.add("");
}
return list;
}
You can use the String.split method.
String line = // the line you read here
// Split on commas but only make three elements
String[] elements = line.split(',', 3);
// The first belongs to names
names[linecount] = elements[0];
// The second belongs to mascot
mascot[linecount] = elements[1];
// And the last belongs to aliases
aliases[linecount] = elements[2];
Try looking into the Pattern/Matcher stuff -- you need to come up with an appropriate regex.
http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html
Something like this might do it:
static final Pattern pattern = Pattern.compile("([^,]*),([^,]*),(*$)");
MatchResult result = pattern.matcher(line).toMatchResult();
if (result.groupCount() == 3) {
// Found the groups
name = result.group(0);
// etc..
} else {
// failed to match line
}
Basically what you want to do is split each line into an array as you read it in, and then parse the data line by line. Something like this (pseudocode):
Scanner inputFile = new Scanner(datafile);
while(inputFile.hasNextLine()) {
String line = inputFile.nextLine();
String[] lineSplit = line.split(",");
//TODO: make sure lineSplit is at least 3 long.
String name = lineSplit[0];
String mascot = lineSplit[1];
//EDIT: Don't just get the last element, get everything after the first two.
// You can do this buy just getting the substring of the length of those two strings
// + 2 to account for commas.
//String alias = lineSplit[lineSplit.length() - 1];
String alias = line.substring(name.length() + mascot.length() + 2);
//If you need to do trimming on the strings to remove extra whitespace, do that here:
name = name.trim();
mascot = mascot.trim();
alias = alias.trim();
//TODO: add these into the arrays you need.
}
Hope this helps.

Categories