Comparing a string in an array with an input string? - java

I am trying to make a program that reads a string from a file and split it and take a string from an array and compare it with the string that the user will input.
If they are equal then it will print it but when i use .contains in my code it prints a different string of the array that contain the word i write to compare with.
If i use .equal, it doesn't work
public static void main(String[] args) throws Exception
{
String word;
System.out.println("Enter word");
Scanner sc=new Scanner(System.in);
word=sc.next();
FileReader file =new FileReader("C:\\Users\\mypc\\Downloads\\ArabicTrans_final.txt");
BufferedReader reader=new BufferedReader(file);
String text="";
String line=reader.readLine();
while(line !=null)
{
text+=line;
line=reader.readLine();
}
String str=text;
String parts[]=str.split("-");
int no=0;
for (int i=0;i<parts.length;i++)
{
System.out.println(parts[i]);
}
for (int i=0;i<parts.length;i++)
{
if(parts[i].contains(word))
{
System.out.println("num"+i);
no=i;
}
}
String newstring[]=parts[no].split(",");
for (int i=0;i<newstring.length;i++)
{
System.out.println("You said : "+newstring[1]);
break;
}
}
}
inside text file there is some words with arabic translation that i want to show as the result of writing the english word as an input
whats,واتس-
whatsapp,واتس اب -
men,من-
yemen,يمين-
if i write whats it will show whatsapp not whats

Related

Writing a program in Java to read in multiple strings from user and compare to text file

I am attempting to write a program that will take user input ( a long message of characters), store the message and search a text file to see if those words occur in the text file. The problem I am having is that I am only ever able to read in the first string of the message and compare it to the text file. For instance if I type in "learning"; a word in the text file, I will get a result showing that is is found in the file. However if I type "learning is" It will still only return learning as a word found in the file even though "is" is also a word in the text file. My program seems to not be able to read past the blank space. So I suppose my questions is, how do I augment my program to do this and read every word in the file? Would it also be possible for my program to read every word, with or without spaces, in the original message taken from the user, and compare that to the text file?
Thank you
import java.io.*;
import java.util.Scanner;
public class Affine_English2
{
public static void main(String[] args) throws IOException
{
String message = "";
String name = "";
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
System.out.println("Please enter in a message: ");
message = scan.next();
Scanner file = new Scanner(new File("example.txt"));
while(file.hasNextLine())
{
String line = file.nextLine();
for(int i = 0; i < message.length(); i++)
{
if(line.indexOf(message) != -1)
{
System.out.println(message + " is an English word ");
break;
}
}
}
}
}
I recommend you first process the file and build a set of legal English words:
public static void main(String[] args) throws IOException {
Set<String> legalEnglishWords = new HashSet<String>();
Scanner file = new Scanner(new File("example.txt"));
while (file.hasNextLine()) {
String line = file.nextLine();
for (String word : line.split(" ")) {
legalEnglishWords.add(word);
}
}
file.close();
Next, get input from the user:
Scanner input = new Scanner(System.in);
System.out.println("Please enter in a message: ");
String message = input.nextLine();
input.close();
Finally, split the user's input to tokens and check each one if it is a legal word:
for (String userToken : message.split(" ")) {
if (legalEnglishWords.contains(userToken)) {
System.out.println(userToken + " is an English word ");
}
}
}
}
You may try with this. With this solution you can find each word entered by the user in your example.txt file:
public static void main(String[] args) throws IOException
{
String message = "";
String name = "";
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
System.out.println("Please enter in a message: ");
message = scan.nextLine();
Scanner file = new Scanner(new File("example.txt"));
while (file.hasNextLine())
{
String line = file.nextLine();
for (String word : message.split(" "))
{
if (line.contains(word))
{
System.out.println(word + " is an English word ");
}
}
}
}
As Mark pointed out in the comment, change
scan.next();
To:
scan.nextLine();
should work, i tried and works for me.
If you can use Java 8 and Streams API
public static void main(String[] args) throws Exception{ // You need to handle this exception
String message = "";
Scanner input = new Scanner(System.in);
System.out.println("Please enter in a message: ");
message = input.nextLine();
List<String> messageParts = Arrays.stream(message.split(" ")).collect(Collectors.toList());
BufferedReader reader = new BufferedReader(new FileReader("example.txt"));
reader.lines()
.filter( line -> !messageParts.contains(line))
.forEach(System.out::println);
}
You have many solution, but when it comes to find matches I suggest you to take a look to the Pattern and Matcher and use Regular Expression
I haven't fully understood your question, but you could do add something like this (I did not tested the code but the idea should work fine):
public static void main(String[] args) throws IOException{
String message = "";
String name = "";
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
System.out.println("Please enter in a message: ");
message = scan.next();
Scanner file = new Scanner(new File("example.txt"));
String pattern = "";
for(String word : input.split(" ")){
pattern += "(\\b" + word + "\\b)";
}
Pattern r = Pattern.compile(pattern);
while(file.hasNextLine())
{
String line = file.nextLine();
Matcher m = r.matcher(line);
if(m.matches()) {
System.out.println("Word found in: " + line);
}
}
}

