Creating a boolean method to check for consecutive numbers [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need help writing a method that checks if numbers and text are consecutive. It needs to return a boolean value of true if an input like inputted deFgh or 456789 and false for anything else not consecutive. I don't understand how to make the loop be true for cases like xyZaBcD and 890123 or cbazyx

try this code:
public static boolean isConsecutive(final String s) throws IllegalArgumentException
{
if (null == s) throw new IllegalArgumentException();
if (s.length() <= 1) return true;
final String lc = s.toLowerCase();
char c = lc.charAt(0);
for (int cc=1; cc<lc.length(); cc++)
if ( (c+1) != lc.charAt(cc) )
return false;
else
c++;
return true;
}
public static void main(String[] args)
{
try
{
System.out.println(isConsecutive("456789"));
System.out.println(isConsecutive("deFgh"));
System.out.println(isConsecutive("xyZaBcD"));
System.out.println(isConsecutive("890123"));
}
catch(final Exception e)
{
e.printStackTrace();
}
}
but I really suggest you do not show it to teacher, as it will have more questions, use it only as direction to your own code

This can be implemented at easiest way:
public class Check {
private static boolean checkConsecutive(String str) {
str = str.toLowerCase();
if (str.length() == 1) return true;
for (int i = 1; i < str.length(); i++) {
String first = str.substring(i, i+1);
String beforeFirst = str.substring(i-1, i);
if (beforeFirst.compareTo(first) > 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Check obj = new Check();
System.out.printf("abcdef is: %s%n", obj.checkConsecutive("abcdef"));
System.out.printf("12345 is: %s%n", obj.checkConsecutive("12345"));
System.out.printf("54321 is: %s%n", obj.checkConsecutive("54321"));
System.out.printf("fedcba is: %s%n", obj.checkConsecutive("fedcba"));
}
}
Output will be next:
abcdef is: true
12345 is: true
54321 is: false
fedcba is: false
This line str.substring(i, i+1) return exactly one letter, and we can use compareTo() from String class it compares consecutive by itself.

Just iterate over string and check sequence of char codes. If needed, use toLowerCase() method.

You can cast (int) to the characters in the loop. If the integer is between 48 and 57 inclusive, that means that the character is a digit.
See ASCII Table for the integers given by casting from char.

Related

Check if string contains number after specific word [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 months ago.
Improve this question
can someone help me with string validation? I tried to find the solution, but none was satisfied.
I have the uri e.g. /dog/cat/house,1/mouse/bird,1/rabbit.
I need to check if after word (with comma) bird, there is a number or not. In my case sometimes i receive uri with number: "bird,1" and sometimes with word: "bird,foo".
Thank you for any suggestions.
As #Federico klez Culloca and #The fourth bird suggested you could use a regular expression (\\bbird,(?:[1-9]|1[0-9]|20)\\b) but some security scans don't like regular expressions. In any case, one another (pure Java) solution would be:
Updated the answer after user added more conditions.
would look for range 1, 2 .. 20 (01, 02 would return false).
public static boolean isNumber() {
// you can parametrize these 2
String input = "/dog/cat/house,1/mouse/bird,10/rabbit.";
String strOfInterest = "/bird,";
boolean isStringEndingInLT20 = false;
int indxOfInterest = input.indexOf("/bird,") + strOfInterest.length();
char c1 = input.charAt(indxOfInterest);
char c2 = input.charAt(indxOfInterest + 1);
int i1 = Character.getNumericValue(input.charAt(indxOfInterest));
if (Character.isDigit(c1) && Character.isDigit(c2)) {
int num = Integer.parseInt("" + c1 + c2);
if ((i1 > 0) && (num >= 1) && (i1 <= 20)) isStringEndingInLT20 = true;
} else if (Character.isDigit(c1)) {
if ((i1 >= 1) && (i1 <= 9)) isStringEndingInLT20 = true;
}
return isStringEndingInLT20;
}
NOTE: I personally hate these verbose solutions and would prefer 1 line REGEX. Try to avoid it and use regex. The only times I avoid regex is when it becomes performance bottleneck and/or causes a security concern.
This is a practical algorithm, you can specify the keyword!
The premise is that the validity of the contains parameter is in line with your description.
keyword, (spaces are allowed)123/
public static void main(String[] args) throws IOException {
String contains = "/dog/cat/house,1/mouse/bird,a/rabbit";
FreeTest f = new FreeTest();
boolean has = f.hasNumber(contains, "bird");
System.out.println(has);
}
/**
* Check if string contains number after specific word
*
* #param contains string contains
* #param key the specific word (without comma)
* #return yes or not
*/
public boolean hasNumber(String contains, String key) {
int commaIndex = contains.indexOf(',', contains.indexOf(key));
int startIndex = commaIndex + 1;
boolean hasNumber = true;
while (true) {
char c = contains.charAt(startIndex++);
if (c == '/') break; // exit
if (c != ' ') {
hasNumber = Character.isDigit(c);
}
}
return hasNumber;
}

program to find if two characters in String in a row are digits does not work in java

I have the code below, which I want to take input from the keyboard and show me if the input contains 2 digits in a row. If so, I want to get false printed out in the console, otherwise true. It works fine, except when the first 2 characters of the input are digits. In that case, I still get true in the console. Can anyone understand why? Thanks in advance
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System. in );
System.out.println("Enter:");
String s = sc.nextLine();
if (checkDigit(s)) {
System.out.println("false");
} else {
System.out.println("true");
}
}
public static boolean checkDigit(String s) {
boolean b = true;
char[] c = s.toCharArray();
for (int i = 0; i < c.length - 1; i++) {
if (Character.isDigit(c[i]) && Character.isDigit(c[i + 1])) {
b = true;
} else {
b = false;
}
}
return b;
}
}
You continue to check the input string even when you already found the result. As noted by #Stultuske, you overwrite the value of the variable b, so your code will only return true, if the last two chars are digits.
You would need to return from the loop if there are two digits in a row:
public static boolean checkDigit(String s) {
char[] c = s.toCharArray();
for(int i=0; i < c.length-1; i++) {
if(Character.isDigit(c[i]) && Character.isDigit(c[i+1])) {
return true;
}
}
return false;
}
UPDATE: in fact there was an error in the snippet, as it was returning too early from the loop. Fixed now.
The problem is that you overwrite the value on each loop iteration, so you only get true if the last pair of characters match. But Krypt1 already said this.
An alternative implementation using streams (because all the kids want to use Streams these days):
return IntStream.range(0, str.length()-1)
.anyMatch(i -> Character.isDigit(str.charAt(i)) && Character.isDigit(str.charAt(i+1)));
use Character.isDigit(char) method in your if condition and return true; rather than store b=true as that may get overwritten in next iteration.
you can also use regular expression. String's matches(pattern) method for this purpose.
Try using the following regex
Pattern pattern = Pattern.compile("[0-9]{2}");
Matcher matcher = pattern.matcher("your input string");

Why won the if statement execute? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I wrote a simple program in Java which writes a word backwards. Trying to check if "hello" works. In if-statement I'm checking that string is equal to "olleh". Could anyone see why the if statement won't execute.
public class MyProgram {
public static void main(String[] args) {
String x = "hello";
System.out.println(back(x));
}
public static String back(String str) {
String y = " ";
String temp = " ";
for (int i = str.length() - 1; i >= 0; i--) {
char lets = str.charAt(i);
y += Character.toString(lets);
System.out.println(y);
if (y.equals("olleh")) {
System.out.println("nice");
}
}
return y;
}
}
Try this it will work
public class MyProgram
{
public static void main(String[] args)
{
String x = "hello";
System.out.println(back(x));
}
public static String back(String str )
{
String temp = "";
for (int i = str.length() - 1; i >= 0; i--) {
char lets = str.charAt(i);
temp = temp + lets;
}
if (temp.equals("olleh")) {
System.out.println("nice");
}
return temp;
}
}
If you will initialize y variable to empty string instead of space your if-statement will execute and print "nice". Also you do not need a temp string as you don't use it. You probably want to return you reverted string back (alternatively you can make your method void and remove the return statement).
public static String back(String str) {
String y = "";
for (int i = str.length() - 1; i >= 0; i--) {
char lets = str.charAt(i);
y += Character.toString(lets);
System.out.println(y);
if (y.equals("olleh")) {
System.out.println("nice");
}
}
return y;
}
By the way, it's better to use StringBuilder when you're concatenating strings in a loop.

Exception in program for search anagrams in 2 strings [duplicate]

This question already has answers here:
How to check if two words are anagrams
(37 answers)
Closed 7 years ago.
I have a problem with this little program in Java for which checks if 2 strings are anagrams or not.
I get a StringIndexOutOfBoundsException:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6
at java.lang.String.charAt(Unknown Source)
at AreAnagrams.areAnagrams(AreAnagrams.java:9)
at AreAnagrams.main(AreAnagrams.java:30)
This is my code:
public class AreAnagrams {
public static boolean areAnagrams(String a, String b) {
int j = 0;
int i = 0;
if (a.length() == b.length()) {
while (i < a.length()) {
if (a.charAt(i) == b.charAt(j)) {
j++;
i = 0;
} else {
i++;
if (j > a.length()) {
return false;
}
}
}
} else {
return false;
}
return false;
}
public static void main(String[] args) {
System.out.println(areAnagrams("momdad", "dadmom"));
}
}
java.lang.StringIndexOutOfBoundsException happens when you refer to a character index which exceeds the string length.
For example the string "dadmom" - when you call charAt(6), then it will throw this exception, because the character indices are in range from 0 to 5.
You can use the following code to identify anagrams:
public static boolean areAnagrams(String a, String b) {
char[] aChars = a.replaceAll("\\s", "").toCharArray();
char[] bChars = b.replaceAll("\\s", "").toCharArray();
Arrays.sort(aChars);
Arrays.sort(bChars);
System.out.println(aChars);
System.out.println(bChars);
return Arrays.equals(aChars, bChars);
}
public static void main(String[] args) {
System.out.println(areAnagrams("momdad", "dadmom"));
}
I feel that you have a programming logic error here. For anagrams the criteria should be that the starting from left to right for 1st string the characters should be equal for the 2nd string starting right to left.
I did not find any such thing in your code. I feel you should try the following inside your if block if ( a.length() == b.length()):
int length = a.length();
for(int i = 0; i < length; i++){
if(a.charAt(i) != b.charAt(length-i-1)){
return false;
}
}
return true;
You should also remove the declaration of i and j variables in your code.
Correction
I really got confused with anagram and palindrome. The above answer is correct for palindrome. I am adding to my answer to work for anagram.
I would suggest that you check the strings recursively by changing the method areAnagrams as illustrated below:
public static boolean areAnagrams(String a, String b) {
//If the length of strings is unequal then return false.
if(a.length() != b.length()){
return false;
}
//Else if the length of strings equals 1 return the equality of the two strings
if(a.length() == 1){
return a.equals(b);
}
//Else replace the first occurrence of the first character
//of variable `a` with blank string in string variable b.
//Here if the character is not present in string b then the
//variable b remains unchanged and the length of b would be
//greater than that of variable `a` in the next recursion.
b = b.replaceFirst(a.substring(0, 1), "");
//remove the first character in string `a`
a = a.substring(1, a.length());
//make the recursive call
return areAnagrams(a, b);
}

How do I check if a string array is full [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to check if there is a value assigned to every part of my string array e.g. If my string array is String[8], I need to check if there is 8 different values in the string array.
You need to iterate through each element of the array and check if it is null, if none is null then the list is full.
boolean isFull = true;
for(String s : yourarray) {
if(s == null) {
isFull = false;
break;
}
}
If each value needs to be different then you have to have nested loop. (A bit unclear in the question)
boolean isFull = true;
for(String s : yourarray) {
for(String t : yourarray) {
if(s == null || s.equals(t)) {
isFull = false;
break;
}
}
}
You want to know if the characters that make up the string are all different. For this, I recommend the following methods: String#length, String.charAt, String.indexOf and a loop over all characters, i.e. from 0 to n-1, where n is the string length.
You can do it like this: Here str_array (just initialized for example purpose) is the string array, and empty_indexes is the list of indexes of String array that are empty.
String str = "This is the example string";
String[] str_array = str.split(" ");
ArrayList<Integer> empty_indexes = new ArrayList<Integer>();
for (int i = 0; i < str_array.length; i++) {
if (str_array[i] != null) {
if (str_array.equals("")) {
empty_indexes.add(i);
}
} else {
empty_indexes.add(i);
}
}
Use a for loop:
boolean isFull = true;
for(int i = 0;i<yourarray.length;i++)
{
if(yourarray[i] != null && !yourarray[i].isEmpty())
{
isFull = false;
break;
}
}

Categories