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...
Related
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
I'm trying to declare a method for my program that takes only a 5 digit integer and for each digit of the integer, reads a value from the program and prints it out. I understand this isn't very clear but im having trouble relaying what I mean. I understand it will be some sort of for loop to read each digit of the integer individually until something reaches 5. Something like the charAt() string method but works for digits.
Read up on "modulo". It is a primitive operation, available via the symbol % in Java.
For division, it is the remainder. So
System.out.println("Last digit: "+(12345 % 10));
will print 5. Figure out yourself how to get the other digits.
As an exercise, figure out how to print binary digits.
You can divide and take modulo.
while(n > 0) {
System.out.println("Digit " + (n % 10));
n /= 10;
}
This works fine if you are using any base: all you need to do is substitute 10 for the base (dividing by the base means shifting everything left, and taking the modulo means getting the last digit).
You can very easily convert your integer to a string and use charAt()
String parseableString = Integer.toString(yourInt);
for (int i = 0; i < parseableString.length(); i++){
System.out.println(parseableString.charAt(i));
}
There are 3 marbles randomly generated and i'll compare them if they are same,different or one is different. My code is below and my question is above... can u help me out ?
public static void marb(){
int a[],b[];
int num=0;
a=new int[3];
b=new int[3];
a[0]=1;
a[1]=2;
a[2]=3;
**num=(int)Math.random();** //num is always assigned 1
for(int x=0;x<3;x++)
{
num=(int)Math.random();
b[x]=a[num];
System.out.println(""+x+". marble:"+b[x]);
}
int x=0;
if(b[x]==b[x+1] && b[x+1]==b[x+2])
System.out.println("ALL SAME");
else if(b[x]!=b[x+1] && b[x]!=b[x+2] && b[x+1]!=b[x+2])
System.out.println("ALL DIFFERENT");
else
System.out.println("One is different");
}
Math.random() returns a double between 0 and 1. Casting to int will always truncate to 0.
If you want a random integer use the Random.nextInt(range) method.
Are you sure that (int) Math.random() always returns 1? If you told us that it always returns 0, I would believe that immediately.
Math.random() returns a double in the range [0;1). The conversion from double to int truncates the number, to it is always 0.
Create an instance of the random number generator
Random rand = new Random();
which also seeds the generator.
Then call
int myrandnum = rand.nextInt();
Subsequent calls to the nextInt method will generate a different number.
Math.random() returns a double >= 0 and < 1. If you want a random number between 0 and x, use (int)(Math.random() * x).
Because Math.random returns a value between 0 and 1 (either double or float I guess). Casting it to an int it loses the value after the decimal point and I guess casting rounds up to 1.
The correct way to use Math.Random() is to multiple it by the uppermost number that you want, then close the parenthesis and cast it to an int (if needed)
int randomNumber = (int)(Math.random()*max)
Its the placement of the parenthesis that you are off on. Math.random is a great function to use when you have an upper bounds for the range of numbers that you want. There is another stack overflow answer on getting it to work with a lower bounds as well, for a range of numbers from a min to a max.
Click here: Math.random() explained
My Math.random() method always return with 1
Well, this isn't true- in that case it always returns 0, which is used as num but what happens next:
b[x]=a[num];
you call a[0] three times as b[0], b[1] and b[2] and since you hardcoded
a[0]=1;
you'll get only that value.
In given example you can try
num=(int)(Math.random()*3);
as it simply generates random int from 0 to 2 or even use
num=(int)(Math.random()*a.length);
I'm not a Java programmer but I have some idea of it.
Math.random() will produce random numbers between 0 and 1. Casting to int means you want either 1 or 2.
Since you are getting only 1, Math.random() just happens to be producing numbers between 0.5 and 1, that's all.
I also know that if you run the program again and again, it will produce the same set of pseudorandom values (except maybe you recompile).
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
I want to generate a random number of 14 positive digits only and I use the below function for it:
public void random()
{
Random number = new Random();
long l = number.nextLong();
number.setSeed(System.currentTimeMillis());
long num = Math.abs(number.nextInt())%999 + (l/100000); // problematic line
mTextBox.setString("" + num);
}
I very new to to JavaMe, I have made above function myself but I believe it is not working as expected. It also generates -ve numbers. Also sometimes one or two digits are missing in generated number resulting in 12 or 13 numbers not 14.
Any suggestions or improvement to the code will be highly appreciated.
If you want 14 digits, then you should use 14 calls to number.nextInt(10) - something like this:
public static String randomDigits(Random random, int length)
{
char[] digits = new char[length];
// Make sure the leading digit isn't 0.
digits[0] = (char)('1' + random.nextInt(9);
for (int i = 1; i < length; i++)
{
digits[i] = (char)('0' + random.nextInt(10));
}
return new String(digits);
}
Note that I've made the instance of Random something you pass in, rather than created by the method - this makes it easier to use one instance and avoid duplicate seeding. It's also more general purpose, as it separates the "use the string in the UI" aspect from the "generate a random string of digits".
I don't know whether Random.nextInt(int) is supported on J2ME - let me know if it's not. Using Math.abs(number.nextInt())%999 is a bad idea in terms of random distributions.
I didn't understand what you really want, the code suggests that you want a 3 digit number (%999).
Otherwise you can create a 14 digit number between 1000000000000000 and 9999999999999999 by
long num = 1000000000000000L + (long)(number.nextDouble() * 8999999999999999.0);
note (1 / 100000) is 0 (zero) since it is done by integer division, use (1.0 / 100000.0) for double division
long num = 10000000000000L+(long)(random.nextDouble()*90000000000000.0);
EDIT:
mTextBox.setString(MessageFormat.format("{0,number,00000000000000}",
new Object[] {new Long(num)}));
You are getting negative numbers because Random.nextInt() returns any 32-bit integer, and half of them are negative. If you want to get only positive numbers, you should use the expression Random.nextInt() & 0x7fffffff or simply Random.nextInt(10) for a digit.