I want to write a program which receive a string value and print the decimal number.
In addition, if the string value is not 1 or 0, I need to print a message.
I wrote this code but it is always getting inside the if command.
I Would appreciate your support!
Thank you
import java.util.Random;
public class Decimal {
public static void main(String[] args) {
String input = (args[0]);
int sum = 0;
for (int i = 0; i <= input.length(); i++) {
if (!(input.charAt(i) == '0') || (input.charAt(i) == '1')) {
System.out.println("wrong string");
break;
}
char a = input.charAt(i);
if (a == '1') {
sum |= 0x01;
}
sum <<= 1;
sum >>= 1;
System.out.println(sum);
}
}
}
The ! (not) operator of the if statement only applies to the first part:
if ( ! (input.charAt(i) == '0')
||
(input.charAt(i) == '1')
) {
So that is the same as:
if ((input.charAt(i) != '0') || (input.charAt(i) == '1')) {
When you actually meant to do:
if (input.charAt(i) != '0' && input.charAt(i) != '1') {
It's a good thing though, because once that works, you're going to get an IndexOutOfBoundsException when i == input.length(). Change the loop to:
for (int i = 0; i < input.length(); i++) {
And for performance, move variable a up and use it in that first if statement. Rename to c or ch is more descriptive/common.
Doing both sum <<= 1 and sum >>= 1 leaves you where you started. Is that what you wanted? You should also do the left-shift before setting the right-most bit.
Applying all that, I believe you meant to do this:
String input = args[0];
int sum = 0;
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c != '0' && c != '1') {
System.out.println("wrong string");
break;
}
sum <<= 1;
if (c == '1')
sum |= 1;
}
System.out.println(sum);
Related
Take as input S, a string. Write a function that replaces every odd character with the character having just higher ASCII code and every even character with the character having just lower ASCII code. Print the value returned.
package assignments;
import java.util.Scanner;
public class strings_odd_even_char {
static Scanner scn = new Scanner(System.in);
public static void main(String[] args) {
String str = scn.nextLine();
for (int i = 0; i < str.length(); i = i + 2) {
char ch = str.charAt(i);
ch = (char)((ch + 1));
System.out.println(ch);
}
for (int j = 1; j < str.length(); j = j + 2) {
char ch = str.charAt(j);
ch = (char)((ch - 1));
System.out.print(ch);
}
}
}
The problem with my code is that it is first printing the values for all the odd characters and then for even characters but what I want is that they get printed in proper sequence like for input --> abcg , the output should be --> badf .
I'd hold the "incremenet" value in a variable and alternate it between +1 and -1 as I go voer the characters:
private static String change(String s) {
StringBuilder sb = new StringBuilder(s.length());
int increment = 1;
for (int i = 0; i < s.length(); ++i) {
sb.append((char)(s.charAt(i) + increment));
increment *= -1;
}
return sb.toString();
}
Just use one loop that handles both characters:
for (int i = 0; i < str.length(); i = i + 2) {
char ch = str.charAt(i);
ch = (char) (ch + 1);
System.out.print(ch);
if (i + 1 < str.length()) {
ch = str.charAt(i + 1);
ch = (char) (ch - 1);
System.out.print(ch);
}
}
You only need to iterate one time but do different operation (char+1) or (char-1) depending on the i:
public static void main(String[] args) {
String str = scn.nextLine();
for(int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if(i % 2 == 0) { // even
ch += 1;
} else { // odd
ch -= 1;
}
System.out.print(ch);
}
}
You are using two loops, but you only need one. You can use the % operator to tell if i is even or odd, and then either subtract or add accordingly:
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if(i % 2 == 0) {
ch = (char)((ch + 1));
System.out.println(ch);
} else {
ch = (char)((ch - 1));
System.out.print(ch);
}
}
You can do it in one for loop, to do that you will need to check whether the current index is even or odd. if current index is even you will increment char and print, if it is odd you will decrement char and print. to check if even or odd using % operator
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if(i%2 == 0) {
ch = ch + 1;
System.out.println(ch);
continue;
}
ch = ch - 1;
System.out.println(ch);
}
So, I'm trying to write a program that calculates an expression such as "3+(6/5)+(2*3/7)7/2(9/4+4*1)=", where the order of precedence is as it is written. The only thing that matters is that if there is a sub-expression present within brackets, they should be calculated first.
My code is okay to some extent but the final result is not what it's desired. For example "3+(6/5)+(2*3/7)7/2(9/4+4*1)=" should print 110.63 but it prints 110.69.
"4+6/5+(4*9-8)/7*2=" prints 8.58 but should be 8.57.
I'm almost certain that it has something to do with the rounding but I'm not really sure and can't think of a solution since I'm fairly new to BigDecimal or even programming in general.
PS: It works fine with doubles but I'm receiving runtime errors while running unknown tests on a certain platform for testing, so I thought I'd try with BigDecimal in case it's because of too many numbers after the decimal point but oh, well..
Heres my code:
String nc = scan.nextLine();
BigDecimal j = new BigDecimal(0);
for (int i = 0; i < nc.length(); i++) {
if (nc.charAt(i) == '(') {
int startIndex = nc.indexOf("(");
int endIndex = nc.indexOf(")");
String toBeReplaced = nc.substring(startIndex, endIndex + 1);
String omg = toBeReplaced.replaceAll("\\(|\\)", "");
BigDecimal ok = new BigDecimal(0);
int m=0;
String split[]=omg.split("\\+|\\-|\\*|\\/|\\=");
for (int k = 0; k < omg.length(); k++) {
if (k == 0) {
ok = new BigDecimal(split[0]);
}
if (omg.charAt(k) == '+') {
m++;
ok=ok.add(new BigDecimal(split[m]));
} else if (omg.charAt(k) == '-') {
m++;
ok = ok.subtract(new BigDecimal(split[m]));
} else if (omg.charAt(k) == '*') {
m++;
ok = ok.multiply(new BigDecimal(split[m]));
} else if (omg.charAt(k) == '/') {
m++;
ok = ok.divide(new BigDecimal(split[m]),2,RoundingMode.HALF_EVEN);
}
}
nc = nc.replace(toBeReplaced, ok + "");
}
}
String split[]=nc.split("\\+|\\-|\\*|\\/|\\=");
int k = 0;
for (int i = 0; i < nc.length(); i++) {
if (i == 0) {
j = new BigDecimal(split[0]);
}
if (nc.charAt(i) == '+') {
k++;
j = j.add(new BigDecimal(split[k]));
} else if (nc.charAt(i) == '-') {
k++;
j = j.subtract(new BigDecimal(split[k]));
} else if (nc.charAt(i) == '*') {
k++;
j = j.multiply(new BigDecimal(split[k]));
} else if (nc.charAt(i) == '/') {
k++;
j = j.divide(new BigDecimal(split[k]),2,RoundingMode.HALF_EVEN);
}
}
System.out.println(j.setScale(2, BigDecimal.ROUND_HALF_EVEN);
Here's my code that I've written :
public String binary(String s)
{
String[] a = {
"0000","0001","0010","0011","0100","0101","0110","0111",
"1000","1001","1010","1011","1100","1101","1110","1111"
};
String k = "";
for(int i = 0; i <= s.length() - 1; i++)
{
if (s.charAt(i) == 'a') { k += a[10]; }
else if (s.charAt(i) == 'b') { k += a[11]; }
else if (s.charAt(i) == 'c') { k += a[12]; }
else if (s.charAt(i) == 'd') { k += a[13]; }
else if (s.charAt(i) == 'e') { k += a[14]; }
else if (s.charAt(i) == 'f') { k += a[15]; }
else { k += a[i]; }
}
return k;
}
I am getting output as a[0-9] = 0000. How can I fix this? What am I doing wrong?
The problem is with use of a[i]. It is a logical error. Because i is loop variable which indicates the current index in s String. But you are using it to indexing it in variable a. So, i variable is use incorrectly here.
Following is corrected (and a bit optimized) code. See it working here:
public class HexaDecimal
{
public String binary(String s)
{
String[] a= {"0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"};
String k="";
for(int i=0;i<s.length();i++)
{
char ch = Character.toUpperCase(s.charAt(i));
if(ch>='A' && ch <= 'F') k+= a[ch - 'A' + 10];
else k+= a[ch - '0'];
}
return k;
}
}
Replace k+=a[i]; with k+=a[s.charAt(i) - '0'];
You're using your string index loop variable as an index into a rather than the character at that location in the string.
You need to do - '0' to convert from unicode codepoint to the value it represents as an ASCII digit (which I assume you want to use here)
Your last else does the incorrect calculation. It does not take into consideration what is inputted, only the position. You want it to be
else {
k += a[s.charAt(i) - '0'];
}
There are easier ways to get the binary representation of hexadecimals, and you probably also want to check the input that it does not contain anything else than 0-9 or a-f.
You can change the for loop to this:
for(int i=0; i < s.length(); i++)
{
char c = s.charAt(i);
if (c >= '0' && c <= '9') k += a[c - '0'];
else if (c >= 'a' && c <= 'f') k += a[c - 'a' + 10];
else if (c >= 'A' && c <= 'F') k += a[c - 'A' + 10];
else throw new InvalidArgumentException(s);
}
This is a lot simpler and self-explanatory, at least in my opinion. Handles digits, uppercase and lowercase letters, and fails in an expected way on bad input.
I wanna to solve my Homework about calculating number value of String in Java like "-3.1+0.12*0.0023-34.1/2.1"
I have limitations to use only Arrays and Strings and not use recursive functions (as first year student)
What I try?
I am trying to solve it by parsing string char by char.
I try this method only for + and - :
public static double CalcPlusMinus(String s) {
double A[] = new double[10000];
if ((s.charAt(0) != '+') && (s.charAt(0) != '-'))
s = '+' + s;
int i = 0, j = 0;
while (i < s.length()) {
int flag = 1;
if (s.charAt(i) == '-')
flag = -1;
i++;
double m = 0;
int end = 0;
if ((s.charAt(i) >= '0') && (s.charAt(i) <= '9'))
while ((s.charAt(i) >= '0') && (s.charAt(i) <= '9')) {
m = m * 10 + (s.charAt(i) - '0');
i++;
if (i >= s.length()) {
end = 1;
break;
}
}
if (end == 0)
if (s.charAt(i) == '.') {
i++;
double x = 10;
while ((s.charAt(i) >= '0') && (s.charAt(i) <= '9')) {
m = m + ((s.charAt(i) - '0') / x);
x *= 10;
i++;
if (i >= s.length())
break;
}
}
A[j++] = m * flag;
}
A[A.length - 1] = j;
for (int m = (int) A[A.length - 1] - 1; m > 0; m--) {
A[m - 1] = A[m] + A[m - 1];
}
return A[0];
}
I am trying to add * and / to this method
But my main question is : how can I control a lot of if-then-else in my code?
Is there any formal way to control a lot of ifs in the code?
I know flowcharts, but the flowchart turn to a very big picture too!!
You should have 3 separate steps:
parsing/tokenization - spiting "-3.1+0.12*0.0023-34.1/2.1" into:
"-" "3.1" "+" "0.12" "*" "0.0023" "-" "34.1" "/" "2.1"
convert to Reverse Polish notation, using array as a stack
calculating the value of expression
for (int i = 0; i < str.length(); i ++) // Checks every position of array
{
arr[i] = str.charAt(i); // Ignore this, not needed
if (arr[i] != ',' || arr[i] != '.' || arr[i] != '$') // Checks every position of array to see if any character equals a comma, decimal point, or a dollar sign
{
// Ignore below
/*
valueString = String.valueOf(value);
numOfAsterisks = arr.length - valueString.length();
for (int asterisk = 0; asterisk <= numOfAsterisks; asterisk ++)
{
System.out.print("*");
}
System.out.println((int)value);
*/
}
}
Here, what I want to do is to check an array of characters and see if the array contains a comma, a decimal point, or a dollar sign. If the array does not contain any of these characters, then the commented-out portion (where it says "Ignore below") will be executed. The only problem I have here is that because if (arr[i] != ',' || arr[i] != '.' || arr[i] != '$') is under the outside for loop, the commented-out part is executed multiple times. I need the code to execute only once, but still check each position of the array.
If I understand your question correctly, what you actually want is something like this:
boolean found = false;
for(int i = 0; i < str.length; i++) {
char c = str.charAt(i);
if(c == ',' || c == '.' || c == '$') {
found = true;
break;
}
}
if(!found) {
/* Your commented-out code */
}
Note that this can also be formulated as such:
skip: {
for(int i = 0; i < str.length; i++) {
char c = str.charAt(i);
if(c == ',' || c == '.' || c == '$')
break skip;
}
/* Your commented out code goes here. */
}
Choose for yourself which you like more. :)