Char of string outputting incorrectly - java

This is my program and what I am trying to achieve is taking the char value in string amount1 at position 1 i.e for example amount1=$3.00 amount2=2. However it doesn't print out what I expected, 2.
System.out.print("$"+cost[0]+".00 remains to be paid. Enter coin or note: ");
String amount1 = keyboard.nextLine();
char amount2 = amount1.charAt(1);
String amountcheck = "$"+cost[0]+".00";
int [] remainder = new int[1];
if (amount1.equals(amountcheck)) {
System.out.println("Perfect! No change given."); }
if (amount2 < cost[0]) {
remainder[0] = cost[0] - amount2; }
System.out.println("Remainder = "+remainder[0]);
System.out.println(+amount2);
For example,
$3.00 remains to be paid. Enter coin or note: $2.00
Remainder = 0
50
The problem is both in lines 2 and 3. Firstly 3, It don't understand why it outputs 50 as char at amount1 index 1. If i'm not wrong don't char positions work similarly off array index systems. Secondly line 3, the if statement in lines of 8 and 9 of my original code don't seem to catch that amount 2 < cost[0] and don't do the following operations.
So what I expected to happen when I am taking char at position 1 of "$2.00" is newamount would be equal to 2 instead of 50 which the program is outputting.
I've tried changing the char positions but all this seems to do is decrement the value.

You set your amount2 as a char and when you print it, it translates to the ASCII number of that charater which for the charater '2' is 50.
If you want to output 2 you should change your amount2 to type intand parse the char to integer like this Integer.parseInt(""+amount1.charAt(1)); in line 3.

You are using a char to store a numeric value, but that value is a character, not a number. Meaning you are storing '2' which is actually 50 in ASCII. You should remove the value of 48 to get the correct value ('0') or parse the String into a number directly with Integer.parseInt(String).
But as I said in comment, this is easy to correct so I will not provide much more code to this.
But let's be honnest, your logic is risky from the beginning.
You are asking the user to input an amount in a specific format : "$#.00". If the number is two digit $##.00 it fails, if he add a space or don't put the $ or any mistake that users are professional to find, it fails.
First, you should simplified this, do you need the $ ? Ask for dollar currency if you want to specifiy it.
Then, do you need decimals ? Let first assume you don't (see Note for decimal hint).
You just need to input an integer value through the Scanner, which provide method to get Integer -> Scanner.nextInt()
int ammountReceived = keyboard.nextInt();
Then you need to see if this is
Equals
Too much
Not enough
Like this :
int remainder = amountToPay - amountReceived;
if(remainder == 0){
//equals
} else if(remainder > 0){
//not enough
} else {
//too much
}
This would give a simpler solution of :
Scanner sc = new Scanner(System.in);
System.out.print("Amount to pay : $");
int amountToPay = sc.nextInt();
System.out.print("Amount received : $");
int amountReceived = sc.nextInt();
int remainder = amountToPay - amountReceived;
if (remainder == 0) {
System.out.println("That perfect, thanks.");
} else if (remainder > 0) {
System.out.println("Remaining : $" + remainder);
} else {
System.out.println("Need to give back : $" + -remainder);
}
sc.close();
Yours and mine are close, but you will see this is more readable and focused on the problem, I don't play with char to get from a specific String pattern, I am focused on the problem -> to get paid ;)
Now, you have to add a loop here to ask again until you received the correct amount. But please, don't read a numerical String character by character...
Note :
Scanner.nextInt throws exception if the format is incorrect (not an integer)
You can easily adapt this to get double, float or better BigDecimal

Related

Way to get the twos compliment decimal from binary?

