Counting decimal numbers in Java - java

I have an issue where i am trying to count the amount of numbers with a decimal point however it is just counting whenever there is an integer even if it is a whole one.
Scanner cd = new Scanner(name); // count double
Scanner cn = new Scanner(name).useDelimiter("[^0-9]+"); // count int
while(cn.hasNextInt()) {
cn.nextInt();
numberOfInts++;
}
while(cd.hasNextDouble()) {
cd.nextDouble();
numberOfDecimals++;
}
so yeah the number of decimals justs counts whenever a integer is scanned, even if it is a whole number, i want it too just count numbers with a decimal point.

Related

Generate random numbers that contain same digits as number n

I have to make an array that contains random numbers in certain range, but each number has to contains same digits as number n (user input).Also numbers can be duplicated. For example n=11452 so the generated number can be 221545. Every next number has to contain 1,4,5,2(in this case where n is 11452) I just need an idea for solving this.
1) Determine the number of distinct digits in the user input (in your example 4: 1,2,4,5)
2) Create a random number of at least this number of digits (in your example: at least 1000)
3) Insert the requested digits in random positions of the found number. Make sure these positions are distinct. I.e., make sure no requested digit is overwritten by another one.
Does this make sense?
1) Parse the user input number as String and add all digits to a Set.
2) Convert your set to an array to have access to random index of array.
3) Access the parsed digits in the converted array via random index.
Perhaps, this is not a perfect implementation but the following method will generate a random digit which follows your requirements as i understood. The length of the generated random digit is so long as your user input number.
Just modify it to create an array with generated random numbers as your requirements.
public int generate(String number) throws NumberFormatException {
// 1) parse number and add the digits to a set
HashSet<Integer> digits = new HashSet<>();
for (String digitStr : number.split("")) {
int digit = Integer.parseInt(digitStr);
digits.add(digit);
}
// 2) convert the set to array to access via random index
Integer[] digitArray = new Integer[number.length()];
digits.toArray(digitArray);
String generated = "";
Random random = new Random();
for (int i=0; i < number.length(); i++) {
// 3) grap a random digit from array and append it to your result
int randomIndex = Math.abs(random.nextInt()) % number.length();
generated += digitArray[randomIndex];
}
return Integer.parseInt(generated);
}

Reading long binary numbers in java

I am trying to write a program which converts binary numbers into decimal, however as soon as I have a binary number which is bigger than 10 digits I get a java.lang.numberformatexception error. I was wondering how I should rewrite my code in order to handle binary numbers:
try{
//will throw an exception if the user's input contains a non-Integer
int inputNumber = Integer.parseInt(returnEnterNumber());
//when our user wants to convert from binary to decimal
if(binaryToDecimal.isSelected()){
//checks if number is binary
int checkNumber = inputNumber;
while (checkNumber != 0) {
if (checkNumber % 10 > 1) {
throw new InvalidBinaryException();
}
checkNumber = checkNumber / 10;
}
//converts from binary and outputs result
int n = Integer.parseInt(returnEnterNumber(), 2);
displayConvertedNumber(Integer.toString(n));
}
}
catch(Exception e) {
displayConvertedNumber("WRONG INPUT! - TRY again");
}
Edit: I understand why the code fails, seeing as how it takes the number as a decimal and overflows. I am not sure how to rewrite the code to take the input as a binary straight away.
That's not a valid way to check a binary number. You're converting to an int in base 10, then checking that each of the digits in base 10 is zero or one. The conversion itself will fail on long enough input strings, and if it doesn't the checking will fail as well.
You shouldn't be converting it all all, you should be checking the input string itself.
EDIT Actually you don't have to do anything. Integer.parseInt() will check it for you and throw NumberFormatException if the string isn't a number in the specified radix.
You are parsing your binary digit string as a decimal integer first. If it has more than 10 significant digits then its decimal interpretation is too big to fit in an int, so the decimal conversion fails.
When you are going to parse the digit string as a binary number, simply avoid first parsing it as a decimal one. For instance, most of what you posted could be reduced to this:
int inputNumber = Integer.parseInt(returnEnterNumber(),
binaryToDecimal.isSelected() ? 2 : 10);
Take a look at Integers MAX values:
public class MainClass {
public static void main(String[] arg) {
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
}
}
the output will be:
2147483647
-2147483648
This means that if you have more than 10 digits, you have exceeded the max number for the Integer data type.
Try Using BigInteger on your binary value or consider returning it as String
Here is one line of code that will accomplish what you are looking for
System.out.println(new BigInteger("10101010101010111101010101001101010101010101001010101010101001011101010101010101",2).toString());

Add two Integers up to 50 digits

