Finding multiple set of given words in a paragraph array - java

I'm searching for word(s) in a string array and if found I want to return their line.
I have tried to divide the searched input in an array and then search it in the paragraph array line by line. Which does not really work.
public static void main(String[] args) {
String paragraph[] = new String[10];
String toBeSearched;
String curSearch;
boolean intIndex = false ;
paragraph[0] = "Hello my name is";
paragraph[1] = "Jack the reaper";
paragraph[2] = "what up";
System.out.printf("enter string:");
Scanner myScanner = new Scanner(System.in);
toBeSearched = myScanner.nextLine();
String[] divide = toBeSearched.split(" ");
for(int j = 0 ;j <=10 ; j++) {
curSearch = divide[j];
for (int k = 0; k <=paragraph[j].length() ; k++) {
intIndex = paragraph[j].contains(curSearch);
if(intIndex == true) {
System.out.printf("Found at line %d \n",j );
}
}
}
Assuming I can search for at most 10 words at a time.
Lets say user enters : "Hello name the up"
I want the answer : At line 1
At line 1
At line 2
At line 3
If I ask for a word in the 2nd or the 3rd index of the paragraph it does not work I dont understand why (getting no error messages)

Here is a working code compare it to yours and figure out the issue:
public static void main(String[] args)
{
String paragraph[] = {"Hello my name is","Jack the reaper", "what up"};
String toBeSearched;
String curSearch;
boolean intIndex = false ;
System.out.printf("enter string:");
Scanner myScanner = new Scanner(System.in);
toBeSearched = myScanner.nextLine();
String[] divide = toBeSearched.split(" ");
for(int i = 0; i < divide.length ; i ++) {
String word = divide[i];
for(int y = 0; y < paragraph.length ; y++) {
if(paragraph[y].contains(word)) {
System.out.println(word+ "found at line: "+ y);
}
}
}
}

Related

How to print strings after inputting

User inputs int number. Based on that number user can input the same number of strings. For example:
Input:
3
Dave
John
Ben
Output:
Hello, Dave
Hello, John
Hello, Ben
Currently it performs output immediately as only first string is being input:
3
Dave
Hello, Dave
John
Hello, John
Ben
Hello, Ben
What should I change? Can't get it right by myself
public class HelloStrangers {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
String stringNumber = scanner.nextLine();
int number = Integer.parseInt(stringNumber);
if (number < 0) {
System.out.println("Seriously? Why so negative?");
} else if (number == 0) {
System.out.println("Oh, it looks like there is no one here");
} else {
int i = 0;
for (i = 0; i < number; i++) {
String string = scanner.nextLine();
System.out.println("Hello, " + string);
}
}
}
}
Store the input. Print it later.
String[] list = new String[number];
for (int i = 0; i < number; i++) {
String string = scanner.nextLine();
list[i] = string;
}
for (int i = 0; i < number; i++) {
System.out.println("Hello, " + list[i]);
}
You'll need to store the strings in an array and then loop through another loop after saving each one:
String[] strings = new String[number];
for (int i = 0; i < number; i++) {
String string = scanner.nextLine();
strings[i] = string;
}
for (int i = 0; i < number; i++) {
System.out.println("Hello, " + strings[i]);
}

