Can I use startsWith and endsWith in Java to check input? - java

In Java can I use startsWith and endsWith to check a user input string? Specifically, to compare first and last Characters of the input?
EDIT1: Wow you guys are fast. Thank you for the responses.
EDIT2: So CharAt is way more efficient.
So How do I catch the First and last Letter?
char result1 = s.charAt(0);
char result2 = s.charAt(?);
EDIT3: I am very close to making this loop work, but something is critically wrong.
I had some very good help earlier, Thank you all again.
import java.util.Scanner;
public class module6
{
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
while(true){
System.out.print("Please enter words ending in 999 \n");
System.out.print("Word:");
String answer;
answer = scan.next();
char aChar = answer.charAt(0);
char bChar = answer.charAt(answer.length()-1);
String MATCH = new String("The word "+answer+" has first and last characters that are the same");
String FINISH = new String("Goodbye");
if((aChar == bChar));
{
System.out.println(MATCH);
}
if(answer !="999")
{
System.out.println(FINISH);
break;
}
}
}
}
The loop just executes everything, No matter what is input. Where did I go wrong?

In Java can I use startsWith and endsWith to check a user input string?
You certainly can: that is what these APIs are for. Read the input into a String, then use startsWith/endsWith as needed. Depending on the API that you use to collect your input you may need to do null checking. But the API itself is rather straightforward, and it does precisely what its name says.
Specifically, to compare first and last Characters of the input?
Using startsWith/endsWith for a single character would be a major overkill. You can use charAt to get these characters as needed, and then use == for the comparison.

yes, you should be able to do that and it should be pretty striaghtforward. Is there a complexity that you are not asking?

Yes, in fact, not just characters, but entire strings too.
For example
public class SOQ4
{
public static void main(String[] args)
{
String example = "Hello there my friend";
if(example.startsWith("Hell"))
{
System.out.println("It can do full words");
}
if(example.startsWith("H"))
{
System.out.println("And it can also do letters");
}
if(example.endsWith("end"))
{
System.out.println("Don't forget the end!");
}
if(example.endsWith("d"))
{
System.out.print("Don't forget to upvote! ;)");
}
}
}
I recommend you use the API, here's a link to it http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

Related

Is there a way to write this program using another method than .hasNext?

Write a program that asks a user to input a string. Then asks a user to type in an index value(integer). You will use the charAt( ) method from the string class to find and output the character referenced by that index. Allow the user to repeat these actions by placing this in a loop until the user gives you an empty string. Now realize that If we call the charAt method with a bad value (a negative value or a integer larger than the size of the string) an exception will be thrown. Add the code to catch this exception, output a warning message and then continue with the loop
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
System.out.println("");
String s;
int ind;
Scanner sc=new Scanner(System.in);
while(sc.hasNext())
{
s=sc.next();
if(s.length()==0)
break;
ind=sc.nextInt();
try {
char ch=s.charAt(ind);
System.out.println("Character is "+ch);
}
catch(Exception e) {
System.out.println("Bad index Error!");
}
}
}
}
Yes. You could rely on assignment evaluating to the assigned value. Also, call Scanner.hasNextInt() before calling Scanner.nextInt(). Like,
System.out.println();
String s;
Scanner sc = new Scanner(System.in);
while (sc.hasNext() && !(s = sc.next()).isEmpty()) {
if (sc.hasNextInt()) {
int ind = sc.nextInt();
try {
char ch = s.charAt(ind);
System.out.println("Character is " + ch);
} catch (Exception e) {
System.out.println("Bad index Error!");
}
}
}
There is a bug; sc.next() cannot return an empty string in this code. Try editing it this way:
while(sc.hasNext()) {
s = sc.next();
if(s.length() == 0) {
System.out.println("Woah, Nelly!");
break;
}
// ...
}
See if you can get the program to print "Woah, Nelly!" by entering a blank line, or anything else. I can't, and assuming I understand the documentation correctly, it is impossible for the if condition to ever be true here (emphasis mine):
Depending upon the type of delimiting pattern, empty tokens may be returned. For example, the pattern "\\s+" will return no empty tokens since it matches multiple instances of the delimiter. The delimiting pattern "\s" could return empty tokens since it only passes one space at a time.
This pattern "\\s+" is the default one, and you haven't set a different one, so your scanner should never return an empty token. So the strict answer to "is there a way to write this program without the break statement?" is: yes, you can just delete the if(...) break; code and it doesn't change the behaviour in any way.
However, that's not really a solution to your problem because it doesn't give the user a way to exit the program. You should use nextLine() instead of next() to allow reading a blank line from the user.

Java - Scanner doesn't read string with space (Solved)