Reading multiple lines into a scanner object in Java

I'm having a bit of trouble figuring out how to read multiple lines of user input into a scanner and then storing it into a single string.
What I have so far is down below:
public static String getUserString(Scanner keyboard) {
System.out.println("Enter Initial Text:");
String input = "";
String nextLine = keyboard.nextLine();
while(keyboard.hasNextLine()){
input += keyboard.nextLine
};
return input;
}
then the first three statements of the main method is:
Scanner scnr = new Scanner(System.in);
String userString = getUserString(scnr);
System.out.println("\nCurrent Text: " + userString );
My goal is to have it where once the user types their text, all they have to do is hit Enter twice for everything they've typed to be displayed back at them (following "Current text: "). Also I need to store the string in the variable userString in the main (I have to use this variable in other methods). Any help at all with this would be very much appreciated. It's for class, and we can't use arrays or Stringbuilder or anything much more complicated than a while loop and basic string methods.
Thanks!
Using BufferedReader:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = "";
String line;
while((line = br.readLine()) != null){
if(line.isEmpty()){
break; // if an input is empty, break
}
input += line + "\n";
}
br.close();
System.out.println(input);
Or using Scanner:
String input = "";
Scanner keyboard = new Scanner(System.in);
String line;
while (keyboard.hasNextLine()) {
line = keyboard.nextLine();
if (line.isEmpty()) {
break;
}
input += line + "\n";
}
System.out.println(input);
For both cases, Sample I/O:
Welcome to Stackoverflow
Hello My friend
Its over now
Welcome to Stackoverflow
Hello My friend
Its over now
Complete code
public static void main (String[] args) {
Scanner scnr = new Scanner(System.in);
String userString = getUserString(scnr);
System.out.println("\nCurrent Text: " + userString);
}
public static String getUserString(Scanner keyboard) {
System.out.println("Enter Initial Text: ");
String input = "";
String line;
while (keyboard.hasNextLine()) {
line = keyboard.nextLine();
if (line.isEmpty()) {
break;
}
input += line + "\n";
}
return input;
}

Why won't my code find a period after typing the sentence?

