JAVA - String contains char letter. Possible to check? [duplicate] - java

This question already has answers here:
How can I check if a single character appears in a string?
(16 answers)
Closed 7 years ago.
I am trying to make a method called Baller(String str, char chr) which should return a boolean if the word contains the character. In the main method I have:
public static void main(String[] args) {
Balling ball= new Balling ();
System.out.println( ball.contains("Baller", 'a'));
System.out.println( ball.contains("Baller", 'A'));
}
What I did was this but it did not work:
public boolean contains(String str, char chr ) {
if(str.length() == chr) {
return true;
}
else {
return false;
}
}
What could be the problem?
ANSWER
public boolean contains(String str, char chr ) {
for(int i = 0; i < str.length(); i++)
if(str.charAt(i) == chr)
return true;
return false;
}
}

The problem is that string length is compared to character value:
str.length() == chr
What you should use if the indexOf String method
public boolean contains(String str, char chr) {
return str.indexOf(chr) != -1;
}

You are testing if the length of the String is equal to some char. This will perhaps work if your String is of length zero and your character == 0 or perhaps if your String is of length one and you compare it to the character with the numeric value of 1. In other words: Almost never.
You never return false. So all your string contain all your characters.
String has an indexOf( character ) method. use that. See documentation.

Related

The user must enter a string that contains at least one lowercase “a”

The user must do the question above or the question keeps repeating so I need a while loop. I need to do this using a subroutine too. My code below isn't working.
public static boolean isAlpha(String name) {
char[] chars = name.toCharArray();
for (char c : chars) {
if (!Character.isLetter(c)) {
return false;
}
else {
for (int i = 0; i < name.length(); i++) {
if (name.charAt(i) >= 'a') {
return false;
}
else {
return false;
}
}
}
}
return false;
}
This is the second part:
System. out.print ("Please enter a string that contains at least one lowercase a. ");
String name = input.next ();
if (isAlpha(name)) {
System.out.println("That is a valid string onto stage 2.");
}
else {
System.out.println("That is an invalid string. Try again.");
}
You're passing a String to the isAlpha method, which iterates over the String and checks each letter to be 'a' or not. You're returning false for every char that isn't 'a', and returning false if you iterate through the entire String.
An easier way to handle this would be to return true upon finding the first 'a', or returning false after iterating over the entire String. It will make scaling easier as well if you reduce the number of return statements in a single method.
Here are three different ways to check whether a string contains at least one lowercase a. The first way uses a for loop as you have tried to do in the code in your question.
The second way uses regular expressions and the last way uses streams.
The code also contains a main method which contains a while loop as requested in your question.
do the question above or the question keeps repeating
import java.util.Scanner;
public class Solution {
public static boolean isAlpha(String name) {
/* Using a loop. */
char[] chars = name.toCharArray();
for (char ch : chars) {
if (ch == 'a') {
return true;
}
}
return false;
/* Using regular expression. */
// return name.matches("^.*a.*$");
/* Using stream API. */
// return name.chars()
// .filter(c -> c == 'a')
// .findFirst()
// .isPresent();
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter a string that contains at least one lowercase 'a': ");
String str = input.nextLine();
while (!isAlpha(str)) {
System.out.println("That is an invalid string. Try again.");
str = input.nextLine();
}
System.out.println("That is a valid string. On to stage 2.");
}
}
Here is a sample run:
Please enter a string that contains at least one lowercase 'a': 1 is the lonliest number.
That is an invalid string. Try again.
2 can be as bad as 1
That is a valid string. On to stage 2.
A couple of mistakes were made. Firstly, your method only returns false, there is no way in which it could be true. Secondly, your code here loops through the entire array for every single character.
public static Boolean isAlpha(String name) {
char[] chars = name.toCharArray();
for (char c : chars) {
if (!Character.isLetter(c)) {
return false;
}
else {
for (int i = 0; i < name.length(); i++) {
if (name.charAt(i) >= 'a') {
return false;
}
else {
return false;
}
}
}
}
return false;
}
Try this instead.
public static Boolean isAlpha(String name) {
char[] chars = name.toCharArray();
for(char c : chars) {
if(c=='a') {
return true;
}
}
return false;
}

Check if a given word is a palindrome [duplicate]