Java Program to Enter a sentence and print the longest word [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 12 months ago.
Improve this question
This a program to enter a sentence and print the longest word using substring()
Here, I have used the 1st loop to extract each word from the sentence and find the length of the longest word.
In the 2nd Loop, its purpose is it to extract and print the word that matches the length which was found out in the 1st loop and stored in the "longestLength" variable.
I am getting an error when i compile the following code:
import java.util.*;
public class Program {
public static void main(String[] args) {
String s, st;
int longestLength = 0;
int i1 = 0;
int i2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter Sentence");
s = sc.nextLine();
s = s.trim();
s = s+" ";
for (int i = 0; i < s.length(); i++) {
if (Character.isWhitespace(s.charAt(i))) {
i2 = i;
st = s.substring(i1, i2);
if (st.length() > longestLength)
longestLength = st.length();
i1 = i;
}
}
for (int i = 0; i < s.length(); i++) {
if (Character.isWhitespace(s.charAt(i))) {
i2 = i;
st = s.substring(i1, i2);
if (st.length() == longestLength) {
System.out.println("Longest Word : " + st);
break;
}
i1=i;
}
}
}
}
Here you don't need to use for loops for just finding the longest word.
Just remove the for loops and add the following lines below that.
Scanner sc = new Scanner(System.in);
System.out.println("Enter Sentence");
s = sc.nextLine();
s = s.trim();
s = s+" ";
String longest = Arrays.stream(s.split(" ")).max(Comparator.comparingInt(String::length)).orElse(null);
System.out.println(longest);
YOUR FINAL CODE WILL BE:
import java.util.*;
public class Program {
public static void main(String[] args) {
String s;
int longestLength = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter Sentence");
s = sc.nextLine();
s = s.trim();
String longest = Arrays.stream(s.split(" ")).max(Comparator.comparingInt(String::length)).orElse(null);
System.out.println(longest);
}
}
It will print the longest word. Hope it will be helpful to you.
There is an alternate easy method to split sentence using delimter using String.spilt(delimiter) funciton.
Below code is an working example for your task
public class Test {
public static void main(String[] args) {
String s, st;
int longestLength = 0;
int i1 = 0;
int i2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter Sentence");
s = sc.nextLine();
String maxString = "";
for(String string : s.split(" ")){
maxString = maxString.length() > string.length() ? maxString : string;
}
System.out.println("The max lengthed string is : "+maxString);
}
}
Your issue is due to i1 has not be resetted to 0 hence the old loop value if i1 is there hence the issue
The solution is given below:
public static void main(String[] args) {
String s, st;
int longestLength = 0;
int i1 = 0;
int i2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter Sentence");
s = sc.nextLine();
s = s.trim();
s = s+" ";
for (int i = 0; i < s.length(); i++) {
if (Character.isWhitespace(s.charAt(i))) {
i2 = i;
st = s.substring(i1, i2);
if (st.length() > longestLength)
longestLength = st.length();
i1 = i;
}
}
i1=0;
for (int i = 0; i < s.length(); i++) {
if (Character.isWhitespace(s.charAt(i))) {
i2 = i;
st = s.substring(i1, i2);
if (st.length() == longestLength) {
System.out.println("Longest Word : " + st);
break;
}
i1=i;
}
}
}

How do I make an Arraylist have the same size?

how do I make two arraylist with the same size
like when I stop at index 5 in the first arraylist the second array list will automatically stop when i reach the index 5
import java.util.*;
public class test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList <String> title = new ArrayList<>();
ArrayList <String> description = new ArrayList<>();
int i = 0;
int d = 0;
String n = in.nextLine();
while(!n.equals(" ")){
System.out.println("Enter a movie title");
title.add(n);
n = in.nextLine();
}
for(;i < title.size(); i++){
System.out.println("[" + i+"]" +title.get(i));
}
description = new ArrayList<>(title.size());
String m = in.nextLine();
while(!m.equals(" ")){
System.out.println("Enter the movie Description");
description.add(m);
m = in.nextLine();
}
description.remove(0);
for(;d < description.size(); d++){
System.out.println("Description for ["+d+"]"+title.get(d)+":"+description.get(d) );
}
}
}
Add a break statement.
// I'm assuming here is where you want it.
// description = new ArrayList<>(title.size());
String m = in.nextLine();
while(!m.equals(" ") && description.size() < title.size()){
System.out.println("Enter the movie Description");
description.add(m);
m = in.nextLine();
}
If you really want the same amount, then don't allow them to exit.
String m = in.nextLine();
while(description.size() < title.size()){
System.out.println("Enter the movie Description");
description.add(m);
m = in.nextLine();
}
for(;d < description.size() && d < title.size(); d++)
This still does not ensure that there are equally many titles and descriptions.
Perhaps you also want to move int i = 0; and int d = 0; into the head of their corresponding for-loops (like for(int i = 0; i < title.size(); i++)). And you may want to change your while-loops to do-while-loops to avoid inserting (and even waiting/"asking" for) the first input line, which will be read before your prompt is written.

Exercise about reading sentences in Java

