Cannot find a word in sentence when using Scanner - java

I just started to learn how to write programs. In this program. I'm trying to find a word in a sentence while using the scanner. However, I ran into a problem. my code is below:
import java.util.Scanner;
public class TestOne {
static Scanner scn = new Scanner(System.in);
public static void main(String[] args) {
if (pick == 5) {
String sentenceFive = "i see you";
String wordFive = "you";
if (sentenceFive.contains(wordFive)) {
System.out.println("Keyword matched the string");
}
else {
System.out.println("No match");
}
} else if (pick == 6) {
System.out.println("Please enter a sentence");
String sentenceFive = scn.nextLine();
scn.nextLine();
System.out.println("Please enter a word");
String wordFive = scn.nextLine();
if (sentenceFive.contains(wordFive)) {
System.out.println("Keyword matched the string");
}
else {
System.out.println("No match");
}
}
}
}
(pick==5) works totally fine but (pick==6) returns "No match".
The if & else statements are both the same and my inputs for (pick==6) are also the same as the strings in (pick==5). So I guess it's because of the scanner, right?

Below code worked, Please refer the comments
import java.util.Scanner;
public class Main {
public static Scanner scn = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Please enter a sentence");
String sentenceFive = scn.nextLine();
// scn.nextLine(); Not needed unless reading another line
System.out.println("Please enter a word");
String wordFive = scn.nextLine();
if (sentenceFive.contains(wordFive)) {
System.out.println("Keyword matched the string");
}
else {
System.out.println("No match");
}
}
}
OUTPUT
PS C:\TEMP\Projects\BU> java Main
Please enter a sentence
i am sam
Please enter a word
am
Keyword matched the string
PS C:\TEMP\Projects\BU>

Related

How do I categorize a list of user inputs into different orders?

I am supposed to make a program that asks users for a list of input. Then, from that list, my program is supposed to pick out the third answer and then print it out. It sounds really simple, but how do I assign numbers to each of the user inputs? Do I even do that? I am a beginner, and thank you so much for your help!
This is the code I have so far:
import java.util.*;
public class MyProgram
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
while(true) {
System.out.println("What do you appreciate in your life or school?");
String ans = scan.nextLine();
if(ans.equals(""))
{
break;
}
}
System.out.println("You said \"" + input3 + "\" as your third answer.");
}
}
You can strore the third input in a variable you initialized bevor the loop.
if there is no third input it prints: ""
import java.util.*;
public class MyProgram
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int index = 0;
String input3 = "";
while(true) {
System.out.println("What do you appreciate in your life or school?");
String ans = scan.nextLine();
if (index == 2) {
input3 = ans;
}
if(ans.equals("")){
break;
}
index++;
}
System.out.println("You said \"" + input3 + "\" as your third answer.");
}
}

Make the program the you if the word you've inputed in the console is a palindrome or not in Java

I've been trying to make this program work, have the person write a word in the console and make the console have an output saying if that word is or isn't a palindrome.
package sct;
import java.util.Scanner;
public class Assignment3Problem4 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a a string: ");
String DAWORD = reader.nextLine();
reader.close();
int n = DAWORD.length();
boolean isPalindrome = true;
for (int i = 0; i < n; ++i) {
if (DAWORD.charAt(i) != DAWORD.charAt(n - i - 1)) {
isPalindrome = false;
break;
}
if (isPalindrome)
System.out.println("This word is a palindrome");
else
System.out.println("This word is not a palindrome");
}
}
}
Sadly, this didn't work and the console doesn't let me input a string, can someone find out why and fix the code?
You shouldn't print whether the word is a palindrome (or not) until after the for loop. That's the only issue I had running the posted code.
Scanner reader = new Scanner(System.in);
System.out.println("Enter a a string: ");
String DAWORD = reader.nextLine();
reader.close();
int n = DAWORD.length();
boolean isPalindrome = true;
for (int i = 0; i < n; ++i) {
if (DAWORD.charAt(i) != DAWORD.charAt(n - i - 1)) {
isPalindrome = false;
break;
}
}
if (isPalindrome)
System.out.println("This word is a palindrome");
else
System.out.println("This word is not a palindrome");
You might want to remove reader.close() (as that also closes System.in).
Another approach you could consider is putting your input into a StringBuilder object, reverse it, then check if it equals your input.
Something like:
import java.util.Scanner;
public class StackOverflow {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a string: ");
String DAWORD = reader.nextLine();
reader.close();
if (new StringBuilder(DAWORD).reverse().toString().contentEquals(DAWORD))
System.out.println("This word is a palindrome");
else
System.out.println("This word is not a palindrome");
}
}
Result:
Enter a string:
racecar
This word is a palindrome
You can also use an external apache lang library from here https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.7. Then you can use StringUtils.reverse() method which reverses a string and then compare reversed string with the normal one , like so:
import org.apache.commons.lang3.StringUtils;
public class Main4 {
public static void main(String[] args) {
String str = "kajak";
String str2 =StringUtils.reverse(str);
if (str2.equals(str)){
System.out.println("It's a palidrom");
}
else{
System.out.println("Not a palidorm");
}
}
}

Java - prompting user to input commands and throw error if unrecognizable