I am trying to allow an input that is only made with characters a-zA-Z and also haves space. Example: "Chuck Norris".
What happens with the code below is that the scanner input.next() doesn't allow the mentioned example input string.
I expect this output: Success! but this is the actual output: Again:
try {
String input_nome = input.next(); // Source of the problem
if (input_nome.matches("[a-zA-Z ]+")) {
System.out.print("Success!");
break;
} else {
System.err.print("Again: ");
}
} catch (Exception e) {
e.printStackTrace();
}
SOLUTION
The source of the problem is the used scanner method.
String input_nome = input.next(); // Incorrect scanner method
String input_nome = input.nextLine(); // Correct scanner method
Explanation: https://stackoverflow.com/a/22458766/11860800
String t = "Chuck Norris";
t.matches("[a-zA-Z ]+")
Does in fact return true. Check for your input that it actually is "Chuck Norris", and make sure the space is not some weird character. Also instead of space, you can use \s. I also recommend 101regex.com
Please refer this link :
Java Regex to Validate Full Name allow only Spaces and Letters
you can use the below Regular Expression
String regx = "^[\\p{L} .'-]+$";
This should work for all scenarios and unicode.

How do you take part of a string and move the first few letters to the end of the string

I am trying to take a user inputted string and move the first letters before the first vowel to the end of the string. I'm stuck here, and just need a suggestion.
This is in java by the way
Find the index at which the first vowel is (suppose x), then use substring..
String modified = mystring.substring(x, mystring.length()) + mystring.substring(0, x);
Read the api for what substring actually does.
Okay. Here's the main method of the program that does what you need.
public static void main(String args[]){
String s;
int i=0;
//presume s gets user's input here
for(i=0;i<s.length();i++){
char c=s.charAt(i);
if(c=='a'||c=='A'||c=='e' || ...)
break;
}
if(i!=(s.length()-1)){
for(int j=i;j<s.length();j++)
System.out.print(s.charAt(j));
//displays from first vowel to end of string
}
else{
System.out.println("String ain't got any vowels.");
}
}

Censored Words Condition

I need this program to print "Censored" if userInput contains the word "darn", else print userInput, ending with newline.
I have:
import java.util.Scanner;
public class CensoredWords {
public static void main (String [] args) {
String userInput = "";
Scanner scan = new Scanner(System.in);
userInput = scan.nextLine;
if(){
System.out.print("Censored");
}
else{
System.out.print(userInput);
}
return;
}
}
Not sure what the condition for the if can be, I don't think there is a "contains" method in the string class.
The best solution would be to use a regex with word boundary.
if(myString.matches(".*?\\bdarn\\b.*?"))
This prevents you from matching sdarnsas a rude word. :)
demo here
Try this:
if(userInput.contains("darn"))
{
System.out.print("Censored");
}
Yes that's right, String class has a method called contains, which checks whether a substring is a part of the whole string or not
Java String Class does have a contains method. It accepts a CharSequence object. Check the documentation.
Another beginner method would be to use the indexOf function. Try this:
if (userInput.indexOf("darn") > 0) {
System.out.println("Censored");
}
else {
System.out.println(userInput);

String.replace() method not printing full string in java

I'm trying to do some homework for my computer science class and I can't seem to figure this one out. The question is:
Write a program that reads a line of text and then displays the line, but with the first occurrence of hate changed to love.
This sounded like a basic problem, so I went ahead and wrote this up:
import java.util.Scanner;
public class question {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text:");
String text = keyboard.next();
System.out.println("I have rephrased that line to read:");
System.out.println(text.replaceFirst("hate", "love"));
}
}
I expect a string input of "I hate you" to read "I love you", but all it outputs is "I". When it detects the first occurrence of the word I'm trying to replace, it removes the rest of the string, unless it's the first word of the string. For instance, if I just input "hate", it will change it to "love". I've looked at many sites and documentations, and I believe I'm following the correct steps. If anyone could explain what I'm doing wrong here so that it does display the full string with the replaced word, that would be fantastic.
Thank you!
Your mistake was on the keyboard.next() call. This reads the first (space-separated) word. You want to use keyboard.nextLine() instead, as that reads a whole line (which is what your input is in this case).
Revised, your code looks like this:
import java.util.Scanner;
public class question {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text:");
String text = keyboard.nextLine();
System.out.println("I have rephrased that line to read:");
System.out.println(text.replaceFirst("hate", "love"));
}
}
Try getting the whole line like this, instead of just the first token:
String text = keyboard.nextLine();
keyboard.next() only reads the next token.
Use keyboard.nextLine() to read the entire line.
In your current code, if you print the contents of text before the replace you will see that only I has been taken as input.
As an alternate answer, build a while loop and look for the word in question:
import java.util.Scanner;
public class question {
public static void main(String[] args)
{
// Start with the word we want to replace
String findStr = "hate";
// and the word we will replace it with
String replaceStr = "love";
// Need a place to put the response
StringBuilder response = new StringBuilder();
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text:");
System.out.println("<Remember to end the stream with Ctrl-Z>");
String text = null;
while(keyboard.hasNext())
{
// Make sure we have a space between characters
if(text != null)
{
response.append(' ');
}
text = keyboard.next();
if(findStr.compareToIgnoreCase(text)==0)
{
// Found the word so replace it
response.append(replaceStr);
}
else
{
// Otherwise just return what was entered.
response.append(text);
}
}
System.out.println("I have rephrased that line to read:");
System.out.println(response.toString());
}
}
Takes advantage of the Scanner returning one word at a time. The matching will fail if the word is followed by a punctuation mark though. Anyway, this is the answer that popped into my head when I read the question.

Categories