I'm trying to read a sentence in Java and to know how many words are in there. This is what I've done:
public class TestWords {
public static void main(String[] args) {
System.out.println("Give your phrase");
Scanner extr=new Scanner(System.in);
String Phrase;
Phrase = extr.nextLine();
int TotalSizeOfPhrase = Phrase.length();
double number;
for (int i=0; i < TotalSizeOfPhrase; i++)
{
if (Phrase[i] != number && Character.isWhitespace(s.charAt(i)))
{
TotalWords = TotalWords + 1;
}
}
}
}
And I'd like to know how to code this:
if (Phrase[i]!= 'of an **arbitrary** number && white space')
then:
TotalWords = TotalWords + 1;
Because it marks a mistake when I type this:
Character.isWhitespace(s.charAt(i))
There are couple of mistakes
System.out.println("Give your phrase : ");
Scanner scan = new Scanner(System.in);
String Phrase;
Phrase = scan.nextLine();
System.out.println("Enter age : ");
int number = scan.nextInt();
// replace the number with empty string mean nothing
Phrase = Phrase.replace(String.valueOf(number), "");
Phrase = Phrase.concat(" "); // add space at end for loop calculation
int TotalSizeOfPhrase = 0; // set tot =0
int count=0; // a count variable to keep track of the word length
for (int i=0; i<Phrase.length(); i++)
{
count++;
if(Character.isWhitespace(Phrase.charAt(i)))
{
if(count-1>1){ // if size of word ( -1 is there for space size)
// is greater than 1 than increment count
TotalSizeOfPhrase=TotalSizeOfPhrase+1;
}
count=0;
}
}
System.out.println(TotalSizeOfPhrase);
scan.close();// don't forget
Inuput :
Hello i'm 20 and I'm a beginner
20
output :
5
The way i would do it, is to split the line by white spaces (getting the words), adding them to array and then getting this array length which would be equal to word count.
Phrase = Phrase.trim(); //make sure there is no spaces at start or end of the line
String[] words = Phrase.split(" "); //get the words
int word_count = words.length; //get the word count in line
if you want to get the number of words in the sentence , you could use this code :
int numberOfWords = Phrase.trim().isEmpty() ? 0 : trim.split("\\s+").length;
You can use this code:
public static void main(String[] args) {
System.out.println("Give your phrase");
Scanner extr = new Scanner(System.in);
String Phrase;
Phrase = extr.nextLine();
String[] words = Phrase.trim().split(" ");
System.out.println("Totals Number Of Words: " + words.length);
for (String word : words) {
System.out.println(word.trim());
}
}

Java code to encrypt a given sting

I want a java code to encrypt a given string using 2 main strings like below
s1 = "qwertyuiopasdfghjklzxcvbnm";
s2 = "mnbvcxzasdfghjklpoiuytrewq";
If our input string is "mnb", then it is compared with s2 and the same index in s1 is added 3 then output will be "rty" but I am not getting proper output.
Can any one help me to solve this problem?
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String s1 = "qwertyuiopasdfghjklzxcvbnm";
String s2 = "mnbvcxzasdfghjklpoiuytrewq";
String input,out = "";
System.out.println("enter input string");
input = sc.nextLine();
for(int i=0;i<s2.length();i++){
if(input.charAt(i)==s2.charAt(i)){
out+=s1.charAt(i+3);
}
System.out.println(out);
}
sc.close();
}
You almost had the solution! The problem is when you input one of the last 3 characters of s2 you'll have to use the modulo operator (when the position gets larger than 25 you will reach the end of the string and have to start searching at the beginning!)
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
String s1 = "qwertyuiopasdfghjklzxcvbnm";
String s2 = "mnbvcxzasdfghjklpoiuytrewq";
String input,out = "";
System.out.println("enter input string");
input = sc.nextLine();
for (int i = 0; i < input.length(); i++) {
int position = s2.indexOf(input.charAt(i));
position = (position + 3) % 26;
out = out + s1.charAt(position);
}
sc.close();
}
In order to avoid wrong user input you should check the position if it's -1 (if the character is not found in s2) and handle that case properly (exception/outprint + break in the loop)
You need an extra loop to check which character matches from s2 string.Other than that,you will have to use modulo operator to avoid ArrayIndexOutOfBound.
Try this
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = "qwertyuiopasdfghjklzxcvbnm";
String s2 = "mnbvcxzasdfghjklpoiuytrewq";
String input, out = "";
System.out.println("enter input string");
input = sc.nextLine();
for (int i = 0; i < input.length(); i++) {
for (int j = 0; j < s2.length(); j++) {
if (input.charAt(i) == s2.charAt(j)) {
out += s1.charAt((j + 3)%26);
}
}
}
System.out.println(out);
sc.close();
}
UPDATE
As pointed in comment by #ParkerHalo,to handle ArrayIndexOutOfBound,you can use modulo operator like this
out += s1.charAt((j + 3)%26);

Categories

Resources