This is the actual question:
Write an interactive program that adds two integers of up to 50 digits each
(Represents integer as an array of digits).
This is a homework question and the language to be used is Java. I got this far but I don't think it is even close.
1. It is not taking input more than 20 digits but have to work with 50 digits.
2. The method 'integerToDigits' is producing two arrays but i am unable to sort out how to use them and add them in the main method.
Help please.
package One;
import java.util.Scanner;
public class AddInt {
public static void main(String[] args) {
Long x,y;
Long a[] = new Long[50];
Long b[] = new Long[50];
System.out.println("Please enter two numbers which have no more than 50 digits: ");
Scanner s = new Scanner(System.in);
x = s.nextLong();
y = s.nextLong();
System.out.println(x+ "and "+y);
integerToDigits(x);
integerToDigits(y);
}
public static Long[] integerToDigits(Long n){
Long digits[] = new Long[50];
Long temp = n;
for(int i = 0; i < 50; i++){
digits[49-i] = temp % 10;
temp /= 10;
}
return digits;
}
}
It is not taking input more than 20 digits but have to work with 50 digits.
This is because you're using x = s.nextLong() which is trying to convert the input to a long. The maximum long value is 9223372036854775807 which is nowhere near 50 digits. You'll need to get the input as a String and then covert that to your int[]
The method 'integerToDigits' is producing two arrays, but I am unable to sort out how to use them and add them in the main method.
In terms of adding up the arrays of digits, you can use the same process we learn very early on in school.
Add the units, then carry over any tens.
Add the tens and carry over any hundreds.
Add the hundreds and carry over any thousands.
...
This process can be iterated adding each order of magnitude with the carry over from the previous one.
Hopefully those tips give you a way to solve your problem.
If you do want a solution, I've produced one here that seems to work as you require. (Although not in ideone apparently)
If "Represents integer as an array of digits" is a suggestion and not a requirement a solution using BigInteger would look something like:
// read numbers from input
// store first value as String "firstNumber"
// store second value as String "secondNumber"
BigInteger a = new BigInteger(firstNumber);
BigInteger b = new BigInteger(secondNumber);
BigInteger result = a.add(b);
System.out.println("Result is " + result.toString());
If "Represents integer as an array of digits" is a requirement, well, then it's a silly assignment :) No one would store an integer like that. Worst case, I'd store it as a String if BigInteger was not allowed.

Finding 1's complement

I am trying to make a program to calculate 1's complement after entering a binary number.
This is what I have to far:
import java.util.Scanner;
public class BitWiseComplement {
public static void main(String[] args) {
Scanner keysIn = new Scanner(System.in);
System.out.println("Please enter your number: ");
long originalNum = keysIn.nextLong();
System.out.println(~originalNum);
}
}
However, when I enter 0111011, I get -111012. I thought the ~ operator was supposed to invert the number so that all 0s are 1s and all 1s are 0s.
Any help?
You presumably want to work in binary, so try:
Scanner keysIn = new Scanner(System.in);
System.out.print("Please enter your number: ");
long originalNum = keysIn.nextLong(2); // specify radix of 2
System.out.println(Long.toBinaryString(~originalNum)); // print binary string
keysIn.close();
Please enter your number: 0111011
1111111111111111111111111111111111111111111111111111111111000100
As you can see, all bits are flipped. Bear in mind that there are leading 0s in front of the binary number you entered.
The ~ operator does what you think, but keep in mind that there are no unsigned types in Java, so when you enter a positive number (i.e., the high bit is a 0), applying ~ to it will make it negative (by turning the high bit on).
If you were to print the number out in hex (or binary, as other answers have suggested), you should see the answer you expect.
count the number of bits in num.
make a mask of 1s of the same length.
xor with the number to get the complement.
eg. 9^15=6
public static int solution(int num) {
int bits = Integer.toBinaryString(num).length();
int maxBound = (int)( Math.pow(2, bits)-1);
return num ^ maxBound;
}

Greatest Product of Five Consecutive Digits

I am trying to parse a 50 character String object to an integer. I have been trying to scan in a data file containing 100 lines (each with a 50 digit number) and compute the sum of the numbers.
Every time I try to parse the String as an integer the call throws a NumberFormatException.
Here's what I have so far..
{
long totalSum = 0;
ArrayList<Long> list = new ArrayList<Long>();
// Create a new JFileChooser object.
JFileChooser fileChooser = new JFileChooser(
"C:\\Users\\Jon\\workspace\\Project Euler\\src");
// Create an "Open File" Dialog box for
// the user.
fileChooser.showOpenDialog(null);
// Get the file the user selects.
File inputFile = fileChooser.getSelectedFile();
try
{
Scanner in = new Scanner (inputFile);
String nextString = "";
// If the scanner has another token to scan,
// continue with the loop.
while (in.hasNext())
{
// The next string is the next number of characters
// that are not seperated by white space.
nextString = in.next();
try {
ing nextNumber = Integer.parseInt(nextString);
list.add(nextNumber);
} catch (NumberFormatException e) {
System.out.println ("NumberFormatException: " + e.getMessage());
}
}
in.close();
I have tried "trimming" the String object before attempting to parse, but there wasn't anything to trim. There isn't any white space in the lines that I am scanning in.
Here are a few lines of what I am trying to scan in and compute the value of:
37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
I've check the API and searched quite thoroughly through the Stack. Anyone know how to get around this?
Your numbers are much too big to fit into an int, with a range of -2147483648 through 2147483647. They are also much too big to fit into a long, with a range of -9223372036854775808L through 9223372036854775807L. If it won't fit into the range of the datatype, then a NumberFormatException is thrown.
You may want to try parsing the numbers into a double:
double nextNumber = Double.parseDouble(nextString);
but that may lose a bit of precision. A Double has 53 bits of precision, good for about 16 digits. You'll lose precision with a double.
To retain precision, use BigInteger:
BigInteger nextNumber = new BigInteger(nextString);
A BigInteger is arbitrary precision and will not lose any precision. You can use basic arithmetic and comparisons directly between BigIntegers.

Categories

Resources