This question already has answers here:
Check string for palindrome
(42 answers)
Closed 1 year ago.
I am trying to write a method to check if a given word is a palindrome, but as of now it does not work. I suspect the error lies within the if-statement and the fact that you don't compare objects such as strings with == but instead with equals, is that right? However Java does not allow me to write: if (firstHalf.charAt(i).equals(secondHalf.charAt(j))), so what can I do to make it work? Are there other errors in the code?
public static boolean isPalindrome(String string) {
String firstHalf = string.substring(0, string.length() / 2);
String secondHalf = string.substring(string.length() / 2, string.length());
for (int i = 0; i <= firstHalf.length(); i++) {
for (int j = secondHalf.length(); j <= 0; j--) {
if (firstHalf.charAt(i) == secondHalf.charAt(j)) {
return true;
}
}
}
return false;
}
Why not do it this way?
public static boolean isPalindrome(String string){
StringBuilder sb = new StringBuilder(string);
sb.reverse();
return sb.toString().equals(string);
}
Your character test was backwards. All of the comparisons have to be equal for the String to be a palindrome.
Also, splitting the String is unnecessary. You can logically split the String with two indices.
Try this code.
public static boolean isPalindrome(String string) {
int frontIndex = 0;
int backIndex = string.length() - 1;
while (frontIndex < backIndex) {
if (string.charAt(frontIndex++) != string.charAt(backIndex--)) {
return false;
}
}
return true;
}
you can make each character a String like so
String s1 = "" + c1;
and then compare them with .equals(s1, s2)
Or you can use the Character class which is a wrapper around primitive character.
That would also enable you to use c1.equals(c2)

Why my code for prefixAgain is not working?

Given a string, consider the prefix string made of the first N chars of the string. Does that prefix string appear somewhere else in the string? Assume that the string is not empty and that N is in the range 1..str.length().
public boolean prefixAgain(String str, int n) {
String res = "";
String res1 = "";
String s = str.substring(0,n);
for ( int i = 0 ; i < n ; i++ ) {
res += str.charAt(i) ;
if (s.equalsIgnoreCase(res)); {
return true;
} else {
return false;
}
}
}
There are many problems with your solution:
Why do you need to loop only till n in the prefixAgain method? You probably need to go till str.length()
Your res variable will again be a prefix of the string and will be of no use.
Why are you having ; after the if?
Using += on Strings in a loop can be very expensive. You should always consider using StringBuilder and it's append method.
The following method does what you want:
public boolean prefixAgain(String str, int n) {
if (str.length() == 1) return false;
String s = str.substring(0, n);
return str.substring(1).contains(s);
}
The main idea is to just search the required prefix in the substring starting from 2nd character (the character at index 1).
Keep it simple. :)

How can I validate if a string is a string and not an integer in java?

I enter a list into a JTextArea, and when I push a button, it runs the method below. I need to check to see if str[i+1], str[i+2] is a String and not an int.
public void readData(JTextArea input) {
String[] str = input.getText().split("\n");
for(int i =1; i< str.length; i= i+3) {
try {
Integer.parseInt(str[i]);
simulator.add(new Process(Integer.parseInt(str[i]), str[i+1],str[i+2]));
} catch(NumberFormatException e) {
System.out.println("Please enter an integer only " +
str[i] + " is not an integer");
}
}
}
You could have a function that tries to parse the string into an Integer or a Double and return true if it succeeded, or return false is an exception was thrown during parsing. Parsing into a Double should be enough since all integer values are decimal values without the .0
public static boolean isNumber(String s) {
try {
Double.parseDouble(s);
/* Use Integer.parseInt(s) instead, if
you want to check if the String s
is an Integer */
} catch(NumberFormatException e) { // string is not a number
return false;
}
return true;
}
Then you can say if(!isNumber(str)) to check if the String str is not a number.
Alternatively, you could make the isNumber() be a isNotNumber() by swapping the return false and return true statements.
If you don't want to use exceptions, a different approach would be the following. Since we know a valid number can only contain digits and at most 1 dot for decimal point, we can iterate through the string and check for each character:
if it is not a digit and not a dot, return false
if it is a dot but a dot was already found, return false
otherwise it is valid number character and we do nothing
Here is a sample function:
public static boolean isNumber(String s) {
int dotCount = 0;
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) != '.' && !Character.isDigit(s.charAt(i))) {
return false;
} else if(s.charAt(i) == '.') {
if(dotCount == 1) {
return false;
}
dotCount = 1;
}
}
return true;
}
EDIT: based on #MadProgrammer's suggestions:
A more general approach that will accept values separated with commas such as 1,35 or any amount of spaces within the number string like with 123 456 . 333.
Approach:
Iterate through the string and check for each character:
if it is not a digit, dot, comma, or a space, return false
if it is a dot or a comma but one of them was already found, return false
otherwise it is valid number character and we do nothing
So the code would look something like:
public static boolean isNumber(String s) {
int separatorCount = 0; // count dots and commas
char currChar;
s.trim(); // remove trailing and leading whitespace
for (int i = 0; i < s.length(); i++) {
currChar = s.charAt(i);
if (currChar != '.' && currChar != ',' && currChar != ' '
&& !Character.isDigit(currChar)) {
return false;
} else if (currChar == '.' || currChar == ',') {
if (separatorCount == 1) {
return false;
}
separatorCount = 1;
}
}
return true;
}
Another solution could use the NumberFormat's parse() method. However, this method only checks the beginning of the string (for example, for 12.3.3 it will return 12.3) so we have to return false if the returned string doesn't equal the input string as well as if the ParseException is thrown.
public static boolean isNumber(String s) {
try {
String newVal = NumberFormat.getInstance().parse(s).toString();
if (!newVal.equals(s)) {
return false;
}
} catch (ParseException e) {
return false;
}
return true;
}
NOTE: All of the methods should probably have a check if(s == null) { return false; } for the input String s to prevent a NullPointerException
Your rules are sparse, you don't specify if things like , or . are considered part of a number or not (1, 000.01 for example), also, you don't define if the value is allowed to contain numerical values or not, but...
You Could...
Try parsing each value (or the concatenation of the two) using Integer.parseInt, if they pass, then they are not String (or text) based values...
You Could...
Verify each character within the String to see if it contains more than just digits, using something like Character#isLetter
You Could...
Use a regular expression to determine if the value contain other content other than numbers.
You can try this simple regular expression to check if a string represents a number or not:-
String str = "12345";
System.out.println(str.matches("\\d+"));
Regex seems the best option. Here's a regex that will parse float and integers and currency values with comma as well.
String numberRex = "^([\\d]*\\.*\\d*|[\\d,]*\\.*\\d*)$";
"1234,455.43".matches(numberRex); // true
This is a simple test that asserts there is at least one non numeric char:
if (str.matches(".*[^\\d.].*"))
the regex translates as "somewhere in the input there's a character that's not a digit or a dot"

