I want to get the last character of a string and if it's a even number to do different actions based on that. Simple example:
Server_3
First I want to get the last value 3
String str = "Server_3";
str.charAt(str.length()-1)
The problem is next how to construct the logic to have different cased based on that is this a even number or not. Can you help me to complete this?
The correct code is:
if (Integer.valueOf(str.charAt(str.length()-1) + "") % 2 == 0) {
// Even logic
} else {
// Odd logic
}
Or.... to reduce method calls and the get rid of the funky string concatenation:
if ((str.charAt(str.length()-1) - '0') % 2) {
// Even logic
} else {
// Odd logic
}
Convert to integer and check for even
if(Integer.valueOf(str.charAt((str.length()-1) + "") % 2 ==0) {
// do your work here
}
Use the modulo (%) operator: i % 2 is 0 if i is even, and 1 if i is odd.
Related
We are learning compareTo() method and equals() method, but I am unsure how to properly print the words in alphabetical order.
I have 2 Strings:
String firstString;
String secondString;
that are assigned values (elsewhere).
I have tried:
System.out.println(firstString.CompareToIgnoreCase(secondString));
but am only getting integers in my output as opposed to full words.
As this is homework, I'll only address your stumbling block.
As per the documentation, compareToIgnoreCase() (and more generally, compareTo()) returns an integer, either negative, zero or positive, depending on whether the first parameter's order is less than, the same or greater respectively than the second parameter.
You'll need to check the result of compareToIgnoreCase(), then print based on that, for example:
if (firstString.compareToIgnoreCase(secondString) > 0) {
// do something
} else {
// do something else
}
For those taking the same class, this solves the requirements for the question:
if (firstString.compareTo(secondString) < 0) {
System.out.println(firstString + " " + secondString);
}
else {
System.out.println(secondString + " " + firstString);
}
The task is to shift a number within a string to the beginning of the string with a recursion. So if I feed "ba3nana" to the code it should return "3banana". Did some recursive tasks already but this one I am stuck on.
I tried I guess already 50 different combinations but so far my code only returns "banana3" so I go the opposite way with my number. Does anyone see the mistake in my code?
The call of the method looks like this:
System.out.println(shiftDigitLeft("ba3nana"));
This is the code so far:
private static String shiftDigitLeft(String text) {
if (text.isEmpty()) {
return text;
} else {
if (text.charAt(0) >= '\u0030' && text.charAt(0) <= '\u0039') {
return shiftDigitLeft(text.substring(1)) + text.charAt(0);
} else {
return text.charAt(0) + shiftDigitLeft(text.substring(1));
}
}
}
Thanks in advance!
The pseudocode for what you've written would look like this
String shiftDigitLeft(String text) {
if the text is empty
return empty
else
if the first character is a digit
return shiftDigitLeft(the rest of the string) + the digit
else
return the letter + shiftDigitLeft(the rest of the string)
}
It should be obvious from this that digits never get moved to the left, only to the right.
You should probably invert your approach so that you look whether the last character is a digit, and if it is then move it to the beginning.
So I'm making a fraction calculator and I have one last part to figure out. For calculations that involve multiplying by 0, the final answer must always be 0. Due to my code I always end up with something like 0/1 or 0/5, so it always has a denominator. I want to return the answer without that denominator, but I'm not sure how to write my if statement. Here's my attempt at trying to print the 0 without the denominator.
if (reducedAnswer.charAt(0) == 0) {
return reducedAnswer.substring(0, 1);
}
I'm not quite sure how to modify that if statement to check if the first character of the answer is 0 so I can remove the unwanted parts. Any ideas?
You need a char literal, change
if (reducedAnswer.charAt(0) == 0) {
to
if (reducedAnswer.charAt(0) == '0') {
or use String.startsWith like
if (reducedAnswer.startsWith("0")) {
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
hello i worked on a recursive method to convert from int to string fully manual way, and i wanna know if that recursive method is efficient or not, and if you could help me to improve the code. Im new to algorithms so don't blame me if something looks like ugly... I've search on the internet but never looked for something like that :
public class IntToString {
public static String intToString(int number) {
return intToString(number, "", false);
}
private static String intToString(int number, String answer,
boolean isNegative) {
if (number < 0 && isNegative == false) {
isNegative = true;
number = -number;
}
if (number == 0)
if (isNegative)
return "-" + answer;
else
return answer;
System.out.println(number);
return intToString(number / 10, answer = number % 10 + answer,
isNegative);
}
// test
public static void main(String[] args) {
String ans = intToString(-324234);
System.out.println(ans);
}
}
No, it's not very efficient. Though it could be worse. At least it's still O(N) where N is the number of decimal digits in the given number.
invertInt is not really needed. You are using it because you are appending it to the answer that you pass down the the recursions, which will cause that number to be inverted. But there are at least two other ways to do it so that it won't be inverted.
If you note, there is only a very slight difference between the the way you handle negative numbers and positive numbers. Perhaps you can just run the same procedure for both of them, if you remember that processing a negative number is the same as processing its positive opposite, and tacking the - when you're done.
There is no reason for all the flags for negative and inversion. Both of them are only done at the top level. So you can do those things at the intToString(int number) function and not in your recursive function, and save yourself a lot of condition checking, and of course, the replaceAll() call.
There is no need to pass down the answer. You can base your return value on what the recursive call returned. Remember that for numbers like 1,2,3, you'll get the string '1','2','3'. So if you have 23, and you pass down 2, you can use the 2 you got to build your answer.
Your algorithm does not return the correct answer for 0. It's the correct answer when you think in recursive terms, but not when you call it with 0 from main. There are at least two ways to handle that.
And a bit of style advice:
Always indent your code properly.
You don't need to compare boolean values to true or false. If you have a boolean variable x, you can use if (x) or if (!x) rather than if (x==true) and if (x==false). Name your boolean variables in a way that will make this more intuitive, like isNegative or needsInversion. An if (isNegative) makes sense when you read it.
More detailed information in case you could not find the solution:
How do we avoid the inversion? There are two ways, basically. If you insist on passing down the answer, then instead of:
answer += num % 10;
Use:
answer = ( num % 10 ) + answer;
That is - append it to the left of the answer, not its right.
The approach I prefer is using the answer from the lower level. Suppose you have the number 123. So you pass down 12, and you get back the answer "12". Then you can use
return answer + ( num % 10 );
which will give you "123". This time, it's appended to the right.
Finally, here is the complete solution:
public static String intToString( int n ) {
if ( n == 0 ) {
return "0";
} else if ( n < 0 ) {
return "-" + positiveIntToString( -n );
} else {
return positiveIntToString(n);
}
}
private static String positiveIntToString( int n ) {
if ( n == 0 ) {
return "";
} else {
return positiveIntToString( n / 10 ) + ( n % 10 );
}
}
You have the public function that is what you expose to the world. The recursive function is private, and it is only called for positive numbers. If called with zero, it will return an empty string, which is good for the recursion, but not as a real solution.
So the public function first checks two possible issues. If the number is zero, it shouldn't be passed to the private function because it will not return the correct answer. Instead, just return the string "0", as it is the correct answer.
For a negative number, all we need to do is do the work for its counterpart, -n, which is positive and so will be acceptable to the private function. And then we add the "-" in front.
The recursive function for positive integers then becomes very simple: if it's zero, return empty string. For anything else, call itself with n/10, tack the n%10 to the right side of the result, and return that.
Here is also an alternative solution, without a private method:
public static String intToString( int n ) {
if ( n == 0 ) {
return "0";
} else if ( n < 0 ) {
return "-" + intToString( -n );
} else if ( n < 10 ) {
return "" + (n%10);
} else {
return intToString(n/10) + (n%10);
}
}
I actually consider this to be a slightly less efficient solution, because we do two more checks on each level. The check for negative will only be true once, at the top level. The check for zero will only be true if the function is called with zero in the first place. The check for single digit numbers is the current recursion end (because we can't stop the recursion at zero, otherwise we'll always get an extra "0" at the beginning).
I have to write a program which reads in 3 numbers (using input boxes), and depending on their values it should write one of these messages:
All 3 numbers are odd
OR
All 3 numbers are even
OR
2 numbers are odd and 1 is even
OR
1 number is odd and 2 are even
This is what I have so far:
import javax.swing.JOptionPane;
class program3
{
public static void main(String[] args)
{
String num1 = JOptionPane.showInputDialog("Enter first number.");
String num2 = JOptionPane.showInputDialog("Enter second number.");
String num3 = JOptionPane.showInputDialog("Enter third number.");
boolean newnum1 = Integer.parseInt(num1);
boolean newnum2 = Integer.parseInt(num2);
boolean newnum3 = Integer.parseInt(num3);
}
}
This is where I am stuck. I am not sure how to use the MOD to display the messages. I think I have to also use an IF Statement too...But I'm not too sure.
Please help! :D
In Java, the modulus operator is %. You can use it like this:
if ( (a % 2) == 0) {
System.out.println("a is even");
}
else {
System.out.println("a is odd");
}
Combine it with some if statements or some counter to implement the final result.
PS: the type of newnumX looks odd :)
I would recommend you to
Start writing down in a piece of paper how would you do it manually.
( Write the algorithm )
Then identify which parts are "programmable" and which ones are not ( identify variables, statements, etc ) .
Try by hand different numbers and see if it is working.
From there we can help you to translate those thoughts into working code ( that's the easy part ).
These are basics programming skills that you have to master.
It is not worth we just answer:
boolean areAllEven = ( one % 2 == 0 ) && ( two % 2 == 0 ) && ( three % 2 == 0 ) ;
boolean areAllOdd = ( one % 2 != ..... etc etc
Because we would be diss-helping you.
Related entry: Process to pass from problem to code. How did you learn?
To avoid big ugly nested IFs, I would declare a small counter (in pseudocode):
if newnum1 mod 2 == 1 then oddcount += 1;
etc...
switch oddcount
case 0:
print "All three numbers are even"
etc...
Just a warning if you choose to use the % operator in Java: if its left-hand operand is negative, it will yield a negative number. (see the language specification) That is, (-5) % 2 produces the result -1.
You might want to consider bitwise operations e.g. "x & 1" to test for even/odd-ness.
Its even simpler than that, you have tree numbers a, b, c
n = a%2 + b%2 +c%2
switch (n):
case 0: 'three are even'
case 1: 'one is odd'
case 2: 'one is even'
case 3: 'three are odd'
And voila!
Write down the basic steps that you have to do to perform the task and then try to implement it in code.
Here is what you have to do:
1 - Get 3 numbers from the user.
2 - You need two variables: one to hold the number of odd inputs and the other to hold the number of the even ones. Lets call these evenCnt and oddCnt. (Hint: Since you know you only have 3 numbers, once you have determined one of these, the other one is just the difference from 3)
3 - Then you need a series of tests (If evenCnt is 3 then show "3 evens", else if ....)
(And Pascal and Kurosch have pretty much given you the fragments you need to fill in steps 2 and 3.)
[Edit: My #2 is wooly-headed. You only need one variable.]
Here you go. I just compiled and ran some test cases through this to confirm it works.
import javax.swing.JOptionPane;
class Program3 {
public static void main(String[] args) {
int evenCount = 0;
for (int i=0; i<3; i++) {
// get the input from the user as a String
String stringInput = JOptionPane.showInputDialog("Enter number " + (i+1) + ".");
// convert the string to an integer so we can check if it's even
int num = Integer.parseInt(stringInput);
// The number is considered even if after dividing by 2 the remainder is zero
if (num % 2 == 0) {
evenCount++;
}
}
switch (evenCount) {
case 3:
System.out.println("All are even");
break;
case 2:
System.out.println("Two are even, one is odd");
break;
case 1:
System.out.println("One is even, two are odd");
break;
case 0:
System.out.println("All are odd");
break;
}
}
}
BTW: I capitalized the class name because it's best practice to do so in Java.
I disagree with alphazero. I don't think two variables are REQUIRED. every number is either ever or odd. So keeping count of one is enough.
As for Asaph's code, I think it is well documented, but if you still want an explanation, here goes:
This is what the for loop does:
It reads (as Strings) user input for the 3 numbers
Integer.parseInt is a function that takes a String as a parameter (for example, '4') and returns an int (in this example, 4). He then checks if this integer is even by modding it by 2. The basic idea is: 4%2 = 0 and 9%2 = 1 (the mod operator when used as a%b gives the remainder after the operation a/b. Therefore if a%2 is 0, then a is even). There is a counter (called evenCount) that keeps track of how many integers are even (based on the %s test).
He then proceeds to do switch statement on the evenCount. A switch statement is sort of like an if-else statement. The way it works is by testing the switch parameter (in this case, evenCount) against the case values (in this case, 3, 2, 1, 0). If the test returns True, then the code in the case block is executed. If there is no break statement at the end of that case block, then, the code in the following case block is also executed.
Here, Asaph is checking to see how many numbers are even by comparing the evenCount to 0, 1, 2, and 3, and then usinga appropriate print statements to tell the user how many even numbers there are
Hope this helps