How to analyze evenness/oddness of numbers in Java - java

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

Related

Get random operators and integers

im doing an assignment which requires me to create 3 classes.
1 with getting 2 random integers,
1 with getting random operators such as + - * / which should be done so in char method
the last one to check if the simple mathematics answer is correct using booleans via user Scanner input.
i need a little help here as im not sure if i've done the random operators method correctly and am really lost at how i should tabulate both random int and operators together in one class.
here's the code i've done so far:
public static char getOperator (int x, int y)
{
char operator;
int answer;
switch (rand.nextInt(4))
{
case 0: operator = '+';
answer = x + y;
break;
case 1: operator = '-';
answer = x - y;;
break;
case 2: operator = '*';
answer = x * y;;
break;
case 3: operator = '/';
answer = x / y;;
break;
default: operator = '?';
}
return operator;
}
I believe you mean you need to create 3 methods (and not classes).
One that creates a random integer (it's a bad design to create a
method that returns two integers instead of just calling two times
one that returns one int).
One that returns a random operator
One that checks if an operation consisting of "random-number
random-operator random-number" is equal to user input
Anyways, there's a lot to unpack here, so:
Your first method getTwoIntegers is incorrect, you're asking for two integers in input but you never actually use them, then you return one random number.
The method getOperator needs to be redesigned to have no input and return one char (equal to + - x /).
Your final method will call the your first method twice, then the second method once, it will then print the operation for the user to see, and check if the response is correct.
Hopefully this can help you conceptualize better the way you should build your code.
I didn't post the source code since I believe it's much better for you if you try to do it by yourself (this being an assignment and all)
Good luck and have fun :)

Questions regarding programming a single-line calculator in Java

I am currently a early CS student and have begun to start projects outside of class just to gain more experience. I thought I would try and design a calculator.
However, instead of using prompts like "Input a number" etc. I wanted to design one that would take an input of for example "1+2+3" and then output the answer.
I have made some progress, but I am stuck on how to make the calculator more flexible.
Scanner userInput = new Scanner(System.in);
String tempString = userInput.nextLine();
String calcString[] = tempString.split("");
Here, I take the user's input, 1+2+3 as a String that is then stored in tempString. I then split it and put it into the calcString array.
This works out fine, I get "1+2+3" when printing out all elements of calcString[].
for (i = 0; i <= calcString.length; i += 2) {
calcIntegers[i] = Integer.parseInt(calcString[i]);
}
I then convert the integer parts of calcString[] to actual integers by putting them into a integer array.
This gives me "1 0 2 0 3", where the zeroes are where the operators should eventually be.
if (calcString[1].equals("+") && calcString[3].equals("+")) {
int retVal = calcIntegers[0] + calcIntegers[2] + calcIntegers[4];
System.out.print(retVal);
}
This is where I am kind of stuck. This works out fine, but obviously isn't very flexible, as it doesn't account for multiple operators at the same like 1 / 2 * 3 - 4.
Furthermore, I'm not sure how to expand the calculator to take in longer lines. I have noticed a pattern where the even elements will contain numbers, and then odd elements contain the operators. However, I'm not sure how to implement this so that it will convert all even elements to their integer counterparts, and all the odd elements to their actual operators, then combine the two.
Hopefully you guys can throw me some tips or hints to help me with this! Thanks for your time, sorry for the somewhat long question.
Create the string to hold the expression :
String expr = "1 + 2 / 3 * 4"; //or something else
Use the String method .split() :
String tokens = expr.split(" ");
for loop through the tokens array and if you encounter a number add it to a stack. If you encounter an operator AND there are two numbers on the stack, pop them off and operate on them and then push back to the stack. Keep looping until no more tokens are available. At the end, there will only be one number left on the stack and that is the answer.
The "stack" in java can be represented by an ArrayList and you can add() to push items onto the stack and then you can use list.get(list.size()-1); list.remove(list.size()-1) as the pop.
You are taking input from user and it can be 2 digit number too.
so
for (i = 0; i <= calcString.length; i += 2) {
calcIntegers[i] = Integer.parseInt(calcString[i]);
}
will not work for 2 digit number as your modification is i+=2.
Better way to check for range of number for each char present in string. You can use condition based ASCII values.
Since you have separated your entire input into strings, what you should do is check where the operations appear in your calcString array.
You can use this regex to check if any particular String is an operation:
Pattern.matches("[+-[*/]]",operation )
where operation is a String value in calcString
Use this check to seperate values and operations, by first checking if any elements qualify this check. Then club together the values that do not qualify.
For example,
If user inputs
4*51/6-3
You should find that calcString[1],calcString[4] and calcString[6] are operations.
Then you should find the values you need to perform operations on by consolidating neighboring digits that are not separated by operations. In the above example, you must consolidate calcString[2] and calcString[3]
To consolidate such digits you can use a function like the following:
public int consolidate(int startPosition, int endPosition, ArrayList list)
{
int number = list.get(endPosition);
int power = 10;
for(int i=endPosition-1; i>=startPosition; i--)
{
number = number + (power*(list.get(i)));
power*=10;
}
return number;
}
where startPosition is the position where you encounter the first digit in the list, or immediately following an operation,
and endPosition is the last position in the list till which you have not encountered another operation.
Your ArrayList containing user input must also be passed as an input here!
In the example above you can consolidate calcString[2] and calcString[3] by calling:
consolidate(2,3,calcString)
Remember to verify that only integers exist between the mentioned positions in calcString!
REMEMBER!
You should account for a situation where the user enters multiple operations consecutively.
You need a priority processing algorithm based on the BODMAS (Bracket of, Division, Multiplication, Addition and Subtraction) or other mathematical rule of your preference.
Remember to specify that your program handles only +, -, * and /. And not power, root, etc. functions.
Take care of the data structures you are using according to the range of inputs you are expecting. A Java int will handle values in the range of +/- 2,147,483,647!