I have a simple question, how do I get the twos compliment instead of the regular answer from binary? I have a program that does the booths algorithm but when it returns the decimal it gives me a number that's a bit too high, I'm doing 9 * -9 and the answer it gives is 65455. I just want to know if there is a way to get the twos compliment instead (-81). The binary I get from the code is 1111111110101111 which I know from looking around does equal -81 when finding the two's compliment, I just don't know how to get my program to recognize or say that.
Edit: I found a small fix, essentially just checking if the binary of the product equals the result I got, this is how I've been printing the binary and converting it to a decimal, putting in the print area as The answer said something had to be done here, I got it working properly but would like to clean it up if I can
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Enter the first number: ");
int operand1 = sc.nextInt();
System.out.print("Enter the second number: ");
int operand2 = sc.nextInt();
String answer = multiply(operand1, operand2);
System.out.println("Final Product (binary): " + answer);
int decimal=Integer.parseInt(answer,2);
if(operand1 * operand2 < 0) {
int decProduct = operand1 * operand2;
String biProduct = toBinary(decProduct, 16);
if (biProduct.length() > 16)
{
biProduct = biProduct.substring(biProduct.length() - 16);
}
if(biProduct.equals(answer)) {
decimal = decProduct;
}
}
System.out.println("Final Answer (decimal): " + decimal);
}
The computer has no idea what it means. It just has some memory and in that memory are bits. The bits that are in it, are e.g. 1111111110101111.
What does that sequence mean? Who knows. The computer doesn't know or care.
It's the print code that decides. IT decides that this is to be taken in and then rendered such that the characters -, 8, and 1 appear on your computer screen.
Thus, the error here, is in the print code. There is no converting required. The bit sequence is all the things, at once: It's 1111111110101111, it's 65455, and it is -81. Which one is shown depends on how you print it.
Given that your print code isn't in the question, you're going to have to figure it out with this information.

Java, even number of even digits, odd number of odd digits