Why won't my code find a period after typing the sentence? The user is supposed to write a sentence and then put a period at the end. When the period is entered then the program should end. Help?
import java.io.*;
class Sentence
{
public static void main(String[] args) throws IOException
{
InputStreamReader inStream = new InputStreamReader (System.in);
BufferedReader mVHS = new BufferedReader (inStream);
String inData; //Store the input data in a String
int result;//Assign the result to the int data type
String sentence, string2; //Store the names in the String type
//Enter a sentance
System.out.println("Type a sentence but make sure it ends with a period:");
Sting userInput = mVHS.readLine();
sentence = userInput;
while(sentence.length()){
{
if(sentence.equals("."))
System.out.println("Thank you come again.");
else
System.out.println("You must put a period to end the program");
System.out.println("Type a period:");
userInput = mVHS.readLine();
sentence = userInput;
}
}
}
}
while(sentence.length()){
{
if(sentence.equals("."))
the while statement has an invalid expression in it.
and: sentence.equals(".") will only return true, if you entered nothing but .
you can check: if sentence.endsWith(".");

Java simple counting words in a file

I am creating a simple program that counts the number of words, lines and total characters (not including whitespace) in a paper. It is a very simple program. My file compiles but when I run it I get this error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1347)
at WordCount.wordCounter(WordCount.java:30)
at WordCount.main(WordCount.java:16)
Does anyone know why this is happening?
import java.util.*;
import java.io.*;
public class WordCount {
//throws the exception
public static void main(String[] args) throws FileNotFoundException {
//calls on each counter method and prints each one
System.out.println("Number of Words: " + wordCounter());
System.out.println("Number of Lines: " + lineCounter());
System.out.println("Number of Characters: " + charCounter());
}
//static method that counts words in the text file
public static int wordCounter() throws FileNotFoundException {
//inputs the text file
Scanner input = new Scanner(new File("words.txt"));
int countWords = 0;
//while there are more lines
while (input.hasNextLine()) {
//goes to each next word
String word = input.next();
//counts each word
countWords++;
}
return countWords;
}
//static method that counts lines in the text file
public static int lineCounter() throws FileNotFoundException {
//inputs the text file
Scanner input2 = new Scanner(new File("words.txt"));
int countLines = 0;
//while there are more lines
while (input2.hasNextLine()) {
//casts each line as a string
String line = input2.nextLine();
//counts each line
countLines++;
}
return countLines;
}
//static method that counts characters in the text file
public static int charCounter() throws FileNotFoundException {
//inputs the text file
Scanner input3 = new Scanner(new File("words.txt"));
int countChar = 0;
int character = 0;
//while there are more lines
while(input3.hasNextLine()) {
//casts each line as a string
String line = input3.nextLine();
//goes through each character of the line
for(int i=0; i < line.length(); i++){
character = line.charAt(i);
//if character is not a space (gets rid of whitespace)
if (character != 32){
//counts each character
countChar++;
}
}
}
return countChar;
}
}
I can't really say the exact reason for the problem without looking at the file (Maybe even not then).
while (input.hasNextLine()) {
//goes to each next word
String word = input.next();
//counts each word
countWords++;
}
Is your problem. If you are using the input.hasNextLine() in the while conditional statement use input.nextLine(). Since you are using input.next() you should use input.hasNext() in the while loops conditional statement.
public static int wordCounter() throws FileNotFoundException
{
Scanner input = new Scanner(new File("words.txt"));
int countWords = 0;
while (input.hasNextLine()) {
if(input.hasNext()) {
String word = input.next();
countWords++;
}
}
return countWords;
}
I have just added an if condition within the while loop. Just make sure to check there are token to be parsed. I have changed only in this place. Just make sure to change wherever needed.
This link will give good info. in regard to that.
Hope it was helpful. :)

compare character with single space java

i'm trying to test a program that will print "space" if the user enters a single space.
but nothings displayed when i hit space then enter. my aim was really to count the number of spaces but i guess i'll just start with this. help me guys, thanks for any help
here's my code
import java.util.Scanner;
public class The
{
public static void main(String args[])throws Exception
{
Scanner scanner = new Scanner(System.in);
String input;
System.out.println("Enter string input: ");
input = scanner.next();
char[] charArray;
charArray = input.toCharArray();
for(char c : charArray)
{
if(c == ' ')
{
System.out.println("space");
}
else
{
System.out.println(" not space");
}
}
}
}
Scanner ignores spaces by default. Use BufferedReader to read input.
By default, Scanner will ignore all whitespace, which includes new lines, spaces, and tabs. However, you can easily change how it divides your input:
scanner.useDelimiter("\\n");
This will make your Scanner only divide Strings at new line, so it will "read" all the space characters up until you press enter. Find more customization options for the delimiters here.
public class CountSpace {
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String word=null;
System.out.println("Enter string input: ");
word = br.readLine();
String data[] ;
int k=0;
data=word.split("");
for(int i=0;i<data.length;i++){
if(data[i].equals(" "))
k++;
}
if(k!=0)
System.out.println(k);
else
System.out.println("not have space");
}
}

Categories