Flip Flop numbers check

The output numbers are displayed from 1 to max, one per line with the following exceptions:
numbers divisible by a are replaced with the word "Flip"
the numbers divisible by b are replaced with the word "Flop"
numbers divisible by both are replaced by "FlipFlop"
I am stuck and need a little direction to where my problem is. I thought maybe a for loop would be perfect to go through and list the numbers and have the if else to check each number with the input numbers picked by the user.
import javax.swing.JOptionPane;
public class FlipFlop {
public static void FlipFlop(Integer a, Integer b, Integer Max) {
for (int i = 1; i < Max; i++) {
if (i % a == 0) {
System.out.println("Flip");
} else if (i % b == 0) {
System.out.println("Flop");
} else if (i % a == 0 && i % b == 0) {
System.out.println("FlipFlop");
} else {
System.out.println(i);
}
System.out.println();
}
}
public static void main(String[] arg) {
Integer a;
Integer b;
Integer max;
String Title = "FlipFlop Assignment";
String data = JOptionPane.showInputDialog(null, "Enter your first number", Title, 1);
a = new Integer(data);
data = JOptionPane.showInputDialog(null, "Enter your second number", Title, 1);
b = new Integer(data);
data = JOptionPane.showInputDialog(null, "Enter the upper bound", Title, 1);
max = new Integer(data);
FlipFlop(a, b, max);
}
}
Integer, not integer. That makes max undefined in the first function. Also look into int.
You never actually assign anything to max
All those println functions, you never defined Flip, Flop and FlipFlop. Presumably they're either missing string constants or just plain string literals. (actually your case is even worse, FlipFlop is your function so you're passing the function reference which I bet confuses Java even more)
The flipflop case should come before the other two. Pen and paper should trivially explain why.
There are a few issues here, but the overall code is very close to what you want.
integer max; is creating a variable using an unreal type, I believe you want to be using the passed in variable Max which has a capital 'M'. Be careful of case sensitivity with variables. Generally non-final variables should start with a lower-case letter to prevent confusion.
If you delete the integer max and change your method's Max to max it solves some of your trouble, because right now you aren't using the passed in Max value at all. Unless you yourself have created a class named "integer" you cannot create variables using it.
You are not checking equality in your if statements, you are trying to assign a value. The '=' is trying to assign a value, you want '==' which checks for value equality.
You should move the if statement checking for both Flip and Flop first, because as it is if both are true, only "Flip" will print.
Last, nothing will print at all right now because you don't have Flip, Flop, or FlipFlop inside quotes. You will get a compiler error because there is no variable or class named Flip, or Flop. System.out.println("Flip"); is what you want.

Recursive manual way to convert int to string (without anything like an array, a list, or parsing stuff) for positive and negative numbers [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
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).

Get last number from string

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.

Categories