How to know what content a character variable contains? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Now if i need to print "alphabets" if the character contains alphabets , need to print "number" if the character contains number.
sorry if the questions seems silly, new to java.
Using charAt() function i've converted the string to characters, all i need is to find the content of the chararcter.

The code :
public class Example
{
public static void main(String[] args) {
String str ="abc123";
for(int i = 0; i < str.length(); i++) {
System.out.println(Character.isDigit(str.charAt(i)) ? "number" : "alphabet");
}
}
}
Output :
alphabet
alphabet
alphabet
number
number
number

String.contains might be you're looking for.
String str = "abc";
boolean isAlphabet = str.contains("a"); // is true
boolean isNumber = str.contains("1"); // is false

Pass your input string to below snippet, if its number then it will return true if its alphabets then it returns false
public static boolean isNumeric(String str) {
try {
double d = Double.parseDouble(str);
} catch (NumberFormatException | NullPointerException nfe) {
return false;
}
return true;
}
Another alternative is to use regular expression
public static boolean isNumeric(String strNum) {
return strNum.matches("-?\\d+(\\.\\d+)?");
}

Related

Parse String statement into a boolean expression [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 months ago.
Improve this question
I have a string statement String s = sb.contains("is");
I want to use this in an if condition like
if (s) {
//do something
}
How can I achieve this functionality?
Edit: Basically I get a boolean logic along with strings as an input. Ex: "Stack & over & (is | flow)". I have an array of sentences and I have to pick every sentence that follows this logic. I thought I would construct a string like "sb.contains(stack) && sb.contains(over) && (sb.contains(is) || sb.contains(flow))" and I thought I would run this boolean logic over all the sentences. Is there any other way of doing this?
The contains method returns a boolean value, so you can just simply set the type of variable 's' to a boolean.
public class Main
{
public static void main(String[] args) {
String sb = "crisis";
boolean s = sb.contains("is");
if(s){
System.out.println("S is true");
System.out.println(s);
}
}
}
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#contains(java.lang.CharSequence)

How to insert an intenger number in a String with method push() [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to put the value "restante" in my string array with method push. But an error display:
incompatible types: int cannot be converted to String
My JAVA file
import java.util.Scanner;
public class NumRestantes {
public static void main(String[] args) {
Pilha p1 = new Pilha(10);
Scanner ler = new Scanner(System.in);
int valor;
int restante;
valor = ler.nextInt();
restante = valor%16;
try {
if (restante == 0) {
p1.push(new Numeros(restante, 0));
} else {
while(restante >= 1) {
restante = restante%16;
p1.push(new Numeros(restante, 0));
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
I don't know much about methods, so I'd want some help to push values from variable "restante" to my array string.
You should convert the int to a String, then add it. One way to do this is to use Integer.toString(int). This uses the Integer class to convert an int into a string containing the int.

Is this the best way to solve "this" particular problem. "Program to reverse a string." [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
import java.util.Scanner;
public class ReverseString {
public static String reverseString(String str)
{
String str2 = "";
char[] ch = str.toCharArray();
int length = ch.length;
for(int i = length-1; i >= 0 ; i--)
{
str2 = str2 + ch[i];
}
return str2;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
System.out.println(reverseString(str));
}
}
I want to know that what should I keep in mind while solving this kind of logical problems & making similar programs?
First of all, don't use String concatenation with + sign inside a loop, use StringBuilder for that.
For simple problems like this one, you should try to solving it in few ways, try writing recursive function for example. Also familiarize yourself with memoization and dynamic programming.
To reverse a String you do not want really write a such a logic, you can simply assign your string to a StringBuilder class and call reverse method .
In general when you have such tasks look at API which we can use to ease our task instead of writing such logic.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
StringBuilder sb=new StringBuilder(str);
sb.reverse();
System.out.println(sb.toString());
}
simply this will work in your case
here's a recursive example:
private string ReverseString(string inputStr)
{
if (inputStr.IsNullOrEmpty(inputStr) || inputStr.Length == 1)
return inputStr;
else
return inputStr[inputStr.Length - 1] + Reverse(inputStr.Substring(0, str.Length - 1));
}

valid word counter out of bounds error [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
{
public static int WordCount (String cString)
{
String currentWord;
int index;
int spacePos;
int validWordCount=0;
boolean validWord;
char upClowC;
cString=cString.trim()+" ";
spacePos=cString.indexOf(" ");
validWord=true;
for(index=0;index<cString.length();index++)
{
currentWord=cString.substring(0,spacePos);
upClowC=Character.toUpperCase(currentWord.charAt(index));
if(upClowC<'A'||upClowC>'Z')
{
validWord=false;
}
}
if(validWord==true)
{
validWordCount++;
}
return validWordCount;
}
public static void main(String[] args)
{
String sentence;
System.out.println("enter a sentence:");
sentence=EasyIn.getString();
WordCount(sentence);
}
}
I'm trying to create a method which takes a sentence and picks out the valid words (i.e. no numbers or symbols), but I keep getting an out of bounds error.
I can't use an array.
Your problem is here:
currentWord = cString.substring(0, spacePos);
upClowC = Character.toUpperCase(currentWord.charAt(index));
currentWord gets shorter, but index is still running from 0 to the length of the string.
General notes:
Follow Java naming conventions and change the name of your method to begin with small letter
if(validWord) is enough when you want to compare something to true, otherwise it's like asking "is it true that the value is true" instead of simply "is the value true"
Next time post your stack trace to get better and sooner help
In your code, you are doing
spacePos = cString.indexOf(" ");
And then inside the loop:
currentWord = cString.substring(0,spacePos);
upClowC = Character.toUpperCase(currentWord.charAt(index));
Now, because of the loop, the index will take values from 0 to your string length minus 1. If your substring (currentWord) is smaller than your string - which probably is -, then currentWord.charAt(index) will try to index out of the bounds of the substring, which is why you get the error.

How to check if String has a Letter after a specific letter? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Example:
String letter = "abc+ab.c+abc.ab";
How to check if String letter contains . after last +?
About your modified question: to match . any time after + char try this:
Letter.matches(".*\\+.*\\..*");
Note: you it was necessary to escape + and . with \\ to match dot and plus literally, since those have a special meaning in regex.
Update: If you only want to match only if there is a dot after last + you could do this:
Letter.matches(".*\\+.*\\.[^+]*");
where the [^+] part means any char except +.
BTW: I would name your String letter instead of Letter because of naming conventions
Try this:
public boolean hasLetter(String string, char afterLetter, char letter) {
int index = string.indexOf(afterLetter);
if (index == -1 || index == string.length() -1) {
return false;
}
if (string.charAt(index+1) == letter) {
return true;
}
return false;
}
You could do something similar to:
for (int i = 0; i < letter.length() - 1; i++) {
if (letter.charAt(i) == '0' {
if (letter.charAt(i+1) == 'c' {
execute desired action here;
}
}
}
Try to use
Letter.matches(".*0c.*");

Categories

Resources