uppercase 1st character the string [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
String replace method is not working
public static String capitalise(String str)
{
if (str != null || !"".equals(str))
{
char chr=str.charAt(0);
String check= Character.toString(chr);
String check1= check.toUpperCase();
char chr1=check1.charAt(0);
str=str.replace(chr, chr1);
return str;
}
else
{
System.out.println("Not a valid String");
}
return str;
}
i want to uppercase only the first character but it capitalize the first character where it comes for eg before upeercase string = shashank after it becomes ShaShank...what should i do for it .
str.replace(chr, chr1); replaces all occurences of the char in that string. It will change all s to S in your case.
User substring to concatenate the upper-cased first char with the rest of the string.
Here's a simple solution for the additional question in your comment. It will uppercase each character after a single(!) space. You may want to enhance it to allow mulitple spaces or multiple whitechars in general.
public static void main(final String[] args) {
String s = "some words";
StringBuilder result = new StringBuilder();
boolean capitalizeNextLetter = true;
for (char c : s.toCharArray()) {
if (capitalizeNextLetter) {
result.append(Character.toUpperCase(c));
capitalizeNextLetter = false;
} else {
if (c == ' ') {
capitalizeNextLetter = true;
}
result.append(c);
}
}
System.out.println(result.toString());
}
How about something like:
public static String capitalize(String str) {
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
Why not simply do following
str= Character.toUpperCase(str.charAt(0)) + str.substring(1)
In your code replace method will replace all 's' with 'S'.
Because char contains 's';
Try this answer
public static String capitalise(String str)
{
String test = str.substring(0,1);
test=test.toUpperCase();
System.out.println(test);
String new1= test+str.substring(1,str.length());
return new1;
}
try this
public static String capitalise(String str)
{
if (str != null || !"".equals(str))
{
char chr = str.charAt(0);
String capsString = Character.toString(chr).toUpperCase() + str.substring(1);
return capsString;
}
else
{
System.out.println("Not a valid String");
}
return str;
}
Use ReplaceFirst method.
str=str.replaceFirst(check, chreck1);
replaceFirst
Also, you should change your if condition to following:
if (str != null && !"".equals(str))
This way empty string won't be processed.
Try this.just change one line.
public static String capitalise(String str)
{
if (str != null || !"".equals(str))
{
char chr=str.charAt(0);
String check= Character.toString(chr);
String check1= check.toUpperCase();
str=check1+str.substring(1);
return str;
}
else
{
System.out.println("Not a valid String");
}
return str;
}

Categories

Resources