This program is essentially a game where the user must enter numbers to see which numbers are good: numbers with an even number of even digits, and an odd number of odd digits.
So first of all, the program ends when I enter a one digit number, which is not intentional. I assume that has something to do with the while being while (n > 0). There also is likely an issue with the if (numEven % 2 == 0......) because the print results seem almost random, with a number being good and the same number not being good sometimes.
Honestly, I am lost at this point. Thank you so much in advance for any help.
UPDATE: This code is working how I want it to, I just wanted to thank everybody who helped out! It's my first semester of computer science class, so I'm still rather new at this...excuse my mistakes that were likely pretty stupid :)
package quackygame;
import java.util.Scanner;
public class QuackyGame
{
public static void main(String[] args)
{
System.out.println("Welcome to the Number Game!"
+ " Try to figure out the pattern "
+ "in the numbers that Wallace likes!");
Scanner scan = new Scanner (System.in);
int n;
int numEven = 0;
int numOdd = 0;
boolean isEven;
do
{
System.out.print("Enter a number > 0: ");
n = scan.nextInt();
while (n > 0)
{
if (n % 2 == 0)
{
//n is even
isEven = true;
numEven++;
}
else
{
//n is odd
isEven = false;
numOdd++;
}
n /= 10;
}
//if numEven is even and numOdd is odd
if (numEven % 2 == 0 && numOdd % 2 == 1)
System.out.println("Wallace liked your number!");
else
{
System.out.println("Wallace didn't like your number.");
}
numEven = 0;
numOdd = 0;
}
while (n >= 0);
}
}
There are a few core issues in the code based on the desired results that you described. The most glaring issue I see is that you intend for the game to essentially "start from scratch" at the beginning of each round, but you never actually reset the numEven and numOdd variables. This is the source of your print results seeming random. For example, if you started a game and input the number:
34567
The game would process the number and say that it is a favorable number because it is odd, has an odd number of odd digits (3), and has an even number of even digits (2). However, upon playing the game again, it would execute the same code without setting the variables back to 0, which means that upon entering:
34567
The game would process this number as a bad number because the accumulated value of odd digits would be 6 instead of 3 (since 3 the first time + 3 the second time results in 6), and 6 is even. So what we want to do is this:
...
int n;
do
{
int numEven = 0;
int numOdd = 0;
System.out.print("Enter a number: ");
n = scan.nextInt();
...
By placing the numEven and numOdd declarations inside of the "do" block, they are local variables which only exist for the duration of the do block. We could also do something as simple as this:
...
else
{
System.out.println("Wallace didn't like your number.");
}
numEven = 0;
numOdd = 0;
}
while (n > 0);
...
Just resetting the values will help us to keep track of the actual intended values of numOdd and numEven more consistently.
With regard to the program closing when you input a single digit number, I'm not sure. That doesn't make sense because since it is a do-while loop it should at least execute once, and issue one of the print statements. I'm loading this code into my IDE right now to give it a run through. I'll update my answer if I find something.
-EDIT-: Upon reading your question again, it seems that you may not be suggesting that the program closes before actually completing any of its functions, but simply that it closes at all. The reason for the closing of the program is that you are performing an integer division arithmetic function where you probably want to be using a different type of number. Let me explain:
In normal human counting, we have our natural set of numbers which have no decimal points. They usually start like this:
1, 2, 3, 4, 5 ...
Then we have a separate set of numbers for math where we operate with more precision:
0.5, 1.4232, 3.142 ...
When we are talking about numbers with normal human language, we assume that dividing 1 by 2 results in 0.5. However, computers do not implicitly know this. In order for a computer to reach the conclusion "0.5" from the division of 1 by 2, you need to explicitly tell it that it should use a certain type of number to produce that output.
The "normal" numbers I referenced earlier are most loosely related to the integer in programming. It's basically a number without a decimal point. What that means is that whenever you divide two integers together, you always get another integer as the result. So if you were to divide 1 by 2, the computer would not interpret the result as 0.5 because that number has a decimal. Instead, it would round it down to the nearest integer, which in this case is 0.
So for a more specific example referencing the actual question at hand, let's say we input the number 5 into our program. It goes through all of the calculations for odds and evens, but eventually gets to this line:
n /= 10
This is where things get funky. We are dividing two integers, but their result does not come out as a perfect integer. In this case, the result of 5 / 10 is again 0.5. But for the computer, since we are dividing two integers, the result 0.5 just won't do, so after rounding down to the nearest integer we get 0. At this point, there is one fatal mistake:
(while n > 0);
When we perform this check, we get false and the while loop ends. Why? Because after performing n /= 10, n becomes 0. And 0 is not greater than 0.
How can we fix this? The best thing to do is probably just use a floating point number to perform the calculations. In Java, this is pretty easy. All we really have to do is:
n /= 10.0
When Java sees that we are dividing by 10.0, which is not an integer, it automatically converts "n" to a floating point number to divide by 10.0. In this case then, if n is 5, our result in dividing 5 by 10.0 will be 0.5. Then, when we run:
(while n > 0);
This becomes true! And the loop does not break.
I am going to put all of these changes into my IDE just to confirm that everything is working as intended for me. I would suggest you give it a try too to see if it fixes your problems.
Hope this helps.
You are increasing numEven or numOdd count each time you input a number, and then you use if (numEven % 2 == 0 && numOdd % 2 == 1) , it is random because if you put number 33 for the first time => numOdd = 1; => true => "Wallace likes" , but next time you put 33 for the second time => numOdd = 2; => false => "Wallace doesnt like".
Edit* Maybe you wanted something like this?
public static void main(String[] args)
{
System.out.println("Welcome to the Number Game!"
+ " Try to figure out the pattern "
+ "in the numbers that Wallace likes!");
Scanner scan = new Scanner (System.in);
int n;
boolean isEven;
do
{
System.out.print("Enter a number: ");
n = scan.nextInt();
//if 0, you leave the loop
if(n==0) {
System.out.println("You pressed 0, have a nice day");
break;
}
if (n % 2 == 0)
{
//it is even
isEven = true;
}
else
{
//it is not even
isEven = false;
}
//if even then he likes it, otherwise he does not
if (isEven)
System.out.println("Wallace liked your number!");
else
{
System.out.println("Wallace didn't like your number.");
}
}
//put any contition here, lets say if you press 0 , you leave the loop
while (n != 0);
}

charAt() for integers greater than 1?

