Figure out Odd Even or Zero by entering the value - java

My teacher asked me a question and I was really confused how to write it out as a code. I understood what I had to do, but just couldn't write in Java. So the question was that: Design and implement an application that determines and prints the number of odd even and zero digits. Input could be anything from the user/keyboard. I just don't know how to start. So can someone help me here with an answer and an explanation with that?(without using string)
Thank you so much for your time.

Application? It's three lines:
int odds = str.replaceAll("[^13579]", "").length();
int evens = str.replaceAll("[^2468]", "").length();
int zeroes = str.replaceAll("[^0]", "").length();
If the input is not a string, make it one:
long number;
String str = number + "";

I would use a for loop to traverse the input string. Within the for loop would be a switch statement that increments either the 'odd' variable, the 'even' variable,' the 'zero' variable, or does nothing.
This way the string is only traversed once instead of three times.
The code would look something like:
int numOdds = 0;
int numEvens = 0;
int numZeroes = 0;
for(int i = 0; i < inputString.length(); i++) {
switch(inputString.charAt(i)) {
case '1':
case '3':
case '5':
case '7':
case '9': numOdds++;
break;
case '2':
case '4':
case '6':
case '8': numEvens++;
break;
case '0': numZeroes++;
default: break;
}
}

Looks like you have a couple answers. Here is another you may like more because you probably can understand it:
int odds, evens, zeroes;
public void setOddsEvensZereos(String str) {
for(char c:str) {
try {
int i = Integer.parseInt(c + "");
if(i == 0)
zereos++;
else if(i % 2 == 0)
evens++;
else
odds++;
} catch (Exception e){/*the character isn't a number*/}
}
}

Related

Current method "evaluatePostfix" running but printing out false results (java)

I have written my code that is a linked list using stacks. The program, that takes an infix form and converts it to postfix, is currently outputting (with the use of my input and output files) the correct conversions. However, I don't understand how to get the evaluatePostFix method to work properly. My problem is printing out false results and I don't know why. Any help is appreciated!
My current evaluatePostfix method:
public static int evaluatePostfix(String postfix) {
Stack<Integer> stack = new Stack<>();
Stack<Character> operatorStack = new Stack<>();
int count = 0;
int operandTwo = '0';
int operandOne = '0';
while (count < postfix.length() && count >= 0) {
char nextCharacter = postfix.charAt(count);
switch(nextCharacter) {
case '^':
operatorStack.push (nextCharacter);
break;
case '+':
stack.push(operandTwo + operandOne);
case '-':
stack.push(operandTwo - operandOne);
case '*':
stack.push(operandTwo * operandOne);
case '/':
stack.push(operandTwo / operandOne);
int result1 = nextCharacter;
stack.push(result1);
break;
default: break;
} //End switch
count = count + 1;
} //End while
//return stack.pop();
return stack.peek();
} //End evaluatePostfix
case '+':
stack.push(operandTwo + operandOne);
case '-':
stack.push(operandTwo - operandOne);
You will want to have a break statement in there to avoid falling into the next case block.
You will want to pop these two operands off your stack first, otherwise you don't get to access their values (and they remain on the stack, too).
In general, to debug this kind of code, useful tools are stepping through with a debugger, inserting println statements, writing unit tests and reasoning about the flow and variable state on a piece of paper.

How to create a program that converts binary to decimal

