How to define 00-90 when I have charAt each of it - java

What I need to do is write a program that makes the first character (which is charAt(0) )and the second character (which is charAt(1) ) to become a value that not exceeding 90 which is (0 ~ 90) , but I also have to define them as an independent digit , because my program will make it to invalid if it is other than a digit.
So for an example it will become invalid if I type in 91
and it will valid if I type in number between 0~90
but I have no idea how to do this...
if(Character.isDigit(loop1.charAt(0))&&
Character.isDigit(loop1.charAt(1)))
I have tried this ,but not working
if(Character.isDigit(loop1.charAt(0)) &&
Character.isDigit(loop1.charAt(1)) &&
((loop1 >= 0)&&(loop1 <= 90)))
also this one but this is not working( I have no idea what I'm doing)
if(Character.isDigit(loop1.charAt(0)) &&
(((int)loop1.charAt(0)) >= 0) && <=9
Character.isDigit(loop1.charAt(1)) &&
((int)loop1.charAt(1)) <= 9)
Please help me... thanks a million !

Assuming I understand your question, parse loop1 and test the values using a simple if check, like
int t = Integer.parseInt(loop1);
if (t < 0 || t > 90) {
System.out.println("Value outside accepted range.");
} else {
System.out.println("Value valid.");
}

If I am getting this right you want to convert the first two characters of a string into a number and check is that number bigger than 90. Also you want the digits to be stored in different variables(?). If so this code should do it:
int digit1 = loop1.charAt(0) - '0';
int digit2 = loop1.charAt(1) - '0';
int number = digit1 * 10 + digit2;
if ( number <= 90 && number >= 0 )
System.out.println("Input is good");
else
System.out.println("Input is bad");

Related

Formatting with Array[i] Logic

I'm trying to build a program that prints 75 random caps and lowercase letters, 25 per line. I think I have all the logic worked out, but whenever I run it the formatting is all off and rather than printing 25 characters per line, it prints a random number. Here's my code so far:
char allLetters[] = new char[3700];
for(int i = 1; i <= 75; i++) { //Begin for loop
int max = 122;
int min = 65;
allLetters[i] = (char)(Math.random() * (max - min) + min);
if(i % 25 != 0){
if (allLetters[i] <= 90) {
System.out.printf("%s,",allLetters[i]);
}
if (allLetters[i] >= 97) {
System.out.printf("%s,",allLetters[i]);
}
} //Close if
else {
if (allLetters[i] <= 90) {
System.out.printf("%s\n",allLetters[i]);
}
if (allLetters[i] >= 97) {
System.out.printf("%s\n",allLetters[i]);
}
}
} //End for
Currently, the output is something like:
U,i,y,e,v,T,G,p,P,a,U,G,e,B,w,U,o,F,G,w,j,m,R
O,X,w,w,u,p,t,g,X,J,R,c,w,I,d,H,R,m,y,b,o
C,p,M,F,X,U,v,O,a,Y,F,E,x,s,x,k,C,b,D,R,r,H
I've tried using different variables besides i, playing around with numbers and such but I can't seem to find the exact flaw in the logic that throws the formatting off. Any help would be greatly appreciated!
The problem with your logic is that you are counting each chosen character even when you do not print it. The ASCII characters falling between 90 and 97, exclusive, are not characters, and you rightfully skip printing them. Yet the loop is still counting those iterations as if a valid letter has been printed. This is resulting in an incorrect count in the output.
The workaround used in the code snippet below is to keep picking characters in a loop until we actually get a lowercase or uppercase letter. Only then do we continue with your previous logic.
char allLetters[] = new char[3700];
int max = 122;
int min = 65;
for (int i = 1; i <= 75; i++) {
char next;
do {
next = (char)(Math.random() * (max - min) + min);
} while (next > 90 && next < 97);
allLetters[i] = next;
if (i % 25 != 0) {
System.out.printf("%s,", next);
}
else {
System.out.printf("%s\n", next);
}
}
Demo
Your two conditions that you put on your random characters, namely allLetters[i] <= 90 and allLetters[i] >= 97, do not cover the entire interval of possible characters, which in your program is 65 to 122, inclusive. When a character between 91 and 96 gets generated, your program does not print anything. The probability of getting one of these six random characters is roughly 10%, so you get 21..23 characters printed.
If you really want to skip these six characters, fix the problem by using a while loop instead of a for loop, and increment the counter of printed characters only when you print something:
int printed = 0;
while (printed != 75) {
char ch = (char)(Math.random() * (max - min) + min);
if (ch >= 91 && ch <= 96) continue;
printed++;
System.out.print(ch);
if (printed % 25 == 0 {
System.out.println();
} else {
System.out.print(',');
}
}
I was looking at your problem, and there's a "clever" solution using Java 8+ IntStream and lambdas. Generate 75 random int(s) between 0 and 26, map each value to a one-character String offset from either 'a' or 'A' by using nextBoolean() from Random. Collect that to a single seventy-five character String. Then print the three twenty-five character substring(s) we're interested in. Like,
Random rand = new Random();
String s = IntStream.generate(() -> rand.nextInt(26)).limit(75)
.mapToObj(i -> Character.toString(
rand.nextBoolean() ? (char) (i + 'a') : (char) (i + 'A')))
.collect(Collectors.joining());
System.out.println(s.substring(0, 25));
System.out.println(s.substring(25, 50));
System.out.println(s.substring(50));

Initializing an int variable before if statement

When compiling i get an Error stating that my variable has not been initialized.
Code :
int number;
if (dotted==true)
{
if (input >= 1 && input <= 21)
{
number = 1;
System.out.print("True");
}
if (input >= 22 && input <= 40)
{
number = 2;
System.out.print("False");
}
if (input >= 41 && input <= 63)
{
number = 3;
System.out.print("False");
}
if (input >= 64 && input <= 82)
{
number = 4;
System.out.print("True");
}
}
else
{
if (input >= 2 && input <= 22)
{
number = 1;
System.out.print("True");
}
if (input >= 23 && input <= 41)
{
number = 2;
System.out.print("False");
}
if (input >= 42 && input <= 64)
{
number = 3;
System.out.print("False");
}
if (input >= 65 && input <= 83)
{
number = 4;
System.out.print("True");
}
}
System.out.print(number); // number is not initialized?
Why is number not initialized?
I put int number = 0;
But then when i print, no matter the value of input it stays at 0?
Love how people downvote this. A student new to java with a question gets downvoted. Nice site
You need to put int number = 0 because you can't be sure whether the IF statement is executed or not. That's a precaution for your code.
Also, if you think about it, if it keeps being 0, it means you're actually not entering into the IF statement.
Try to put that and check if the dotted variable is actually TRUE or not.
Check also your variable input, because it is the one that changes your number variable.
Why is number not initialized?
Simply, because if none of the if statements are executed then the number variable will never get initialised. Hence the variable will not have a value and that's why you get the following error:
When compiling i get an Error stating that my variable has not been
initialized.
Also, remember local variables must be initialized before the method exits.
with that in mind, you must at least give the variable below a default value:
int number = 0;
I put int number = 0; But then when I print, no matter the value of
input it stays at 0?
if that's the case then it means you're never entering into the if statement. So, you might have to consider your if statement expressions again.

How to check values in a string?

So i have a string in military time format : "1532" corresponding to 3:32pm.
I'm trying to write a method to check if each digit in time string is an appropriate digit. So the first element cannot be greater than 2 or equal to 0, and so forth. Currently, my code doesn't run past the second log statement and I'm hoping you guys could help!
cheers!
String mOpen = "1532";
Log.d("hoursTesting","pass1, length is > 2");
if(mOpen.getText().length() == 4)
{
Log.d("hoursTesting","pass2, length is == 4");
char[] tempString = mOpen.getText().toString().toCharArray();
if(tempString[0] != 0 && tempString[0] < 3)
{
Log.d("hoursTesting","pass3, first index is != 0 and < 3");
if(tempString[0] == 1)
{
Log.d("hoursTesting","pass4, first index is 1");
if(tempString[2] <= 5)
{
Log.d("hoursTesting","pass5, third index is <= 5, success!");
}
}
else //tempString[0] is equal to 2
{
Log.d("hoursTesting","pass4, first index is 2");
if(tempString[1] < 4)
{
Log.d("hoursTesting","pass5, second index is <3");
if(tempString[2] <= 5)
{
Log.d("hoursTesting","pass6, third index is <= 5, success!");
}
}
}
}
}
tempString contains characters, not numbers.
i.e. '0' not 0 etc.
Easiest fix is to compare characters e.g. tempString[0] == '1' Alternatively, you can do something like int digit1 = tempString[0] - '0'; - but that kind of assumes you already know you just have digits in the string.
Note that cos of those clever ASCII guys and their tricky character set '0' < '1' < '2' etc, so you can still say if (str[0] < '2') etc. You just need to be a bit careful that you are only dealing with digits.
Personally I'd convert the first 2 chars to a number and the second 2 chars to a number and then just check 0 <= number1 <= 23 and 0 <= number2 <= 59.
You are comparing char with int here:
if(tempString[0] != 0 && tempString[0] < 3)
It should work like this:
if(tempString[0] != '0' && tempString[0] < '3')
I would substring the hours and minutes components and then check to see if each one be in range:
public boolean isTimeValid(String mOpen) {
int hours = Integer.parseInt(mOpen.substring(0, 2));
int minutes = Integer.parseInt(mOpen.substring(2));
if ((hours >= 0 && hours <= 24) && (minutes >= 0 && minutes <= 59)) {
return true;
}
else {
return false;
}
}

How do I detect errors in UPC codes?

I know that UPC codes have a check digit and how to use this check digit to see if the code is valid.
If the code is not valid, my program needs to tell me where the error is. I know it can be done, but how? I need to detect single replacement errors (e.g., typing a 5 in the place of a 2) and transposition errors (e.g., typing 12 instead of 21).
Seems simple but I can't figure it out.
The following code will detect errors in a UPC-A code (12-digit) when considered a String (recommended way).
String upc = "074985003004"; // UPC as a string
int sum = 0;
for(int i = 0; i < a.length(); i++) {
sum += (i%2==0) ? (3*(upc.charAt(i)-48)) : (upc.charAt(i)-48);
}
if (sum % 10 == 0) {
System.out.println("true");
} else {
System.out.println("false");
}
Alternatively, a long can be used in the following code: (Note: the leading zero's must be removed.)
long upc = 74985003004L; // omit leading zeros;
int sum =0;
for(int i=0; i < 12; i++) {
sum += (i%2 == 0) ? (upc % 10) : (sum += 3*(upc % 10));
upc /= 10;
}
if (sum % 10 == 0) {
System.out.println("true");
} else System.out.println("false");
It is usually best to validate the UPC code before testing. i.e. check to make sure it contains the correct number of digits and only the digits 0-9. As mentioned in the link: https://en.wikipedia.org/wiki/Universal_Product_Code, UPC-A detects 100% of single digit errors and 90% of 2-digit transposition errors.
*UPC does not support error correction. However, if you know which digit is incorrect, you can just try all 10 possible values for that digit until no errors are detected (a valid UPC code).

How to check string length range in a short form in java?

How to check string range in a short from in java?
if( !(str2.length() >= 3) && !(str2.length() <= 15)){
System.out.println("Minumum length required");
}
rather than using like above. is there any short??
(!(str2.length() >= 3) && !(str2.length() <= 15))
is the same as
( (str2.length() < 3) && (str2.length() > 15))
is the same as
(str2.length() < 3) && (15 < str2.length())
which is always false.
There is no number that is both less than 3 and greater than 15.
So these are pointless comparisons.
If you want to know that length is between 3 and 15, inclusive, use
if (3 <= str2.length() && str2.length() <= 15)
It's easy on the eyes and reminds people of familiar math expressions like 3 ≤ x ≤ 15.
But if that's what you meant your message needs fixing as well. If you meant what you said then the shortest version of this code is a blank line. It'll do the same thing.
This is not shorter but at least correct
if (!(str2.length() >= 3 && str2.length() <= 15)){
System.out.println("text length is not within range");
}
You can use a local variable.
int len = str2.length();
if (len < 3 || len > 15)
throw new IllegalArgumentException("String length" + len + " out of range.");
You could use a single comparison but this is not shorter.
if (len + Integer.MIN_VALUE - 3 > Integer.MIN_VALUE - 3 + 15)
This works as values below 3 will underflow and appear to be very large.

Categories

Resources