How to separate words by spaces? - java

What I'm trying to do in this code is separate each word of a five-word input into the five words that it's made of. I managed to get the first word separated from the rest of the input using indexOf and substring, but I have problems separating the rest of the words. I am just wondering what I could do to fix this.
import java.util.Scanner;
public class CryptographyLab {
public static void main (String [] args) {
fiveWords();
}
public static void fiveWords () {
Scanner input = new Scanner(System.in);
for (int i = 1; i <= 3; i++) {
if (i > 1) {
String clear = input.nextLine();
// I was having some problems with the input buffer not clearing, and I know this is a funky way to clear it but my skills are pretty limited wher I am right now
}
System.out.print("Enter five words: ");
String fW = input.nextLine();
System.out.println();
// What I'm trying to do here is separate a Scanner input into each word, by finding the index of the space.
int sF = fW.indexOf(" ");
String fS = fW.substring(0, sF);
System.out.println(fS);
int dF = fW.indexOf(" ");
String fD = fW.substring(sF, dF);
System.out.println(fD);
int gF = fW.indexOf(" ");
String fG = fW.substring(dF, gF);
//I stopped putting println commands here because it wasn't working.
int hF = fW.indexOf(" ");
String fH = fW.substring(gF, hF);
int jF = fW.indexOf(" ");
String fJ = fW.substring(hF, jF);
System.out.print("Enter five integers: ");
int fI = input.nextInt();
int f2 = input.nextInt();
int f3 = input.nextInt();
int f4 = input.nextInt();
int f5 = input.nextInt();
//this part is unimportant because I haven't worked out the rest yet
System.out.println();
}
}
}

The Scanner class has a next() method that returns the next "token" from the input. In this case, I think calling next() five times in succession should return your 5 words.
As Alex Yan points out in his answer, you can also use the split method on a string to split on some delimiter (in this case, a space).

You're extracting the strings incorrectly. But there is another simpler solution which I'll explain after.
The problem with your approach is that you're not supplying the indices correctly.
After the first round of extraction:
fW = "this should be five words"
sf = indexOf(" ") = 4
fS = fW.substring(0, sF) = "this"
This appears correct. But after the second round:
fW = "this should be five words". Nothing changed
df = indexOf(" ") = 4. Same as above
fD = fW.substring(sF, dF) = substring(4, 4). You get a null string
We see that the problem is because indexOf() finds the first occurrence of the supplied substring. substring() doesn't remove the portion that you substring. If you want to keep doing it this way, you should trim off the word you just substringed.
space = input.indexOf(" ");
firstWord = input.substring(0, space);
input = input.substring(space).trim(); // sets input to "should be five words" so that indexOf() looks for the next space during the next round
A simple solution is to just use String.split() to split this into an array of substrings.
String[] words = fw.split(" ");
If input is "this should be five words"
for (int i = 0; i < words.length; ++i)
System.out.println(words[i]);
Should print:
this
should
be
five
words

Related

Multiple systeminputs on different lines concatenated together. JAVA

I have "N" systeminputs each on a new line. Each line consists of three names.
I want to concatinate the lines together so i can count each word and print the word thats unique.
The systeminputs have space between them and is the following.
Input:
betsy andrew flora
carol andrew betsy
dora andrew carol
elena andrew dora
Output:
Elena
I tried putting them in a Hashset but didnt get it work because the inputs were on different lines so the output was that every word was unique.
My CODE:
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();//number that defines how many inputs
int i = 0;
ArrayList<String> utopia = new ArrayList<String>();
while (sc.hasNextLine() && i <= N) {
utopia.add(sc.nextLine());
i++;
}
Plz help have tried alooot of stuff.
// A Beginner
You can try something like this to read input:
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();//number that defines how many inputs
int i = 1;
List<String> utopia = new ArrayList<String>();
String line= sc.nextLine();
while (!(line = sc.nextLine()).isBlank() && i < N) {
utopia.add(line);
i++;
}
System.out.println(utopia);
You can use StringBuilder to concatenate each line. String#split(" ") method to get each word.

How to replace multiple occurences of a character in a java string using replace and charAt methods