I'm trying to convert binary to decimal, how do I change my code to be able to do that? Where did I mess up?
i tried looking at other examples, looking at java api and watching videos but i still can't figure out what mistake i have made.
package Calculator;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("(2) Convert binary to decimal");
System.out.println("\n\n Please enter your choice: ");
int choice = scan.nextInt();
if(choice == 2){
scan.nextLine();
//prompt for user input
System.out.println("Please enter a binary number: ");
String binary = scan.nextLine();
char[] binaryArray = binary.toCharArray();
int i=1;
int integer=0;
//potential problem somewhere around here?
while(i<8){
if(binaryArray[i]==0) {
++i;
}else if(binaryArray[i]==1) {
switch(i) {
case 1:
integer+=128;
++i;
break;
case 2:
integer+=64;
++i;
break;
case 3:
integer+=32;
++i;
break;
case 4:
integer+=16;
++i;
break;
case 5:
integer+=8;
++i;
break;
case 6:
integer+=4;
++i;
break;
case 7:
integer+=2;
++i;
break;
case 8:
integer+=1;
++i;
break;
}
}
}
System.out.println("The decimal value of the binary number is: "+ integer);
scan.close();
}
}
}
The input is always 0. I've tried 11010110, 11111111,and 01010111. Always 0. I know the problem lies somewhere with my integer value not changing but I can't figure out what it specifically is.
This is happening because you are reading the input, and converting into an array of char.
Anywhere where you are making your comparisons to an int, you should instead be doing a comparison to a char, by wrapping your values in single quotations.
while(i<8){
if(binaryArray[i]=='0') {
++i;
}else if(binaryArray[i]=='1') {
switch(i) {
case 1:
integer+=128;
++i;
break;
case 2:
integer+=64;
++i;
break;
case 3:
integer+=32;
++i;
break;
case 4:
integer+=16;
++i;
break;
case 5:
integer+=8;
++i;
break;
case 6:
integer+=4;
++i;
break;
case 7:
integer+=2;
++i;
break;
case 8:
integer+=1;
++i;
break;
}
}
Others have already pointed out that you have got confused between 0 and 1, and '0' and'1'`.
Other problems:
Your i starts at 1, so you miss the most significant bit;
You will never actually hit case 8: in the switch because of the while (i < 8) loop guard.
This doesn't work unless you enter exactly 8 bits.
You can write the entire while loop in a much more concise way:
for (int i = 0; i < binaryArray.length; i++) {
integer *= 2; // shift the digits along by 1 place
if (binaryArray[i] == '1') {
integer += 1; // set the least significant bit.
}
}
You should get away from all those switch statements.
Say you have "10101101" as input.
set val = 0;
Then either multiply by val by 2 or shift left 1 bit. They're the same. It is important
you do this before adding the next bit.
Start from the left and if it's a '1', add a 1 to val. Otherwise, add 0.
Then repeat starting at multiply until you've gone thru the string.
val should then have the decimal version when you print it.

How to add 14 based numbers in instance method?

So I'm having trouble with creating an instance method to add two 14-based number and I was wondering if anyone could help? I'm a bit new to java and still sort of confused on the whole thing. So far I have the code to convert the 14-based numbers to base 10 then I need to add them and convert them back to base-14. I want to put them all in once instance class, but I feel like it's too much to put into one instance class.
This is the kind of input I was for the client code to be like this:
PokerNum sum = num1.add(num2);
import java.util.Scanner;
public class PokerNum{
String alienNum;
int num1, num2;
public PokerNum(String alienNum) throws IllegalArgumentException{
this.alienNum = alienNum;
String toUpper = alienNum.toUpperCase();
for (int i = 0; i < toUpper.length(); i++){
char c = toUpper.charAt(i);
if (!(Character.isDigit(c) || c == 'A' || c == 'J' || c == 'Q' || c == 'K')){
throw new IllegalArgumentException("invalid input");
}
}
}
// initialized at zero
public PokerNum() {
this.num1=0;
this.num2=0;
}
#Override public String toString(){
return PokerNum()+ " ";
}
//add pokernums
public PokerNum add(PokerNum another){
PokerNum num = new PokerNum();
this.num1 = another.num1;
this.num2 = another.num2;
public PokerNum convert(PokerNum pn){
char[] firstNum = num1.toCharArray();
int amountValue = 0;
int length = characters.length;
for (int index = 0; index < length; index++){
int symbolValue;
switch (characters[index]) {
case 'A':
symbolValue = 10;
break;
case 'J':
symbolValue = 11;
break;
case 'Q':
symbolValue = 12;
break;
case 'K':
symbolValue= 13;
break;
default:
symbolValue = characters[index] - 48;
}
amountValue += symbolValue*Math.pow(14, length - index - 1);
}
StringBuilder result1 = new StringBuilder();
while(amountValue > 0){
int digit = amountValue%14;
switch (digit) {
case 10:
result.insert(0, 'A');
break;
case 11:
result.insert(0, 'J');
break;
case 12:
result.insert(0, 'Q');
break;
case 13:
result.insert(0, 'K');
break;
default:
result.insert(0, digit);
}
amountValue-=digit;
amountValue/=14;
String firstValue = result1.toString();
}
}
char[] secNum = num2.toCharArray();
int amountValue2= 0;
int length = secNum.length;
for (int index = 0; index < length; index++){
int symbolValue;
switch (characters[index]) {
case 'A':
symbolValue = 10;
break;
case 'J':
symbolValue = 11;
break;
case 'Q':
symbolValue = 12;
break;
case 'K':
symbolValue= 13;
break;
default:
symbolValue = characters[index] - 48;
}
amountValue2+= symbolValue*Math.pow(14, length - index - 1);
}
StringBuilder result = new StringBuilder();
while(amountValue2> 0){
int digit = amountValue%14;
switch (digit) {
case 10:
result.insert(0, 'A');
break;
case 11:
result.insert(0, 'J');
break;
case 12:
result.insert(0, 'Q');
break;
case 13:
result.insert(0, 'K');
break;
default:
result.insert(0, digit);
}
amountValue2-=digit;
amountValue2/=14;
PokerNum secondValue = result.toString();
}
return firstValue + secondValue;
/*PokerNum sum = num1 +
PokerNum another.num2 =
return sum;*/
}
Thanks to anyone who helps in advance :)
I believe you can keep it in one instance. One suggestion is to use the conversion using the following functions:
Integer.parseInt(String s, int radix)
Integer.toString(int i, int radix)
The javadoc says that the string produced will use:
0123456789abcdefghijklmnopqrstuvwxyz
So, if we choose radix = 14, it will have 0123456789abcd.
The logic idea is to keep the actual number as int, and to convert at creation and at printout from and to String. We can just keep member variable num1 and remove the member variable alienNum and num2.
Constructor
Your constructor with String argument seems to do a good error checking. What we need here is just to convert from string to integer and store it in the member variable. First we need to convert all valid string from AJQK to ABCD. The example here is inefficient, but gets the idea across:
//alienNum = alienNum.replace('A', 'A'); // no need
alienNum = alienNum.replace('J', 'B');
alienNum = alienNum.replace('Q', 'C');
alienNum = alienNum.replace('K', 'D');
Then we can call the parsing method:
num1 = Integer.parseInt(alienNum , 14);
Your empty arg constructor is already fine by initializing the value of num1 to 0.
Adding
The method inside addition is not right because it is setting the current value to the addition. There are three objects working here: num, this, and another. You want to add this to another into num and return num.
num.num1 = this.num1 + another.num1;
Output
I'm assuming the output is going to be from toString(). In this case, you want to convert from integer to string, then convert it to the right character
String out = Integer.toString(num1, 14).toUpper();
//alienNum = alienNum.replace('A', 'A'); // no need
alienNum = alienNum.replace('B', 'J');
alienNum = alienNum.replace('C', 'Q');
alienNum = alienNum.replace('D', 'k');
You probably won't need a convert method now.

How to check if a string contains a letter different then a given range in Java

I'm learning Java and I need to write a program that converts Roman numerals and traditional integers.
The code only accepts the letters MDCLXVI as Roman numerals. It does not accept any number.
This is my code:
System.out.print("Enter a roman numeral");
Scanner keyb = new Scanner(System.in);
String roman = keyb.next();
if(roman.matches(".*[0-9].*") || **something different then M, D, C, L, X, V or I**)
{
System.out.println("Wrong! Re-type.");
}
The problem that I'm trying to solve is how to write the second condition of the If.
first off all you have to check if the given Roman number is valid or not. So the method could look like the following:
public static boolean isValid(String romanNumber) {
String pattern = "[m|d|c|l|x|v|i]*";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(romanNumber);
return m.matches();
}
Then you can use this one inside your converter method. After you made this, it is necessary to convert each character inside your Roman string. So you can go ahead by creating a switch-function, which can be used inside of a for-loop.
public static int convertCharacter(String romanNumber, int position) {
char c = romanNumber.charAt(position);
switch (c) {
case 'm':
return 1000;
case 'd':
return 500;
case 'c':
return 100;
case 'l':
return 50;
case 'x':
return 10;
case 'v':
return 5;
case 'i':
return 1;
default:
return 0;
}
}
And due to fact that you are new to Java, I will show you, how the converter method could be written. This one is not the best solution, but it worked for me. Using this one, it will also be possible to convert numbers like "MCMXCIX".
I deleted the comments. So try to understand what the code does. Otherwise you won't learn from it.
public static int convertRomanNumber(String romanNumber) {
romanNumber = romanNumber.toLowerCase();
if (!isValid(romanNumber)) {
System.out.println("Invalid character detected");
System.exit(0);
}
int result = 0;
int currentNumber;
int nextNumber;
for (int i = 0; i < romanNumber.length(); i++) {
currentNumber = convertCharacter(romanNumber, i);
if (i < romanNumber.length() - 1) {
nextNumber = convertCharacter(romanNumber, i + 1);
if (nextNumber > currentNumber) {
result += currentNumber * -1;
} else {
result += currentNumber;
}
} else {
result += currentNumber;
}
}
System.out.println("Your input: " + romanNumber.toUpperCase());
return result;
}
I hope it helps you for the future.
All the best.
First I use toLowerCase() to lower case the user input, then use matches() to check whether the user input is equal to the character of M D C L X V I.
String user_input = "M";
if (user_input.toLowerCase().matches("m|d|c|l|x|v|i")){
System.out.println("Matches");
}
you can use this:
if(roman.matches(".*[0-9].*") ||
!roman.matches("[MDCLXVI]"))
this for case insensitive:
if(roman.matches(".*[0-9].*") ||
!roman.matches("(?i)[MDCLXVI]"))

Why do I get this "unreachable statement" error?

I am converting a roman numeral input to it's integer value. In my convertChar method, I keep getting an error that it is an unreachable statement whenever I add a break statement in to the code. I don't know why this is. I'm a new student and I must have done something wrong and I was hoping maybe someone can show me what I did wrong and how to fix it. It must have something to do with the way I set the methods up right? I still get confused on what variables to input so maybe I messed up there but I'm not experienced enough to know exactly what I did wrong. Here is everything I have:
public class RomanNumeralConverter {
public int romanInput() {
return convert(getUserInput());
}
public String getUserInput() {
Scanner numberInput = new Scanner (System.in);
System.out.print("Enter a roman numeral in uppercase: ");
String userInput = numberInput.next();
numberInput.close();
return userInput;
}
public int convert (String userInput) {
int result = 0;
int subtractamount = 0;
int x = userInput.length();
while(x != 0) {
char romanConvert = userInput.charAt(x);
if(x >= 1) {
if(convertChar(romanConvert) >= convertChar(userInput.charAt(x - 1))) {
subtractamount += convertChar(userInput.charAt(x - 1));
}
}
result += convertChar(romanConvert);
x--;
}
result -= subtractamount;
return result;
}
public static char convertChar(char value) {
switch (value) {
case 'I':
return 1;
break;
case 'V':
return 5;
break;
case 'X':
return 10;
break;
case 'L':
return 50;
break;
case 'C':
return 100;
break;
case 'D':
return 500;
break;
case 'M':
return 1000;
break;
default:
System.out.println("Invalid character!");
return 0;
break;
}
return value;
}
public void printValue() {
System.out.println(romanInput());
}
public static void main(String[] args) {
new RomanNumeralConverter().printValue();
}
}
Your problem lies in your switch statement. You can minimize this occurring elsewhere by attempting to have methods return only once (which i think is best practice)
public static char convertChar(char value) {
char result;
switch (value) {
case 'I':
result = 1;
break;
case 'V':
result = 5;
break;
case 'X':
result = = 10;
break;
case 'L':
result = 50;
break;
case 'C':
result = 100;
break;
case 'D':
result = 500;
break;
case 'M':
result = 1000;
break;
default:
System.out.println("Invalid character!");
result = 0;
break;
}
return result
}
In Java, it is a compile error to have statements that will never be reached while execution. In your case, the break statement will never be reached as there is a return statement above it. Also that last return statement will never be reached as you already would have returned in any case by the end of the switch block.
The problem is in your switch statement.
A default case can be thought of like the else in an if-else statement; it will always execute if no other condition in the switch is satisfied. If you are performing a return (or throw) inside of a default case, any code that follows after that will not be reachable.
You have two options:
Change the return statements to only assign a value to result instead, meaning that there's only one point of return from your code, or
Remove the return result from after your switch.

Categories

Resources