Reading from the File - java

This program has 2 classes with a main method and is supposed to read from a file. My problem is that the line double listPrice = fileScan.nextDouble(); gives an error exception like this Exception in thread "main" java.util.InputMismatchException. The error is in this class:
Here is contents of the file:
Honda Accord
2004 16780.00 10.0
Chrysler SUV
2002 8600.00 0.0
Toyota Camry
2007 21799.99 3.0
Ford Escort
2006 12345.78 5.5
//note there is no space between each line
class Proj1P2CarAryListService
{
private ArrayList<Proj1CarData> carList = new ArrayList<Proj1CarData>();
public Proj1P2CarAryListService()
{
carList = new ArrayList<Proj1CarData>();
}
public void readStoreCarsData()
{
Scanner scan = new Scanner(System.in);
Scanner fileScan;
boolean validName = false;
double discountAmount;
double netPrice;
do
{
System.out.print("Enter file name: ");
String str1 = scan.nextLine();
try
{
fileScan = new Scanner(new File(str1));
validName = true;
while (fileScan.hasNext())
{
String name = fileScan.nextLine();
String modelYear = fileScan.next();
double listPrice = fileScan.nextDouble();
double percentDiscount = fileScan.nextDouble();
discountAmount = listPrice * percentDiscount/100.0;
netPrice = listPrice - discountAmount;
Proj1CarData proj1 = new Proj1CarData(name, modelYear, listPrice, percentDiscount, discountAmount, netPrice);
carList.add(proj1);
System.out.println(proj1.toString());
}// end while
}// end try
catch (FileNotFoundException fnfe)
{
System.out.println("Invalid File name; enter again");
}
} while (!validName);
}//readStoreCarsData

This exception is thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type(Double must be separated by . or , like said jlordo), or that the token is out of range for the expected type. Perhaps it is a file content problem.

The nextDouble() method of Scanner is locale-aware (see Documentation).
This means, if your locale is set to a country where '.' seperates a floating point number following would be a parsable double value: 123.456 while following number will give you a InputMismatchException 123,456. In Europe 123,456 would work, and 123.456 would throw an Exception. Hope it helps...

You might want to consider printing out each line. You might be getting more than you expect.

Related

How to make it so the user can replace a sentence they typed can be replaced in Java

So I am trying to make the program ask the user the following and get the following answer:
For example:
Type a 2nd Sentence Below:
This is a book (user inputs this)
Choose what string of characters do you want to replace:
book (user inputs this)
Choose what new string will be used in the replacement:
car (user inputs this)
The text after the replacement is: This is a car.
import java.util.*;
import java.util.Scanner;
public class StringManipulation {
public static void main(String[]args) {
/*This is where the user can type a second sentence*/
System.out.println("Type a 2nd Sentence Below:");
Scanner sd = new Scanner(System.in);
String typingtwo = sd.nextLine();
String sending;
/*Here the program will tell the user a message*/
System.out.println("This is your sentence in capital letters:");
sending = typingtwo.toUpperCase();
System.out.println(sending);
/*Here the program will tell the user another message*/
System.out.println("This is your sentence in lower letters:");
sending = typingtwo.toLowerCase();
System.out.println(sending);
System.out.print("Your Token Count:");
int FrequencyTwo = new StringTokenizer(sending, " ").countTokens();
System.out.println(FrequencyTwo);
String charactertwo = new String(typingtwo);
System.out.print("Your Character Length:");
System.out.println(charactertwo.length());
String repWords;
String newWord;
String nwords;
String twords;
System.out.println("Choose what string of characters do you want to
replace");
repWords = sd.next();
System.out.println("Choose what new string will be used in the replacement");
nwords = sc.next();
twords = typingtwo.replace(repWords,nwords);
System.out.printf("The text after the replacement is: %s \n",nwords);
}
}
I have tried everything but for some reason I keep getting the word that they chose at the end only. Pleas help!
try using Scanner.nextLine instead of Scanner.next
refer to the Java API documentation to understand the difference between the two
Here is another problem:
twords = typingtwo.replace(repWords,nwords);
System.out.printf("The text after the replacement is: %s \n",nwords);
You are printing nwords instead of twords.
Two errors i could see.
nwords = sc.next(); here it should give compilation error as scanner instance name is sd.
You are trying to print nwords at the end. it should be "twords".

Java number format exception.

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "P35.00"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at OrderSystems.OrderSystem.jButton3MouseClicked(OrderSystem.java:419)
at OrderSystems.OrderSystem.access$900(OrderSystem.java:14)
at OrderSystems.OrderSystem$10.mouseClicked(OrderSystem.java:241)
I keep getting this error after i clicked the jButton3. heres my codes.
private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {
double sub = Double.parseDouble(sub_field.getText());
double vat = Double.parseDouble(vat_field.getText());
double allTotal = (sub + vat);
String iTotal = String.format("%.2f", allTotal);
total_field.setText(iTotal);
}
This is the code for the sub_field and vat_field
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
double ham = Double.parseDouble(ham_field.getText());
double burger = Double.parseDouble(burger_field.getText());
double bacon = Double.parseDouble(bacon_field.getText());
double bac = bacon * 5;
double harm = ham * 10;
double burg = burger *20;
double sub = harm + burg + bac;
String sub_com = String.format("P%.2f", sub);
sub_field.setText(sub_com);
}
java.lang.NumberFormatException is pretty clear: "P35.00" is not a number.
This Exception is thrown when the paramether for the parsing Double.parseDouble is not what it is excpecting.
Try out removing the P from 35.00 and see if it works.
It is also common practice to surround it with a try-catch block to prompt to the user what went wrong.
It is crashing because your input string is "P35.00" and you try to parse that into a double. Remove the 'P' and it should work because the compiler will not parse a P into a double.

reading student record from file

I'm trying to read a file that has student record(first name, last name, and grade).
I have written a simple code to accomplish this task but the code fails after reading two lines from the text file. Here is my code:
public class Student {
private final String first,last;
final int MAXGRADE = 100;
final int LOWGRADE = 0;
private final int grade;
public Student(String firstname,String lastname, int grade){
this.first = firstname;
this.last = lastname;
this.grade = grade;
}
#Override
public String toString(){
return first + " " + last + "\t" + grade;
}
}
and the driver has this code
public class driver {
public static void main(String[] args) throws FileNotFoundException {
String first_name ,last_name;
int grade;
Scanner fileInput = new Scanner(new File("data1.txt"));
while (fileInput.hasNextLine())
{
first_name = fileInput.next();
last_name = fileInput.next();
grade = fileInput.nextInt();
Student st = new Student(first_name, last_name,grade);
System.out.println(st);
}
}
}
the compiler is pointing to this
grade = fileInput.nextInt();
as the source of the error.
This code is working for me. Make Sure
The location of text file correctly given,
Integer value given at 3rd position in each line (like:- steve smith 22)
If you are using Java 8, then functional way of doing this would be:
String filePath = "C:/downloads/stud_records.txt"; // your file path
/*
* Gives you a list of all students form the file
*/
List<Student> allStudentsFromFile = Files.lines(Paths.get(filePath)).map(line -> {
String[] data = line.split("\\s+"); //Split on your delimiter
Student stud = new Student(data[0], data[1], Integer.parseInt(data[2]));
return stud;
}).collect(Collectors.toList());
Note: I've made an assumption that this:
FirstName LastName Grade
is the input file format.
From the comment you post "#AxelH each line represents a single student first, last name and grade" we can see the problem.
Your actual loop to read a line
while (fileInput.hasNextLine())
{
first_name = fileInput.next();
last_name = fileInput.next();
grade = fileInput.nextInt();
Student st = new Student(first_name, last_name,grade);
System.out.println(st);
}
Is reading 3 lines, one per fileInput.nextXXX();. What you need to do is
Read a line as a String : `String line = fileInput.nextLine();
Split that line base on the delimiter : `String[] data = line.split(" "); //Or your delimiter if not space (carefull with some names...)
Set the value from this array (parse are need for integer)
EDIT :
I have made a mistake since I am used to use nextline and not next, I can't delete the answer as it is accepted so I will update it to be more correct without changing the content.
The code is indeed correct, next will take the following input until the next delimiter, \\p{}javaWhitespace}+, but using the given solution would give you more solution to manage composed names as it could be Katrina Del Rio 3.

