I want to create a boolean method that allows me to check if the characters in one string randomly generated in a method before contains characters from a string that the user inputs.
Example:
Random base word: Cellphone
User word: Cell --> Yes this is okay.
User word: Cells --> No, it contains letters not found in original word given.
I'm thinking we can maybe do something that looks like this:
public static class boolean usesSymbolsFromWord(String candidate, String base) {
//pseudocode
characters in String candidate are found in String base
return true;
}
return false;
}
Just try it with a build in method of Java.lang.String:
base.contains(candidate);
That's all.
For further informations see the Java Docs:
contains(CharSequence s)
Returns true if and only if this string
contains the specified sequence of char values.
try this func
boolean allS1CharsAreInS2(String s1, String s2) {
for(int i = 0; i < s1.length(); i++) {
char c = s1.charAt(i);
if (s2.indexOf(c) == -1) {
return false;
}
}
return true;
}
I normally use : word1.toUpperCase().contains(word2.toUpperCase()) as I prefer case insensitive check. But its based on your requirement. If it has to be case sensitive checking, you can use word1.contains(word2)
Related
I have a task to write a return type method which takes String as an argument and returns boolean. If the String matches with the requirements it returns true else false.
So it should not have any space, and more then 1 '#'and format must be 2>chars#2>chars.2>chars so it should be xyz#xyz.com is true but if any part of it less then 3 it should return to false. I checked so many forums but all i can find regex and we didn't learn anything about it. I could able to do this much but i just couldn't figure out how can i specifically set length of each part and set it as true or false. I'm missing so many and this is all i able to complete;
public static boolean emailAddress(String str) {
if (str.contains(" "))
return false;
boolean flag = true;
if(str3.length()> 11)
for (int i = 0; i < str3.length(); i++) {
for (int j = i + 1; j < str3.length(); j++) {
if (str3.charAt(i) == str3.charAt(j)) {
flag = false;
break;
}
}
if(flag)
return true;
}
return false;
}
This is how I would approach it:
public static boolean isEmailAddress(String str)
{
if(str.trim().equals("")) // Checking if it is an empty string
{
return false;
}
boolean flag = true;
int atIndex = str.indexOf("#"); // Get the index of #
if (atIndex == -1)
{
return false;
}
// Slice your email str and get only the characters before the #
// Check whether the length and the characters are as you want them.
// Do the same thing about the string between # and .
// and then do the same thing about the sliced string after .
}
Check substring() and indexOf().
For anyone who needs it.
This should be one of the Regex to match your requirement:
[a-zA-Z_0-9]{2,}#[a-zA-Z_0-9]{2,}\.[a-zA-Z_0-9]{2,}
[a-zA-Z_0-9] it requires one of the characters, from a-z,A-Z or 0-9
{2,} it requires two or more from one of the characters inside.
A few hints instead of complete solution:
Check if the input string...
has # and . (there could be two or three period's as some domain uses .co.in)
does not have any white spaces (' ')
does not start with special characters ('#', '^')
If possible, do not check for length of each part, as sometimes .in also valid domain.
I am writing a Java program that can convert an inputted Roman Numeral into a Short, and I want it to be able to recognize and ask for input again when any letter has been inputted besides a Roman Numeral (I, V, X, L, C, D, and M).
Is there a method similar to .contains(), but with the opposite function?
Or do I have to check each individual letter with some kind of loop?
Well of course, you need some type of filter to test against the input.
One solution could be to use a string that contains all the possible valid characters in the input and then return false if a character wasn't found in the filter.
public class HelloWorld
{
public static boolean filter(String test, String filter) {
for(int i = 0; i < test.length(); i++) {
if (filter.indexOf(test.charAt(i)) == -1) {
return false;
}
}
return true;
}
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
System.out.println(filter("XDQX", "XDQ"));
}
}
I suggest you use a regular expression to check whether the input is a Roman numeral. You can find a regular expression for this problem here. Use String#matches() to determine whether your input matches the regex.
if(!input.matches("^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$")) { // input is the String the user entered
// handle invalid input here
}
Just testing for valid characters, not for a valid sequence, can be done with contains:
boolean roman (String s)
{
for (char c: s.toCharArray())
if (! "IVXCLDM".contains(""+c))
return false;
return true;
}
However, I would prefer a regular expression
boolean roman (String s)
{
return s.matches ("[IVXCLDM]+");
}
which means any number(+) of characters from that Set, at least one.
I need to write a program where the main reads two strings as input: if the strings have the same length, then it has to pass the whole first string and the first char of the second string to a method called find, which has to return 'true' if the character appears even a single time on the string. If the length differs, then it will pass the whole second sentence and the last char of the first string to find. At last, the main will give whatever the method returns as output, so it has to be true, or false. I've created the whole main, and it works correctly, but I have no idea how to create the find method. Here is the code:
import java.util.Scanner;
public class Exercise {
/*
* public static boolean find(String... sentence, char... character) {
* // No, I can't use multiple varargs...
* }
*/
public static void main(String[] args) {
String first, second;
char firstChar, lastChar;
Scanner keyboard = new Scanner(System.in);
int lengthFirst, lengthSecond;
boolean goal = true;
first = keyboard.nextLine();
lengthFirst = first.length();
lastChar = first.charAt(lengthFirst - 1);
second = keyboard.nextLine();
lengthSecond = second.length();
firstChar = second.charAt(0);
System.out.println("Length 1: " + lengthFirst); // Those lines are test lines.
System.out.println("Length 2: " + lengthSecond); // They're here just to check
System.out.println("Char 1: " + firstChar); // if everything else works.
System.out.println("Char 2: " + lastChar);
if (lengthFirst == lengthSecond) {
goal = find(first, firstChar);
System.out.println("Goal is: " + goal);
System.exit(0);
} else
goal = find(second, lastChar);
System.out.println("Goal is: " + goal);
System.exit(0);
}
}
I was thinking about using the varargs option, using a varargs for the String, and another for the char, and then using a 'for' loop inside of the method to check if the character appears or not, and everything was easy on my head...but with some research I found out it will be a waste of time, because I can't use two varargs on the same method. The for loop idea works, but I can't figure out how to pass only the right String and the right Char. How should I pass them to the method, without passing them both?
Edit: No, this is not a duplicate. I allow loops, the other question doesn't. Also, my problem is about how am I supposed to pass multiple variables, but then using just some. That's an example:
The strings are both long 50, so the method needs to use only 'first' as String, and 'firstChar' as Char.
You can use String.indexOf().
returns the index within this string of the first occurrence of the
specified character. If a character with value ch occurs in the
character sequence represented by this String object, then the index
(in Unicode code units) of the first such occurrence is returned, if
no such character occurs in this string, then -1 is returned.
public static boolean find(String str, char ch){
if(str.indexOf(ch) == -1)
return false;
return true;
}
As you are thinking, you don't need four parameters for this function. You can use this function with two parameters for both cases:
goal = find(first, firstChar);
goal = find(second, lastChar);
EDIT I think you have misunderstood the way the parameters are mapped.
if you have a function like
public static boolean find(String str, char ch){
//do something
}
You don't need to call the find with same parameters str and ch, I mean find(str,ch). You can call them with any parameter, with any name, like :
goal = find(s,c); // s is a string and c is a char
goal = find(a,b); // a is a string and b is a char
when you call find(s,c), s will be mapped to the first argument in your function that is str and c will be mapped to your second argument that is ch.
This is the reason you are able to call both find(first, firstChar) and find(second, lastChar) with a single function.
private static boolean find(String str, char Char) {
for(int i=0;i<str.length();i++)
if(str.charAt(i)==Char)
return true;
return false;
}
This would help hopefully...
Seems like what you are looking for is:
if (second.indexOf(c) == -1) return false; //char c not found
return true;
Find will simply contain
private boolean find(String subject, char first) {
return subject.indexOf(first) > -1;
}
I am attempting to create a method that checks every character in userInput to see if they are present in operatorsAndOperands. The issue is that tempbool is always false for all values.
import java.util.*;
public class stringCalculator
{
private String userInput = null;
String[] operatorsAndOperands = {"1","2","3","4","5","6","7","8","9","0","+","-","*","/"};
public stringCalculator(String newInput)
{
userInput = newInput;
}
public boolean checkInput()
{
boolean ifExists = true;
for(int i=0; i<userInput.length(); i++)
{
char currentChar = userInput.charAt(i);
boolean tempbool = Arrays.asList(operatorsAndOperands).contains(currentChar);
if (tempbool == false)
{
ifExists = false;
}
}
return ifExists;
}
}
This is because you have an array of string objects (which you later convert to a list of string objects), but you are checking a char for presence in that array.
Efficiency is also pretty poor here - converting a fixed array to a list on each iteration takes a lot of unnecessary CPU cycles.
A simple solution to this problem is to put all characters in a string, and then check each incoming character against that string:
if ("0123456789+-*/".indexOf(currentChar) >= 0) {
... // Good character
}
Another solution would be making a regex that allows only your characters to be specified, like this:
if (expr.replaceAll("[0-9+/*-]*", "").length() == 0) {
... // Expr contains only valid characters
}
Why don't you declare
String[] operatorsAndOperands = {"1","2","3","4","5","6","7","8","9","0","+","-","*","/"};
as a String, instead of an array of String. Then you can just use the contains method to check the characters against the valid operators.
Declare: char[] operatorsAndOperands; instead of: String[] operatorsAndOperands.
Or add this: String.valueOf(charToCompare) as the "contains" argument.
As has been pointed out, the issue is that you're checking for a char in a list of String objects, so you'll never find it.
You can make this check easier, though, by using a regular expression:
Pattern operatorsAndOperands = Pattern.compile("[0-9+\\-*/]");
Let's say I have this string: "abcd123fx".
Now, I want to make a method which checks (in order) if "a","b","c","d" etc is a number and if not, returns false. I don't know how to handle the n-th position of char and for each char, in order.
You can check if a character is a letter of number with teh Character class.
String text = ...
char ch = texct.charAt(nth);
if (Character.isLetter(ch)) {
// is a letter
} else if (Character.isDigit(ch)) {
// is a digit
}
Note: these method support characters in different blocks of the unicode. e.g. it will accept characters in Arabic or Korean.
Check the documentation. You can use charAt function.
if (Character.isLetter(yourString.charAt(index)))
// ... Letter
if (Character.isDigit(yourString.charAt(index)))
// ... Number
Check this page
Well there are a few ways you could do this. The simplest would probably be something along the lines of:
Character.isDigit(someString.charAt(x))
or a regex way would be someString.substring(x,x).matches("[0-9]")
To get the nth character of a string you should use charAt, the you should use the Charachter's isLetterOrDigit.
Usually, when you face these problems, you should search the javadoc looking for suitable methods.
Check out the Java tutorials on oracle.com for more information.
Specifically for this subject:
Characters, specifically the Character.isLetter(char ch) and Character.isDigit(char ch) methods
Strings and Manipulating Characters in a String, the simplest method is String.charAt(int index)
- As you have said that you are a newbie, i won't make this complicated using Regex, but will use inbuilt Java functionalities to answer this.
- First use subString() method to get the "abcd" part of the String, then use toCharArray() method to break the String into char elements, then use Character class's isDigit() method to know whether its a digit or not.
Eg:
public class T1 {
public static void main(String[] args){
String s = "abcd123fx";
String str = s.substring(0,4);
System.out.println(str);
char[] cArr = str.toCharArray();
for(char a :cArr){
if(Character.isDigit(a)){
System.out.println(a+" is a digit");
}else{
System.out.println(a+" is not a digit");
}
}
}
}
This might help you
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(.\\d+)?");
}
public static void main(String[] args){
System.out.println(isNumeric("abcd123fx"));
}
If you have a numeric string it will return true else false
public static void main(String[] args){
System.out.println(checkNumber("123a44"));
}
public static boolean checkNumber(String s){
for(int i = 0; i < s.length(); i++){
if(Character.isDigit(s.charAt(i))){
continue;
}
else{
return false;
}
}
return true;
}
You can also have a look into the ASCII table
Depending on this you can write a method:
private boolean isNumber(char a) {
int i = a;
if(i >= 48 && i <=57)
return true;
else
return false;
}
// now you can look by a String
private void checkString() {
String x = "abcd123fx ";
for(char counter : x.toCharArray())
System.out.println(isNumber(counter));
}