Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm learning a Java and I have a problem in one of my project called "point of sale". When the program reads a barcode from the user, it starts to search for the proper product in products.txt. When it finds the product, next it should set the values to the created object. The problem occurs when I try to convert String to double. I spend almost 2 hours to solve it and I didn't succeed. I need your help.
So I have tried:
double dbl = Double.valueOf(parts[2]);
p.set_price(dbl);
double dbl = Double.parseDouble(parts[2]);
p.set_price(dbl);
double dbl = new Double(parts[2]);
p.set_price(dbl);
And also tried a combinations like this (but it doesn't work):
p.set_price(Double.valueOf(parts[2].ToString()));
There is only a method
public void newSale() {
Products p = new Products();
// Barcode
System.out.print("Barcode:");
p.set_barcode(scan.next());
// Find the product
try{
File file = new File("products.txt");
Scanner scan = new Scanner(file);
while(scan.hasNextLine()) {
String x = scan.next();
if(x.contains(p.get_barcode())) {
String[] parts = x.split(";");
p.set_barcode(parts[0]);
p.set_name(parts[1]);
try{
double dbl = Double.valueOf(parts[2]);
p.set_price(dbl);
}catch(NumberFormatException ex){
System.err.println("Error: " + ex.getMessage());
}
}
}
}catch(Exception e){
System.err.println("Error: " + e.getMessage());
}
System.out.print(p.get_name()+"\t"+p.get_price());
}
It will be good if anyone will help me to understand why conversion and assigning don't work.
Dot devides integer with fraction in Double. In products.txt, change commas to dots in prices. That should help :)
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 12 hours ago.
Improve this question
I am a beginner in Java and this issue arose when I was working on a HackerRank problem that I have solved but it still confuses me why it wouldn't work the first iteration of code I made to solve it. This code function is to separate a string and an integer into two columns with the integer being limited to three digits and string having 10 chr limit, covered by "========". Also, I intend the code only ends when the user has inputted "nothing" or white spaces.
However, the do while loop keeps going as its condition does not match the inputted variables created by the scanner, being white spaces. I had a clue that it might be when I used an integer scanner as it interfered with the string scanner, but I tried clearing the scanner by using nextLine(), and it wouldn't work with the loop. I tried using scanner.reset() and also declaring the integer first as a string and then converting it back to an integer but the loop keeps going. I tried simplifying it, and I found out that the loop ends when I use "word = scanner.nextLine();" but it wouldn't work with the loop. Hope you guys can educate me and possible ways to fix this issue.
package hackerRankTestCode;
import java.util.Scanner;
import java.lang.*;
import java.util.concurrent.atomic.DoubleAdder;
public class TestCode {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String word = "";
Integer number = 0;
String baruNumber = "";
System.out.println("================================");
do {
word = scanner.next();
number = scanner.nextInt();
String blank = new String(new char[15 - word.length()]).replace("\0", " ");
if(number<100 && number>=10){
baruNumber = "0"+number;
System.out.println(word+blank+baruNumber);
}
else if(number>=0 && number<10) {
baruNumber = "00"+number;
System.out.println(word+blank+baruNumber);
}
else if(number>=100) {
System.out.println(word+blank+number);
}
}
while(!word.isBlank() && number != 0);
scanner.close();
System.out.println("================================");
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
How would you go about adding the total number to all the integers inside an array element?
My code below is what I have and the issue is the multiple numbers are all displayed in different rows but I can't get them to add together because its all considered one integer.
This is what my output looks like.
462085
361250
351477
328955
But when I attempt to alter the numbers in any way I get something like this,
+2
462087
361252
351479
328957
When I really want to get just get the total sum of the numbers.
Desrired Output:
1503767
I attempted to use .parseInt() but that did not seem to make a difference.
import java.io.*;
import java.nio.charset.StandardCharsets;
public class babySort {
public static void main(String[] args) {
File inputFile = new File("src/babynames.txt");
try (BufferedReader br = new BufferedReader(new FileReader(inputFile, StandardCharsets.UTF_8))) {
String input;
String maleNames;
while ((input = br.readLine()) != null) {
// process the line
String[] inputSplit = input.split("\\s+");
// System.out.println(inputSplit[2]);
int maleBb = Integer.parseInt(inputSplit[2]);
System.out.println(maleBb);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
You want the total. Declare a variable to compute the total with before your loop. Add the values to the total. Print it after your loop. Like,
int total = 0;
while ((input = br.readLine()) != null) {
String[] inputSplit = input.split("\\s+");
// int maleBb = Integer.parseInt(inputSplit[2]); // what is a maleBb?
total += Integer.parseInt(inputSplit[2]);
}
System.out.println(total);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
"Sales Docket successfully saved and sent for approval. Please note your document number. JBHL/39/16-17"
i want only the number 39 in the string should be increased by +1 when we run the method
Use regular expression to find the number, then build new string:
private static String increment(String input) {
Matcher m = Pattern.compile("/(\\d+)/").matcher(input);
if (! m.find())
throw new IllegalArgumentException("Invalid document number: " + input);
int newNumber = Integer.parseInt(m.group(1)) + 1;
return input.substring(0, m.start(1)) + newNumber + input.substring(m.end(1));
}
Test
System.out.println(increment("JBHL/39/16-17"));
Output
JBHL/40/16-17
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have an assignment where I have to attach the letters "un" to any word that the user inputs (unless the inputted word already has "un" in front of it, in which case I just return the inputted word). I'm testing my method but I encountered one problem: my program keeps returning an error if I were to test for an empty input. Here is my code:
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter: ");
String input = keyboard.nextLine();
if(input.substring(0,2).equalsIgnoreCase("un"))
{
System.out.println(input);
}
else if(input.equals(""))
{
System.out.println("un");
}
else
{
System.out.println("un" + input);
}
So I wanted to ask how I can test for an empty input/blank string since, evidently, the "" quotations do not work.
There's nothing wrong with checking input.equals("") per-se. The problem is that you have another test beforehand that throws an exception if input is shorter than 2 characters.
There are several ways to solve this, but I'd just simplify things and use startsWith. An empty string doesn't really need a special case of its own - just slap un before it, and you'll get un:
if (input.toLowerCase().startsWith("un")) {
System.out.println(input);
} else {
System.out.println("un" + input);
}
You are having this problem because you are trying to get the substring of string that doesnt have the required length. Put the empty string check first.
if(input.equals("")||input.length==1)
{
System.out.println("un");
}
else if(input.substring(0,2).equalsIgnoreCase("un"))
{
System.out.println(input);
}
else
{
System.out.println("un" + input);
}
If this weren't homework, and the library could be used for other things ( using it in this single purpose may be overkill ), you could use StringUtils.PrependIfMissing().
It does exactly this and handles nulls as well.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I wrote a program that calculates Acceleration. This is how it looks:
http://prntscr.com/57yngo
when you press that button it show a dialog message that is a part of JOptionPane. The data you enter in fields are Strings I convert them to double by doing :
double name = Double.valueOf(String);
The problem is if you inserted a String value instead of a double value in the fields you and pressed the button that sends the acceleration total the program badly crash. I really need a solution to fix that!
If you said why did you set the inserted value as String I will answer
that this is the only way to do the
Textfieldname.gettext();
If you knew a way to get a double only from a text field please tell me it.
Try something like this:
public static void main(String[] args) {
String[] values = {"1.0", "2.0", "a"};
for (String value: values) {
System.out.println(getValue(value));
}
}
private static Double getValue(String valueString) {
Double result;
try {
result = Double.valueOf(valueString);
} catch (NumberFormatException e) {
result = 0.0;
}
return result;
}
You have to catch NumberFormatException to handle wrong input
Example:
try {
result = Double.valueOf(valueString);
} catch (NumberFormatException e) {
//show alert and clean field or something else
}
Check IF the String in the textfield can be parsed to Double before the conversion. If you expect simple String values like 3.01 or 150 then a simple regular expression would do:
import java.util.regex.Pattern;
// some stuff in your class
// and in your action listner
Pattern p = Pattern.compile("\\d+|\\d+\\.\\d+"); //digits or digits dot digits
String valueToTest = Textfieldname.gettext();
boolean canBoConverted = p.matcher(valueToTest).matches();
if (canBoConverted) {
double name = Double.valueOf(String);
// do something with name
} else {
// idicate a bad input value to the user
}
If you need a wider range o possible values than you can use the pattern from the Double class documentation
Also please remember that a programmer should always validate user input against whats acceptable.