I am trying to write a code that will prompt the user to enter some instructions. If the user inputs the command "echo" + word, it will be displaying the word itself on the next line. Then the prompt will appear again waiting for another input.
The program should display an error if the command that was entered is unknown. I'm having issues here as the program is not displaying the error message.
In addition, if the user does not type anything and just press enter, it should just simply display again the prompt on the next line, however it's not doing it.
Hopefully, you can help me..
import java.util.Scanner;
import java.io.*;
public class Prompter {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
String sInstruct, sTerm;
System.out.print("Enter:> ");
sInstruct = sc.next();
sTerm = sc.nextLine();
try {
if (sInstruct.equals("")){
while(sInstruct.equals(""))
{
System.out.print("Enter:> ");
sInstruct = sc.next();
}
} else if (sInstruct.equals("echo")){
while (sInstruct.equals("echo"))
{
sayWord(sInstruct, sTerm);
System.out.print("Enter:> ");
sInstruct = sc.next();
sTerm = sc.nextLine();
}
}
}
catch(Exception error){
System.out.print("Invalid command " + sInstruct);
}
sc.close();
}
public static void sayWord (String sInstruct, String sTerm){
System.out.println(sTerm);
}
}
Output should be:
Enter:> echo hello brown fox
hello brown fox
Enter:>
Enter:>
Enter:> eccoh hello
Invalid command eccoh
Enter:>
I see some problems in your code:
Using sInstruct and sTerm at the same time is an overkill, you should use only sTerm since it will contain the complete instruction
The while loop must be outside the if conditions and should check for a sc.hasNextLine()
To check if the entered string is empty, you should do it using sTerm.isEmpty()
To check if the entered string starts with echo, you should do it using sTerm.startsWith("echo")
The check for an invalid instruction, must be set inside the while loop.
The try-catch clause is not needed.
See the proposed solution:
import java.util.Scanner;
import java.io.*;
public class Prompter {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
String sTerm;
System.out.print("Enter:> ");
while(sc.hasNextLine()) {
sTerm = sc.nextLine();
if(sTerm.isEmpty()) {
} else if (sTerm.startsWith("echo")) {
sayWord(sTerm.substring(5));
} else {
System.out.println("Invalid command " + sTerm.split(" ")[0]);
}
System.out.print("Enter:> ");
}
sc.close();
}
public static void sayWord (String sTerm){
System.out.println(sTerm);
}
}
Or, if you prefer, the if-else clauses could be even more compacted:
if (sTerm.startsWith("echo")) {
sayWord(sTerm.substring(5));
} else if(!sTerm.isEmpty()) {
System.out.println("Invalid command " + sTerm.split(" ")[0]);
}

Need to have a string "Enter a number: " repeat

As the title said I need to enter a string "Enter a number: " repeat itself after I've entered multiple values until I enter "DONE."
So for example it should look like this:
Enter a number:
4
Enter a number:
53
Enter a number:
DONE //closes program
This is a small part to a larger program and granted I know its simple, but I cant figure this out :[
What I'm guessing and been trying is a public static class with a toString method. But I can only get one "Enter a number: " printed once.
Enter a number:
4
53
DONE //closes program
Thanks in advance.
Some code I have for this part would be:
import java.util.Scanner;
public class EnterANumba
{
public static void main(String[] args)
{
while() //Stuck here
{
System.out.println("Enter a number:");
}
Scanner scanner = new Scanner(System.in);
String word=null;
while (scanner.hasNextLine())
{
word = scanner.nextLine();
if (word != null)
{
word = word.trim();
if (word.equalsIgnoreCase("done"))
{
break;
}
}
else
{
break;
}
}
I guess this following code snippet may help you.
public class Main {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("Enter a number:");
while(!(s.next().equalsIgnoreCase("DONE"))){
System.out.println("Enter a number:");
}
}
}
try asking for the 1st time and then make a loop where you validate the input and ask until the condition is met...
Example:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a number:");
while (!("done".equalsIgnoreCase(scanner.next()))) {
System.out.println("Enter a number:");
}
System.out.println("Enter a number:we are done....");
}

Multi-word scanner input in java?

So I'm trying to use if-else statement dependant upon the user's input. It works when the user's input is only one word, however, multiple word inputs go unrecognized and triggers the else statement. How can i resolve this?
import java.util.Scanner;
public class MyFirstJavaClass {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner myScanner = new Scanner(System.in);
String answer;
System.out.println("Catch the tiger or run away?");
answer = myScanner.next();
if (answer.equals("Catch the tiger" )) {
System.out.println("You've been mauled by a tiger! What were you thinking?");
answer = myScanner.next();
} else {
System.out.println("run away");
}
}
}
Replace:
answer = myScanner.next();
With:
answer = myScanner.nextLine();
next will only read in the next value until it reaches a space or newline. You want to read in the full line before making the comparison
try this :
Scanner scanner = new Scanner(System.in);
int choice = 0;
while (scanner.hasNext()){
if (scanner.hasNextInt()){
choice = scanner.nextInt();
break;
} else {
scanner.next(); // Just discard this, not interested...
}
}
Reference :
Flush/Clear System.in (stdin) before reading
Try this
import java.util.Scanner;
public class MyFirstJavaClass {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner myScanner = new Scanner(System.in);
System.out.println("Catch the tiger or run away?");
if (myScanner.hasNext("Catch the tiger")) {
System.out.println("You've been mauled by a tiger! What were you thinking?");
} else {
System.out.println("run away");
}
}
}

Categories

Resources