This is my second question here and still a beginner so please bear with me.
I have this code of a very basic hangman type game.I have changed the characters to "-",I am able to get the indices of the input but I am not able to convert back the "-" to the characters entered.
Its an incomplete code.
String input;
String encrypt = line.replaceAll("[^ ]","-");
System.out.println(encrypt);
for (int j=0;j<10;j++){ //Asks 10 times for user input
input = inpscanner.nextLine();
int check = line.indexOf(input);
while (check>=0){
//System.out.println(check);
System.out.println(encrypt.replaceAll("-",input).charAt(check));
check = line.indexOf(input,check+1);
}
Here is how it looks like:
You have 10 chances to guess the movie
------
o
o
o
L
L
u //no repeat because u isn't in the movie.While 'o' is 2 times.
I would like to have it like loo---(looper).
How can I do like this "[^ ]","-" in case of a variable?
This might help.
public static void main(String[] args) {
String line = "xyzwrdxyrs";
String input;
String encrypt = line.replaceAll("[^ ]","-");
System.out.println(encrypt);
System.out.println(line);
Scanner scanner = new Scanner(System.in);
for (int j=0;j<10;j++) { //Asks 10 times for user input
input = scanner.nextLine();
//int check = line.indexOf(input);
int pos = -1;
int startIndex = 0;
//loop until you all positions of 'input' in 'line'
while ((pos = line.indexOf(input,startIndex)) != -1) {
//System.out.println(check);
// you need to construct a new string using substring and replacing character at position
encrypt = encrypt.substring(0, pos) + input + encrypt.substring(pos + 1);
//check = line.indexOf(input, check + 1);
startIndex = pos+1;//increment the startIndex,so we will start searching from next character
}
System.out.println(encrypt);
}
}

Search a text file for two strings and display how many strings are in between

How can I use Binary search in Java to find how many strings lie between the two strings given by the user? I have a large text file to search through.
I was thinking ((word position 2 - word position 1)-1) would give the position from an array but I am not quite sure how to put it into code. I got stuck after checking the file for the words.
String[] allWords = new String[400000];
int wordCount = 0;
Scanner input = new Scanner(new File("C:\\text.txt"));
while (input.hasNext()) {
String word = input.next();
allWords[wordCount] = word;
wordCount++;
System.out.println(wordCount);
}
Scanner sc = new Scanner(new File("C:\\text.txt"));
while(sc.hasNextLine()){
String in = sc.nextLine();
System.out.println("Enter a string:");
Scanner sc2 = new Scanner(System.in);
String str = sc2.nextLine();
System.out.println("Enter a string:");
Scanner sc3 = new Scanner(System.in);
String str2 = sc3.nextLine();
if (str.contains(str)) {
System.out.println("yes");
}
if (str.contains(str2)) {
System.out.println("yes");
}
Your math is correct. As you have surmised, subtract one from the difference of the positions. If you have any issues with the code, post your attempt to your question.
You could try something like this pseudocode.
int start
int end
a = startingString
b = startingString
String[] lines = StringFromFile.split("\n");
for(x in lines)
if(x=a)
start = position of x
for(x in lines)
if(x=b)
end = position of x
String[] newLines = Arrays.copyOfRange(lines, start,end)
return newLines.length

How to pause "for" in Java so that I can input some text

I need to solve a problem when take an input of integer which are the number of lines the user wants to input just next to this input(some sentences) as understandable from text as follows:
The first line of input contains a single integer N, indicating the
number of lines in the input. This is followed by N lines of input
text.
I wrote the following code:
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
String lines[] = new String[n];
for(int i = 0; i < n; i++){
System.out.println("Enter " + i + "th line");
lines[i] = scan.nextLine();
}
}
}
And an interaction with the program:
5(The user inputted 5)
Enter 0th line(Program outputted this)
Enter 1th line(Doesn't gave time to input and instantly printed this message)
Hello(Gave time to write some input)
Enter 2th line(Program outputted this)
How(User input)
Enter 3th line(Program outputted this)
Are(User input)
Enter 4th line(Program outputted this)
You(User input)
What's the problem? I can't input 0th line.
Suggest a better method to input n numbers of lines where n is user provided to a string array.
The call to nextInt() is leaving the newline for the 0th call to nextLine() to consume.
Another way to do it would be to consistently use nextLine() and parse the number of lines out of the input string.
Start paying attention to style and code formatting. It promotes readability and understanding.
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());
String lines[] = new String[n];
for (int i = 0; i < n; i++) {
System.out.println("Enter " + i + "th line");
lines[i] = scan.nextLine();
}
}
I don't know what you would consider better:
Try changing
System.out.println("Enter " + i + "th line");
to
System.out.print("Enter " + i + "th line:");
Makes it look better.
A better way of inputting lines would be to keep reading input lines until you see a special termination char.
Use an ArrayList to store the lines then you don't need to declare the size beforehand

Java Finding number of occurrences of a string in another string using nested loops

So I'm new to programming. I'm using java. Right now I have an assignment I can't solve on a website that teaches java.
This is the assignment
Write a program that returns number of occurrences of a string in another string.
E.g
Input:
First String: the
Second String: The children are playing with their toys because they love it.
Output:
3
Note: You should only use nested loops. Don’t use methods like indexOf or substring.
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
String a = input.nextLine();
String b = input.nextLine();
String z[] = b.split(" ");
int number=0;
for (int i =0; i<z.length; i++){
if (z[i].contains(a))number++;
}
System.out.println(number);
I won't give you too much code, but here are the main talking points:
You need a way to read the input in. This can be accomplished with a Scanner - it's either from STDIN or a file.
You need a way to break up each word in the sentence. String#split will help you with that.
You need a way to ignore the casing of each sentence - toLowerCase() works well here.
You need to loop over each word in one sentence, as well as each occurrence in the other sentence. Consider that String.split produces a String[], and you can iterate over that with any standard for loop.
You need a way to see is a string is contained in another string. String#contains will help - although you want to be very careful on which side you're asking contains a string. For example:
// This will print true
System.out.println("The world".toLowerCase().contains("the"));
// This will print false
System.out.println("the".contains("The world".toLowerCase()));
Try this :
import java.util.Scanner;
public class Occurence {
/**
* #param args
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str1 = input.nextLine();
String str2 = input.nextLine();
int count = 0;
String word[] = str1.split(" ");
for (int i = 0; i < word.length; i++) {
if (word[i].toLowerCase().contains(str2.toLowerCase())) {
count++;
}
}
System.out.println("Occurence = " + count);
}
}

Categories

Resources