Check Protection Format - java

I'm trying to write an application that inputs a dollar amount to be printed on a check, I'm having trouble figuring out how to print out the number in a check protected with leading **** asterisks.
Here's the code I have so far
import java.text.DecimalFormat;
import java.util.Scanner;
import java.text.NumberFormat;
import java.util.Locale;
public class CheckProtection
{
private static double maxAmount = 1000;
public static void main (String args [])
{
//System.out.printf(checkFormatter.format(check));
//DecimalFormat checker = new DecimalFormat("******.**");
//System.out.println(checker);
boolean validEntry = false;
while (validEntry == false)
{
Scanner userEntry = new Scanner(System.in);
System.out.println("Enter The check amount under a $1000.00 and greater that 0.");
if (userEntry.hasNextDouble() == true)
{
double check = userEntry.nextDouble();
if (check > 0)
{
if(check < maxAmount)
{
validEntry = true;
NumberFormat checkFormatter = NumberFormat.getCurrencyInstance();
checkFormatter.format(check);
System.out.printf("%5s",+ check);
}
}
}
}
}

Edit: With the sample inputs and expected output given in the comment, my previous answer was not correct.
Given each of those inputs, this update should produce the expected output:
String value = "$" + String.format("%.2f", check);
System.out.println(value);
String check_fmt = ("*********" + value).substring(value.length());
System.out.println(check_fmt);
Note: borrowed ingenuity from this answer
old answer: Not sure if it could be done with printf(), but String.format works,
String result = String.format("%6.2f", check); // 6 spaces width, 2 spaces precision, 'f' converts the double
System.out.println(result.replace(" ", "*"));
Note: used 6 spaces width = 3 spaces for whole dollar + 2 spaces for cents + 1 space for decimal

Related

How to leave only 4 decimals after number bigger than 0?

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)

How do I convert a String into doubles to compute average in Java?

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;
}

I keep getting "Invalid constant error" on my program and I am not sure why?

This is my code that calculates ISBN 13th number but I seem to be having trouble. It keeps giving me an error on the return about invalid character constant and every time I change it, it gives an error on the method name I don't understand why.
import java.util.Scanner;
public class ISBN {
public static int VerifyISBN(String isbn) {
if(isbn.matches("[0-9]+") && isbn.length() > 12){
for(int i = 0; i < 12; i++){
char digit = isbn.charAt(i);
int sum = 0;
if (Character.isDigit(digit)){
int digitValue = digit - '0';
if(i % 2 == 0)
sum += digitValue;
else sum += 3 * digitValue;
}
else
return 'invalid'; (This is where I get the error)
}
}
}
public static void main(String[] args) {
final String TITLE = "ISBN-13 Identifier";
System.out.println("Welcome to the " + TITLE);
Scanner input = new Scanner(System.in);
String response;
do {
System.out.print("Enter the first 12 digits of an ISBN-13: ");
String isbn = input.nextLine().trim();
//String isbnVerifier = generateISBN(isbn);
//if(isbn.equals("INVALID"));
System.out.println("The 13th number of" + isbn + " is " +
((verifyISBN(isbn))));
System.out.print("Do this again? [nY]");
response = input.nextLine().toUpperCase();
} while (!response.equals("N"));
input.close();
System.out.println("Thank you for using the " + TITLE);
}
}
Two problems:
The literal 'invalid' is incorrect Java syntax. A string is delimited with double quotes. Single quotes are used to delimit single-character literals, such as 'a' but cannot be used for strings of characters.
The method is declared to return an integer, so you cannot return a String.
If your intent is to return a sentinel value indicating that the input was invalid, you should probably use something like -1, which can then be interpreted by the caller as the error condition.
Or, you could define the method to throw an exception.

Could someone please tell me what's wrong with my Java code? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I'm trying to make a USD <-> JPY converter. If the numbers seem off to you, trust me - I did the math. Also, I know the spacing's off, but it doesn't matter. Morph it in N++ if you need to.
import java.util.Scanner;
import java.lang.Math;
public class jpy_usd {
public static void main(String[] args) {
//Initializing variables and the scanner
boolean isSourceUSD;
double usd;
double usdMult = 0.00803568;
int jpy;
double jpyMult = 124.449;
Scanner scanner = new Scanner(System.in);
//Selecting an input currency and checking for valid input arguments
System.out.println("Choose your input currency. Type \'USD\' for U.S. Dollars or \'JPY\' for Japanese Yen.");
while(isSourceUSD != true && isSourceUSD != false) {
if(scanner.nextLine == "USD") {
isSourceUSD = true;
} else if(scanner.nextLine == "JPY") {
isSourceUSD = false;
} else {
System.out.println("Invalid argument. Please use \'USD\' for U.S. Dollars or \'JPY\' for Japanese Yen.");
}
}
//Asking for the input in the chosen currency and converting
if(isSourceUSD) {
System.out.println("Please enter the value to convert");
usd = scanner.nextDouble;
System.out.println(usd " in JPY is " (Math.round(usd * jpyMult)));
} else if(!isSourceUSD) {
System.out.println("Please enter the value to convert");
jpy = scanner.nextInt;
System.out.println(jpy " in USD is " (Math.round(jpy * usdMult)));
}
}
}
If you want me to add the error messages, I suppose I could. Without much explanation, there's 6 errors split evenly across these two lines:
System.out.println(usd " in JPY is " (Math.round(usd * jpyMult)));
System.out.println(jpy " in USD is " (Math.round(jpy * usdMult)));
There's two of each error - one per line - so the similarities in the lines have to be the same issues (duh). So, anybody got any clues?
P.S.: If there's anyhing wrong with the code other than that, please do mention it.
P.S. 2: I know I'm basically making this code public by putting every single character into this block of text, but please don't steal. I know someone's about to do it, but please don't.
~wundr
There are ideally many problems with your code, starting with the Naming conventions to method names, String comparison. Below is the minimal code changes required to make your code work:-
import java.util.Scanner;
import java.lang.Math;
public class jpy_usd {
public static void main(String[] args) {
//Initializing variables and the scanner
String isSourceUSD;
double usd;
double usdMult = 0.00803568;
int jpy;
double jpyMult = 124.449;
Scanner scanner = new Scanner(System.in);
//Selecting an input currency and checking for valid input arguments
System.out.println("Choose your input currency. Type \'USD\' for U.S. Dollars or \'JPY\' for Japanese Yen.");
if(scanner.nextLine() .equalsIgnoreCase( "USD")) {
isSourceUSD = "USD";
} else if(scanner.nextLine() .equalsIgnoreCase( "JPY")) {
isSourceUSD ="JPY" ;
} else {
isSourceUSD="NA";
System.out.println("Invalid argument. Please use \'USD\' for U.S. Dollars or \'JPY\' for Japanese Yen.");
}
//Asking for the input in the chosen currency and converting
if(isSourceUSD.equalsIgnoreCase("USD")) {
System.out.println("Please enter the value to convert");
usd = scanner.nextDouble();
System.out.println(usd +" in JPY is "+ (Math.round(usd * jpyMult)));
} else if(isSourceUSD.equalsIgnoreCase("JPY")) {
System.out.println("Please enter the value to convert");
jpy = scanner.nextInt();
System.out.println(jpy+ " in USD is " +(Math.round(jpy * usdMult)));
}
else{
System.out.println("Do nothing!!!");
}
scanner.close();
}
}

find decimal in a given number

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+")

Categories