My question is :
How do I make the program print the number of digits before the decimal point and how many comes after a number.
public class Strings {
public static void main(String args[])
{
double number = 17.0/3;
DecimalFormat number_format = new DecimalFormat("#.###");
System.out.println(number);
String formatted_string = number_format.format(number);
System.out.println(formatted_string);
}
}
I need the number of integers before decimal point
I need to get result of 1 and 3.
Number of digits before the decimal point - DecimalFormat#setMaximumIntegerDigits It does the job -
double number = (double)17/3;
java.text.DecimalFormat number_format = new java.text.DecimalFormat("#.###");
number_format.setMaximumIntegerDigits(0);
System.out.println(number);
String formatted_string = number_format.format(number);
System.out.println(formatted_string);
Result :
5.666666666666667
.667
or a more simpler way
double d = 17.0/3;
System.out.format("%1.2f", d);
just try this
double d = 15.0/4; // Assuming a number
String ds = String.valueOf(d); // converting it into string (it will be 3.75)
String arr[] = ds.split("\\D"); // splitting by non number charecter (in our case its dot)
// So array containts ["3", "75"] strings
System.out.println("Before Decimal point: "+ arr[0].length()); // length gives number of digits
System.out.println("After Decimal point: "+ arr[1].length());
The easiest way to do this would be to convert the number to a string and then to split the string based on the '.' separator. Then split the first array element with "". The length of this array would give you your answer.
// number = some_number.some_more_numbers;
String value = number + ""; // convert to string
String[] parts = value.split(".");
String[] numbers = parts[0].split("");
int length = numbers.length; // Gives number of individual numbers before decimal point
I hope this helps.
Related
I don't know how to explain this well, but for example I have a number:
0.00000548347554 and want to make 0.000005483 from it, or
0.0683453248 to 0.06843, etc.
This assumes your number is a string:
String tmp = "0.0683453248";
String[] tmpA = tmp.split("");
ArrayList<String> res = new ArrayList<>();
for(int i = 0; i < tmpA.length; i++){
res.add(tmpA[i]);
if(!tmpA[i].equals(".") && Integer.parseInt(tmpA[i]) > 0){
res.add(tmpA[i + 1]);
res.add(tmpA[i + 2]);
res.add(tmpA[i + 3]);
break;
}
}
String result = String.join("",res);
Using the solution from this answer, you can convert the given number into a string and then use the regex replacement to get the required string out of it.
Demo:
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(doubleToString(0.00000548347554));
System.out.println(doubleToString(0.0683453248));
}
static String doubleToString(double n) {
DecimalFormat df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
df.setMaximumFractionDigits(340);
return df.format(n).replaceAll("(\\d*\\.0*[1-9]{4})\\d*", "$1");
}
}
Output:
0.000005483
0.06834
ONLINE DEMO
Explanation of the regex:
(: Start of capturing group#1
\\d*\\.: Digit(s) followed by .
0*: Any number of zeros
[1-9]{4}: Non-zero four digits
): End of capturing group#1
\d* : Any digit any number of times
For small numbers BigDecimal can be used:
BigDecimal significant(double number, int count) {
if (count < 1)
throw new IllegalArgumentException("invalid count: " + count);
BigDecimal big = BigDecimal.valueOf(number);
if (big.precision() <= count) {
return big;
} else {
return big.setScale(big.scale()-big.precision()+count, RoundingMode.HALF_EVEN);
}
}
precision() returns the number of significant digits;
the method changes the scale so only the desired number of digits is present.
The if is used to avoid more zeros than the input if this has less than count digits.
Use doubleValue() to convert the result to double if needed (may suffer from rounding error).
To get a string, use toPlainString(), which will transform the result to string without using the exponential notation.
Rounding mode can also be changed if desired.
Note: it can also be used with larger numbers, it basically will replace digits by zero like in significant(12345,2) -> 12000 (or 1.2E+4)
I need help with an assignment. There are many similar questions on here, but those answers are not working for me so I don't know what I'm doing wrong.
The assignment is "The program prompts the user for five to ten numbers, all on one line, and separated by spaces. Then the program calculates the average of those numbers, and displays the numbers and their average to the user."
We need to call to different methods to do this. The part that's giving me problems is converting the String to doubles and finding the average. We also need to validate that there are between 5-10 numbers in the String (I can validate it once I get it to count properly). I've tried a few things, including answers to similar questions on here (shown in code below), but the only output I get is 0.0.
Here is my code:
public static void main(String[] args) {
String getNumbers = "";
double calcAverage = 0;
getNumbers();
calcAverage(getNumbers);
System.out.println(calcAverage);
}
public static String getNumbers() {
Scanner scnr = new Scanner(System.in);
System.out.println("Please enter 5 to 10 numbers separated by spaces: ");
String getNumbers = scnr.next();
return getNumbers;
}
public static double calcAverage(String userNumbers){
double calcAverage = 0.0;
double i = 0;
double count = 0.0;
Scanner str = new Scanner(userNumbers);
while (str.hasNextDouble()){
count++;
i = i + str.nextDouble();
}
System.out.println("count=" + count); //test to check it is counting properly
calcAverage = i/count;
return calcAverage;
}
Thank you so much for any help!
It seems you have an error in your main method and need to set the getNumbers equal to the getNumbers method and the same with the calcaverage double with the calcaverage method.
public static void main(String[] args) {
String getNumbers = "";
double calcAverage = 0;
getNumbers();
calcAverage(getNumbers);
System.out.println(calcAverage);
}
should be
public static void main(String[] args) {
String getNumbers = "";
double calcAverage = 0;
getNumbers =getNumbers();
calcAverage =calcAverage(getNumbers);
System.out.println(calcAverage);
}
You can use streams to make it more readable and avoid and external iterations
import static java.util.Arrays.stream;
import java.util.OptionalDouble;
class Scratch {
public static void main(String[] args) {
OptionalDouble optAvg = calcAverage("2 5 6 7 8 9 0 1");
if (optAvg.isPresent()) {
System.out.println("optAvg.getAsDouble() = " + optAvg.getAsDouble());
}
}
public static OptionalDouble calcAverage(String userNumbers) {
String[] inputArr = userNumbers.split(" ");
int count = inputArr.length;
System.out.println("count = " + count);
if (count < 5 || count > 10) {
throw new IllegalArgumentException("Or do some other this here!");
}
return stream(inputArr)
.mapToDouble(
Double::parseDouble) // throws a NumberFormatException if it can't convert to Double
.average();
}
}
Or even simpler
import static java.util.Arrays.stream;
import java.util.DoubleSummaryStatistics;
class Scratch {
public static void main(String[] args) {
DoubleSummaryStatistics doubleSummaryStatistics = calcAverage("2 5 6 7 8 9 0 1");
System.out.println("count = " + doubleSummaryStatistics.getCount());
System.out.println("average = " + doubleSummaryStatistics.getAverage());
}
public static DoubleSummaryStatistics calcAverage(String userNumbers) {
return stream(userNumbers.split(" "))
.mapToDouble(Double::parseDouble)
.summaryStatistics();
}
}
Here you go:
public static void main(String[] args) {
String numberString = getNumbers();
double averageNum = calcAverage(numberString);
System.out.println(averageNum);
}
public static String getNumbers() {
Scanner scnr = new Scanner(System.in);
System.out.println("Please enter 5 to 10 numbers separated by spaces: ");
String getNumbers = scnr.nextLine();
return getNumbers;
}
public static double calcAverage(String userNumbers){
double calcAverage = 0.0;
double i = 0;
double count = 0.0;
Scanner str = new Scanner(userNumbers);
while (str.hasNextDouble()){
count++;
i = i + str.nextDouble();
}
System.out.println("count=" + count); //test to check it is counting properly
calcAverage = i/count;
return calcAverage;
}
A few changes, but you had it right for the most part. Going from the top of the file:
Removed getNumbers and calcAverage
Added numberString and averageNum (when you call functions with return, you need to store the value that it returns into a variable)
changed line:
String getNumbers = scnr.next();
to:
String getNumbers = scnr.nextLine();
Let me know if you have any questions.
Here is one way to do it with supplied values validation :
public static double calcAverage(String userNumbers) {
double calcAverage = 0.0;
double i = 0;
int count = 0;
Scanner str = new Scanner(userNumbers.trim().replaceAll("\\s+", " "));
while (str.hasNext()) {
String val = str.next();
// Is the supplied numerical value valid?
if (!val.matches("-?\\d+(\\.\\d+)?")) {
//No...
System.out.println("Supplied value of " + val +
" is ignored since it is not a valid numerical value!");
continue;
}
count++; // count now that we know the value is indeed valid.
i += Double.parseDouble(val);
}
System.out.println("count=" + count); //test to check it is counting properly
calcAverage = i / count;
return calcAverage;
}
Since you are processing a supplied whitespace delimited string of hopefully numerical values you can merely utilize the the Scanner#hasNext() method in conjunction with the Scanner#next() method.
Preparing the Scanner object:
Scanner str = new Scanner(userNumbers.trim().replaceAll("\\s+", " "));
Here we take the string contained within the supplied userNumbers string variable and trim off any possible leading and trailing white-spaces, we don't want these if there are any. We also replace any portion of the supplied string that may contain more than a single whitespace with just a single whitespace. We want to enforce this format before we proceed so as to help with eliminating any possible type of conflict later on in method code. You can't always rely on the User to provide everything perfectly all the time so if you can help then it's worth it.
Retrieving each supplied value from the supplied String:
while (str.hasNext()) {
String val = str.next();
// ... other code ...
}
The hasNext() method will allow the loop to continue for as long as there is another whitespace delimited string token to process. In this case we're hoping that each token will be a string representation of a numerical value.
Because the hasNext() method has let us get this far into the loop we know there is another String token available. The str.next() call retrieves that available token and in this case, is placing that string token into the string variable named val. This is done upon each iteration of the while loop until there are no more tokens remaining to process.
Validating a retrieved string token:
if (!val.matches("-?\\d+(\\.\\d+)?")) { ... }
Validation of each string token is done here utilizing the String#matches() method along with a specific Regular Expression (regex) of "-?\\d+(\\.\\d+)?". When passed in the matches() method, this regex checks to see if the string it is played against is indeed a string representation of a signed or unsigned integer or floating point numerical value:
-? Optional. Value is prefixed with '-'.
\\d+ One or more digits.
(\\.\\d+)? Optional. Value is post-fixed with a decimal point
and one or more digits.
In this case we're checking to see if the token is invalid and if it is we supply a message to the console window indicating as such and the fact that this token value will be ignored. We ignore it by using the continue keyword which forces the while loop into it's next iteration and bypassing the remaining code within the loop.
Converting a String numerical value to a Double data type:
count++; // count now that we know the value is indeed valid.
i+= Double.parseDouble(val);
We do the count after knowing the value provided is indeed valid. i was previously declared as a double type and sums the token numerical value after it is converted to double with the Double.parseDouble() method. Using i += is the very same as i = i +.
Another shorter way:
public static double calcAverage(String userNumbers) {
double calcAverage = 0.0;
double i = 0;
int count = 0;
Scanner str = new Scanner(userNumbers.trim().replaceAll("\\s+", " "));
while (str.hasNextDouble()) {
double val = str.nextDouble();
count++;
i+= val;
}
System.out.println("count=" + count); //test to check it is counting properly
calcAverage = i / count;
return calcAverage;
}
Hello StackOverflow community! I'm student trying to solve this problem....
The main issue I am having with it is that I dont know the best way to find characters that are valid integers in Strings.
Note: I am only 1 month into learning Java, and I spent most of last year learning python. So compiler languages are new to me.
Write a program that reads in a product code and outputs whether it is valid or not based on some simple rules.
The rules:
1st part can contain only capital letters and 6 digits. 2nd part is alldigits and = the product of the first 6 digits taken in groups of two from the left.
eg: AX6BYU56UX6CV6BNT7NM 287430
is valid because 65*66*67 = 287430
This is what I have so far
import java.util.*; //import java utilities
public class Basic5{ //declares my class
public static void main(String[]args){
Scanner kb=new Scanner(System.in);//creates Scanner for user input
String userentry=kb.nextLine(); //Takes users input as a string
String result="Valid"; //Variable for if the code is Valid
int DoubleCounter=0; //Counter for number of ints
double newdouble;
List<Double> NumberList = new ArrayList<Double>(); //Creates Array List for tracking Doubles
for(int i=0;i<userentry.length();i++){ //checks length of Users input
if(Character.isLowerCase(userentry.codePointAt(i))){ //checks if its a Lowercase letter
result="Fail"; //Changes result variable
if(Integer.parseInt(userentry,i)){ //checks if character from input is a valid integer
DoubleCounter+=1; //Adds to DoubleCounter
newdouble=userentry.charAt(i); //Isolates character
NumberList.add(newdouble); //Adds it to List of doubles
}
}
}
}
}
You can use following methods to check whether the input is a char or digit :
Character.isDigit('A');
Character.isLetter('A');
Here's one way to do it:
#Test
public void testExample() {
assertTrue(isValid("AX6BYU56UX6CV6BNT7NM 287430"));
assertFalse(isValid("AX6BYU56UX6CV6BNT7NM 287431"));
}
private boolean isValid(String s) {
String[] parts = s.split(" ");
int[] ints = extractIntegers(parts[0]);
int target = Integer.parseInt(parts[1]);
return product(ints) == target;
}
private int[] extractIntegers(String s) {
String digits = s.replaceAll("\\D+", "");
int[] ints = new int[digits.length() / 2];
for (int i = 0; i < digits.length(); i += 2) {
ints[i / 2] = Integer.parseInt(digits.substring(i, i + 2));
}
return ints;
}
private int product(int[] ints) {
int result = 1;
for (int num : ints) {
result *= num;
}
return result;
}
It assumes that there are non-zero even number of digits in the first part of the string. If you need to handle other cases, it should be easy to do, based on this.
String str = "AX6BYU56UX6CV6BNT7NM 287430";
str = str.replaceAll("[^0-9]+", "");
I'm trying to get the last two characters in a string for inches and the first two characters for feet. Is there something I'm not seeing because I've tried a lot of things.
The heights are supposed to have a space between two sets of numbers something like 5 10 or 12 02 so that's why I'm trying to get certain characters. It's so I can move them into another string to add them together because I'm suppose to add two peoples heights together and this is what I got so far...
import javax.swing.JOptionPane;
public class TestProgramming
{ //begin class
public static void main(String[] args)
{ // begin main
// ***** variables *****
int h1;
int h2;
String height1 = "0";
String height2 = "0";
String feet1;
String feet2;
String inches1;
String inches2;
String FinalFoot = "0";
String FinalInch = "12";
// ***** input box 1 *****
height1 = JOptionPane.showInputDialog (null, "Please enter the height of the first person in inches.");
// ***** input box 2 *****
height2 = JOptionPane.showInputDialog (null, "Please enter the height of the second person in inches.");
// ***** parse *****
h1 = Integer.parseInt(height1);
h2 = Integer.parseInt(height2);
// ***** integer to string *****
Integer.toString(h1);
Integer.toString(h2);
// ***** taking the feet and inches from the two heights *****
feet1 = h1.substr(0, 1); // subtract the last 2 numbers
inches1 = h1.substr(2, 4); // subtract the first 2 numbers
feet2 = h2.substr(0, 1); // subtract the last 2 numbers
inches2 = h2.substr(2, 4); // subtract the first 2 numbers
As you can see, I'm having problems where it says "taking the feet and inches from the two heights".
Let's take a little closer look at the code...
int h1;
int h2;
String height1 = "0";
String height2 = "0";
//...
// This is good...
height1 = JOptionPane.showInputDialog (null, "Please enter the height of the first person in inches.");
height2 = JOptionPane.showInputDialog (null, "Please enter the height of the second person in inches.");
// Ahh, here is a problem...
// If the String values contain any thing that is not a numerical character,
// these will throw a NumberFormatException, meaning anything that follows won't
// be processed...
h1 = Integer.parseInt(height1);
h2 = Integer.parseInt(height2);
// This does nothing. Integer.toString will RETURN a String representation
// of the int's you pass it, but you're not assigning them to anything...
Integer.toString(h1);
Integer.toString(h2);
// Last time I checked, String don't have a method called `substr`
feet1 = h1.substr(0, 1);
Once you have the String input from the user, you can use String#split to split the input on the spaces, for example...
height1 = ...
String[] heightsOf1 = height1.split(" ");
You would then need to convert each element into an int...
int[] personOneHeights = new int[2];
personOneHeights[0] = Integer.parseInt(heightsOf1[0]);
personOneHeights[1] = Integer.parseInt(heightsOf1[1]);
Now, you really should add some sanity checking here, you can use String#contains to determine if the original String contains a space character or not and keep asking the user for input if it doesn't (for example). You should also check the results of the split to determine if it has at least 2 elements in the array.
If you can't use arrays, you shouldn't rely on magic numbers, but try and use the information you have at hand, for example...
String part1 = height1.substring(0, height1.indexOf(" "));
String part2 = height1.substring(height1.lastIndexOf(" ") + 1);
Try this: (Note that I hardcoded the inputs for easier testing in a console app)
public static void main(String []args){
// removed the early declarations here. This is C-style, old, unnecessary and makes
// code harder to read
// ***** input box 1 ***** HARCODED - replace with UI call
String height1 = "6 10";
// ***** input box 2 ***** HARCODED - replace with UI call
String height2 = "3 10";
// ***** parse feet and inches from each input *****
String feet1 = height1.substring(0, 1); // get the first digit
String inches1 = height1.substring(2, 4); // get the last 2 digits
String feet2 = height2.substring(0, 1); // get the first digit
String inches2 = height2.substring(2, 4); // get the last 2 digits
// convert parsed string data to their integer counterparts
int f1 = Integer.parseInt(feet1);
int i1 = Integer.parseInt(inches1);
int f2 = Integer.parseInt(feet2);
int i2 = Integer.parseInt(inches2);
// calculate total feet
int totalFeet = f1 + f2 + (i1 + i2) / 12;
// calculate total inches (using modulus operator)
int totalInches = (i1 + i2) % 12;
// and do the output... assuming this is what you want...
System.out.println(totalFeet + " " + totalInches);
}
Also, it's substring not subtract or substr.
These two lines:
Integer.toString(h1);
Integer.toString(h2);
don't do what you think they do.
I think you're expecting that after they run, h1 and h2 are now Strings. But that isn't what happens. Variables can't change type. h1 and h2 remain ints.
Rather than having a side effect, Integer.toString returns a result. Currently you are simply discarding tht result. You need to do something with the result, such as store it in a new variable. Maybe something like this:
String h1AsString = Integer.toString(h1);
String h2AsString = Integer.toString(h2);
You are trying to use substr() on an int. Also, when you call Integer.toString(h1); that does not set the variable to a string. To do so, it would have to be:
feet1 = Integer.toString(h1)
feet1 = feet1.substr(0, 1);
Hope this helps
I'd split the string by spaces first:
How to split a String by space
String[] split1 = height1.split("\\s+");
feet1 = Integer.parseInt( split1[0] );
inches1 = Integer.parseInt( split1[1] );
String[] split2 = height2.split("\\s+");
feet2 = Integer.parseInt( split2[0] );
inches2 = Integer.parseInt( split2[1] );
How can i find decimal(dot) in a given number in java.
I am getting input from user, he may give integer or float value.
I need to find he entered integer or float, is it possible?
if yes could u tell me please.
--
Thanks
Assuming you got the digits of the number in a String, it would be
String number = ...;
if (number.indexOf('.') > -1)
...
you can try with yourNumberString.indexOf("."). If it returns a number greater than -1 there's a dot in the input.
Anticipating your need, I would suggest that you use java.util.Scanner for number parsing, and use its hasNextXXX methods instead of dealing with parseInt etc and deal with NumberFormatException.
import java.util.*;
String[] inputs = {
"1",
"100000000000000",
"123.45",
"blah",
" "
};
for (String input : inputs) {
Scanner sc = new Scanner(input);
if (sc.hasNextInt()) {
int i = sc.nextInt();
System.out.println("(int) " + i);
} else if (sc.hasNextLong()) {
long ll = sc.nextLong();
System.out.println("(long) " + ll);
} else if (sc.hasNextDouble()) {
double d = sc.nextDouble();
System.out.println("(double) " + d);
} else if (sc.hasNext()) {
System.out.println("(string) " + sc.next());
}
}
This prints:
(int) 1
(long) 100000000000000
(double) 123.45
(string) blah
You do not need to explicitly search for the location of the decimal point as some answers suggest. Simply parse the String into a double and then check whether that double represents an integer value. This has the advantage of coping with scientific notation for doubles; e.g. "1E-10", as well as failing to parse badly formatted input; e.g. "12.34.56" (whereas searching for a '.' character would not detect this).
String s = ...
Double d = new Double(s);
int i = d.intValue();
if (i != d) {
System.err.println("User entered a real number.");
} else {
System.err.println("User entered an integer.");
}
Some other ways to do this:
given
String input = ...
the following evaluates to true if it's a decimal number
input.split(".").length == 2
or
input.matches(".+\\..+")
or
!input.matches("\\d+")