I am trying to create a program that displays the x and y coordinates of any given point, reflected across the linear function ax+b. However, I get a runtime error which says that it's out of bounds. I know you can't invoke methods on primitive data types, but I have no idea how else to get it.
import java.util.*;
public class ReflectivePoint {
public static void main (String[]args){
Scanner lol = new Scanner(System.in);
System.out.println("Please enter the linear function.");
//That will be in the format ax+b
String function = lol.nextLine();
Scanner lol2 = new Scanner(System.in);
System.out.println("Please enter the point.");
//That will be in the format a,b
String point = lol2.nextLine();
int a = point.charAt(1);
int b = point.charAt(3);
int m = function.charAt(1);
int c = function.charAt(4);
int x1 = (2 / (m + 1 / m)) * (c + b - a / m) - a;
int y1 = (-1/m) * x1 + a / m + b;
System.out.println(x1+", "+y1);
}
}
Perhaps you are getting a String of length 3, eg "1,2".
charAt(3) will try and return the 4th char of the String which doesn't exists so it throws an StringIndexOutOfBoundsException.
The index out of bounds error means "You have asked me for the 4th character of this string, but the string has fewer than 4 characters."
Note that (like most computer language indexes), the first character is 0. charAt("hello",1) == 'e'
You should check the length of the string before calling charAt(). Or, catch the exception and handle it.
charAt() probably isn't the best choice for your program, because it will only currently handle single-digits. Try String.split() to split the String on the comma.
Also, at the moment it's using the ASCII value of the character. That is (if you fixed the indexes) "a,b" would result in you doing your maths with m=97 and c=98. I guess that's not what you want. Find out about Integer.parseInt()
Aside from the out of bounds issue, which others have pointed out is you need to start at charAt(0) because the number is an offset into the char array (string), not getting the nth element.
You also need to subtract '0' to convert to an integer.
string point = "4";
int a = point.charAt(0);
//a=52 //not what you wanted
string point = "4";
int a = point.charAt(0) - '0';
//a=4 //this is what you wanted
You can use:
int a = point.charAt(0);
provided that that point is not empty.
Ideally you should perform a pre-use length check on the input String.

Finding the most left digit in a number with Java

I have to find the most left digit in a randomly generated number (for example: 46891 -> 4). No matter what the number is I keep getting zero. Here's one of the codes I try:
int num1 = (int)((Math.random()*100000)+1);
while((Math.floor(num1/10))>0)
{
num1 = (int)Math.floor(num1/10);
}
System.out.println("Left digit: " + num1);
I tried to use Integer.parseInt, but I got this mistake, obviously: The method parseInt(String) in the type Integer is not applicable for the arguments (int).
What am I doing wrong and how can I make it work?
Thank you!
how about this :
final Random r=new Random();
final int t=r.nextInt(100000)+1;
// naive way:
final String s=Integer.toString(t);
System.out.println("left digit is:"+s.charAt(0));
// "math" way:
int temp=t;
while(temp>=10)
temp/=10;
System.out.println("left digit is:"+temp);
Integer division removes the fractional part, so all you need is a simple loop:
int num = (int)((Math.random()*100000)+1);
for ( ; num >= 10 ; num /= 10);
System.out.println(num);
You're almost there! The problem is, the num1 will be a number, not a character, although they are basically the same thing. Convert it to a string using .toString() or use System.out.format with the %i format string.
EDIT: nevermind, I was wrong. You are doing the loop while num1 is greater than 0, the problem being that this loop exits when num1 is 0. In this case, you need to break one before, so I'd just change the test to >=10. In this case, you ensure you have a single digit, which given the nature of the question, must be greater than 0.
I am using code based on yours
int num1 = (int)((Math.random()*100000)+1);
System.out.println("Randomed number: " + num1);
while((num1/10)>0)
num1 = num1/10;
System.out.println("Left digit: " + num1);
and it works fine for me
No need to use Math.floor as integer division rounds down automatically.
And you want to check for num1 > 9 in your loop, to only divide if number is at least 10.
EDIT: I tested your code and it works for me too, without modifications...

Convert fraction to decimal number