separating lines of printed text when using printf

Working on a project that requires something to be printed as "printf" but the next line then ends up on the same line as the previous one, how would I go about seperating these?
System.out.print("Cost per course: ");
double costPerCourse1;
costPerCourse1 = keyboard.nextDouble();
System.out.printf("%.2f", costPerCourse1 + /n);
double tuition;
tuition = numberOfClasses1 * costPerCourse1;
System.out.println("Tuition: " + tuition);
You're trying to pass a new line character into the argument String, something that I don't think work. Better is to include "%n" within the format String passed into printf and that will give you an OS independent new line. For example:
System.out.printf("%.2f%n", costPerCourse1);
Or you could simply follow your printf with an empty SOP call.
Edit
I'm wrong. An argument String can have a valid newline char and it works:
public class TestPrintf {
public static void main(String[] args) {
String format1 = "Format String 1: %s";
String arg1 = "\nArgument String 1 that has new line\n";
System.out.printf(format1, arg1);
String format2 = "Format String 2 has new line: %n%s%n";
String arg2 = "Argument String2 without new line";
System.out.printf(format2, arg2);
}
}
returns:
Format String 1:
Argument String 1 that has new line
Format String 2 has new line:
Argument String21 without new line
Or:
System.out.printf("%s: %.4f%s%s", "Value:", Math.PI, "\n", "next String");
returns:
Value:: 3.1416
next String

How to transform this String (contains string and int) to an actual number? (Java) [duplicate]

This question already has answers here:
Best way to parseDouble with comma as decimal separator?
(10 answers)
Closed 7 years ago.
I have a string.
String value = "The value of this product: 13,45 USD";
I want it to be a double which should be like:
double actualprice=13,45;
Or should i use float, double is useless here? Sorry, i am not an expert.
So how can i transform this string to a number?
oh and i almost forgot, i've got a code, which makes it to "13,45" but it's still a String.
String price = "The price is: 13.45";
String s = price;
for(int b=0;b<s.length();b++){
if(s.charAt(b)=='.') {
System.out.print(",");
}
if(Character.isDigit(s.charAt(b))) {
System.out.print(s.charAt(b)+"");
}
}
This code will work. It will throw a NumberFormatException if the string formatted in different manner and number was not found.
double actualprice = Double.parseDouble(
value.replaceFirst("The value of this product: (\\d+),(\\d+) USD", "$1.$2"));
System.out.println(actualprice);
This may be helpful.
public class RegexTest1 {
public static void main(String[] args) {
Pattern p = Pattern.compile("\\d+,\\d+");
Matcher match = p.matcher("The value of this product: 13,45 USD");
Double d ;
while (match.find()) {
System.out.println(match.group());
DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator(',');
symbols.setGroupingSeparator(' ');
df.setDecimalFormatSymbols(symbols);
try {
d = (Double)df.parse(match.group());
System.out.println(d);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Categories

Resources