i'm doing some exercises in my Java book. I'm very new to programming. Therefore, notice (in the code) that i'm still on Chapter one. Now I already did everything, I just want a confirmation if this is legitimate so I can feel free to move on next.
If not, I would sincerely appreciate to not do my code for me; I want advice.
Here's the question written in the book,
"Write an application that prompts/reads the numerator and denominator of a fraction as integers, then prints the decimal equivalent of the fraction."
I'll illustrate this sentence with my code:
I did a revision here. Is this one OK?..
import java.util.*;
public class ExerciseEleven {
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
double fraction;
int fractionValue;
int decimal;
double value;
System.out.println("Enter Numerator: ");
int numerator = sc.nextInt();
System.out.println("Enter Denominator: ");
int denominator = sc.nextInt();
fraction = (double) numerator / denominator;
fractionValue = (int) (fraction * 10);
decimal = fractionValue % 10;
value = decimal * 0.1;
System.out.println(value);
}
}
It compiles and works fine.
Thank you.
It doesn't do what task says it should. You read doubles instead of integers, and the decimal equivalent is not what you print out. Decimal equivalent for 1/2 is 0.5. And you print 5.
Also, you can pay attention to your code style: variable names are usually written in lowerCamelCase, like that : simpleVariable.
Update
now it prints what you need. However you do it not in the very right way and your indentation can still be improved.
It's fine (I didn't read the assignment very well, did I? Kudos to Vladimir.) ...but some comments:
Usually you want to indent methods within the class.
Standard practice is to use initial caps (Numerator) only for types (e.g., classes, interfaces, enums). Variable, field, and method names should start with a lower-case letter. Now, you're free to ignore standard practice, but if you do people will have a lot of trouble reading your code. :-)
For rounding, you probably want to look at Math.round rather than truncating with a cast. But the assignment didn't say anything about rounding.
You might want to handle the case where denominator is zero.
So keeping those in mind:
import java.util.*;
public class ExcerciseEleven {
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Enter Numerator: ");
int numerator = sc.nextInt();
System.out.println("Enter Denominator: ");
int denominator = sc.nextInt();
if (denominator == 0) {
System.out.println("Can't divide by zero");
}
else {
double fraction = (double)numerator / denominator;
System.out.println(fraction);
}
}
}
Hey I am doing some thinking about this and I have noticed something interesting after looking at this source and here is the Algorithm that I plan on implementing
First I will convert the number from the Metric using the
Javax.Measure family of functions and I will get a number like
0.3750
Then I will divide the number by ONE_SIXTEENTH which = 0.0625
ONE_SIXTEENTH = 0.0625
The answer 0.3750 / ONE_SIXTEENTH = 6;
So now I know there are 6 sixteenths of the inch
Next I check to see if 6 is divisible by 4, 6/4 = 1.5 ie not a whole number so the fraction is still regarded as 6/16th of an inch for now
Next I check to see if 6 is divisible by 2, 6/2 = 3
This is a whole number so we will use it to reconstitute the fraction
So now that we have divided 6 by 2 and gotten 3 the 16 needs to be divided by 2 and we end up with 8 so 6/16th of an inch becomes 3/8th of an inch.
PS Has anyone noticed that this is similar to a fizz bang program?
____________________________________________
Here is the chart which helped me get my head around this
My workings
There are three important parts of division operation :
Sign of the result.
Integral part
Decimal part
Also, there are few corner cases where you need to deal with the fact that Integer.MIN_VALUE is greater than Integer.MAX_VALUE when compared in absolute form.
For example : -2147483648/-1 can't yield 2147483648 when divided in the form of integer types. The reason is simple. The type of the resulting type will be integer type, and the maximum positive value that a integer type variable can hold is +2147483647
To mitigate that scenario, we should at first convert both the numerator and denominator into their long positive form. That gives us the integral part of the answer.
The XOR of two numbers will have the sign bit as 1 only in case they have opposite signs. That solves the first part (sign of result) of the problem.
For decimal part, we can employ the general division rule i.e. multiply the remainder with 10 and try dividing again and repeat. Keep record of the remainder we have already come across to prevent the loop from going into unbounded iterations.
public String fractionToDecimal(int A, int B) {
StringBuilder sb = new StringBuilder((A^B) < 0 ? "-" : "");
long a = Math.abs((long)A);
long b = Math.abs((long)B);
sb.append(Long.toString(a/b));
long rem = a % b;
sb.append((rem != 0) ? "." : "");
Map<Long, Integer> remainderMap = new HashMap<>();
int pos = 0;
while (rem != 0){
sb.append(Long.toString((rem*10)/b));
remainderMap.put(rem, pos++);
rem = (rem*10) % b;
if (remainderMap.containsKey(rem)){
String currNum[] = sb.toString().split("\\.");
return currNum[0] + "." + currNum[1].substring(0, remainderMap.get(rem)) +
"(" + currNum[1].substring(remainderMap.get(rem)) + ")";
}
}
if (sb.toString().equals("-0")) return "0";
return sb.toString();
}
Sample output :
2/3 gives 0.(6)
-2147483648/-1 gives 2147483648

Categories

Resources