I am testing a program I wrote for an assignment, and right now it's testing at 50% against test cases. I get the following errors when I submit, but I can't figure out why. I tried changing some pieces of code and retesting, but no matter what I do I get the same errors, so I must be completely missing what I should be looking for. Here is the CSV file from which the data is being pulled -
CSV Data File. Here are the errors I get:
Here is my code:
Main class:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package csc212hw04;
import java.io.File;
import java.util.Scanner;
/**
*
* #author Michal
*/
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception{
Scanner kb = new Scanner(System.in);
boolean flag = true;
System.out.println("Welcome to the Car Database");
System.out.println("Enter the size of the array:");
int size = Integer.parseInt(kb.nextLine());
CarDatabase db1 = new CarDatabase(size);
System.out.println("Enter the name of the input file:");
String userFile = new String(kb.nextLine());
db1.readFile(userFile);
while (flag) {
System.out.println("Enter make, mpg, weight, all, or quit:");
String command = kb.nextLine();
if (command.equals("make")) {
System.out.println("Enter the make:");
String make = kb.nextLine();
db1.displayMake(make);
} else if (command.equals("mpg")) {
System.out.println("Enter the mpg range:");
double mpgLow = Double.parseDouble(kb.nextLine());
double mpgHigh = Double.parseDouble(kb.nextLine());
db1.mpgRange(mpgLow, mpgHigh);
} else if (command.equals("weight")) {
System.out.println("Enter the weight range:");
double weightLow = Double.parseDouble(kb.next());
double weightHigh = Double.parseDouble(kb.next());
db1.weightRange(weightLow, weightHigh);
} else if (command.equals("all")) {
CarDatabase.displayAll();
} else if (command.equals("quit")) {
flag = false;
}
}
}
}
CarDatabase class:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package csc212hw04;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
/**
*
* #author Michal
*/
public class CarDatabase {
private static Car[] database;
public CarDatabase(int s) {
this.database = new Car[s];
}
public boolean isFull() {
boolean full = true;
for (int i = 0; i < database.length; i++) {
if (database[i] == null) {
full = false;
}
}
return full;
}
public static void readFile(String f) throws FileNotFoundException {
File file = new File(f);
int lineNum = 0;
Scanner sc = new Scanner(file);
String csvSplitBy = ",";
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] carData = line.split(csvSplitBy);
String model = carData[0];
String make = carData[1];
double mpg = Double.parseDouble(carData[2]);
int weight = Integer.parseInt(carData[3]);
int year = Integer.parseInt(carData[4]);
database[lineNum] = new Car(model, make, mpg, weight, year);
lineNum++;
}
}
public static void displayMake(String m) {
for (int i = 0; i < database.length; i++) {
if (database[i].make.equals(m)) {
database[i].toString();
}
}
}
public static void mpgRange(double l, double h) {
for (int i = 0; i < database.length; i++) {
if (database[i].mpg >= l && database[i].mpg <= h) {
database[i].toString();
}
}
}
public static void weightRange(double l, double h) {
for (int i = 0; i < database.length; i++) {
if ((database[i].weight >= l) && (database[i].weight <= h)) {
database[i].toString();
}
}
}
public static void displayAll() {
for (int i = 0; i < database.length; i++) {
database[i].toString();
}
}
}
Car class:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package csc212hw04;
/**
*
* #author Michal
*/
public class Car {
public String model, make;
public double mpg;
public int weight, year;
public Car(String md, String mk, double umpg, int w, int y) {
model = md;
make = mk;
mpg = umpg;
weight = w;
year = y;
}
public String toString() {
return "Model:" + model + " Make:" + make + " mpg:" + " weight:" + " year:" + year;
}
}
Here is a sample from the CSV file if you cannot see it:
You are probably getting to the End of File and you try to split. The array then doesn't have any value. Make sure there is no blank line at the end of your database, or put a check in your readfile to make sure that if the carData.length == NUMBER OF DATA FIELDS
Update
You also should check to make sure that you don't pass the total number of database entries you have. So do:
while(sc.hasNextLine() && lineNum < database.length) {
ArrayIndexOutOfBoundsException is thrown in very specific circumstances:
Thrown to indicate that an array has been accessed with an illegal
index. The index is either negative or greater than or equal to the
size of the array.
In your code, you assume that each row in your csv has the same number of fields.
You're also assuming that the size of database array matches the number of cars in your file. Since you don't create your database array entries until you read them from the file - but you pre-initialize the size database array, you could end up reading past the end of your database if the number of records in the CSV is larger than the value you initialize for the database size.
Related
Write a class with a constructor that accepts a file name as its argument. Assume the file contains a series of numbers, each written on a separate line. The class should read the contents of the file into an array, and then displays the following data.
The lowest number in the array
The highest number in the array
The total of the numbers in the array
The average of the numbers in the array.
The file, Numbers.txt used for the above program contains these twelve numbers:
8.71
7.94
3.01
29.27
9.23
82.76
12.6
47.99
63.89
1.09
22.23
79.17
This is the main program: NumberAnalyzerDemo.java
import java.io.*; // Needed for IOException
/**
This program demonstrates a solution to the
Number Analysis Class programming challenge.
*/
public class NumberAnalyzerDemo
{
public static void main(String[] args) throws IOException
{
// Create a NumberAnalyzer object.
NumberAnalyzer na = new NumberAnalyzer("Numbers.txt");
// Display data about the numbers in the file.
System.out.println("The lowest number in the file is " +
na.getLowest());
System.out.println("The highest number in the file is " +
na.getHighest());
System.out.println("The total of the numbers in the file is " +
na.getTotal());
System.out.println("The average of the numbers in the file is " +
na.getAverage());
}
}
This is the class: NumberAnalyzer.java
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
import java.io.File;
/**
The NumberAnalyzer class is to searching the numbers in a file.
*/
public class NumberAnalyzer
{
private double[] numbers;
private int count;
File file;
Scanner scan;
/**
Constructer that accepts the file name as its argument.
*/
public NumberAnalyzer(String filename) throws IOException
{
count = 0;
file = new File("Numbers.txt");
scan = new Scanner(file);
numbers = new double[11];
}
/**
The getLowest() method to search the file and pull out the lowest
number in the file.
#return Return the lowest number.
*/
public double getLowest()
{
double low = numbers[0];
for (int i = 0; i < numbers.length; i++)
{
if (low > numbers[i])
{
low = numbers[i];
}
}
return low;
}
/**
The getHighest() method to search the file and pull out the highest
number in the file.
#return Return the highest number.
*/
public double getHighest()
{
double high = numbers[0];
for (int i = 0; i < numbers.length; i++)
{
if (high < numbers[i])
{
high = numbers[i];
}
}
return high;
}
/**
This method calculate the total of all the number in the file.
#return Adding all number in the file.
*/
public double getTotal()
{
double total = 0;
for (int i = 0; i < numbers.length; i++)
{
total += numbers[i];
}
return total;
}
/**
This method used to calculate the average of the numbers in the file.
#return Using the getTotal() divided to the length of the numbers.
*/
public double getAverage()
{
return getTotal() / numbers.length;
}
/**
This method to read all the file txt and get the right number.
*/
private void getNumbers(String filename)
{
while(scan.hasNext())
{
numbers[count] = scan.nextDouble();
count++;
}
scan.close();
}
/**
This method
*/
private int getNumberOfValues(String filename)
{
return count ;
}
}
I'm getting 0.0 for all the output. Please give me some suggestions. Thanks!
solution
change you method
private void getNumbers(String filename)
to
public void getNumbers()
and then do
NumberAnalyzer na = new NumberAnalyzer("Numbers.txt");
na.getNumbers();
You're not calling your getNumbers() method, and so haven't populated your numbers[] array.
Just make the call in your constructor, like this:
public NumberAnalyzer(String filename) throws IOException
{
count = 0;
file = new File("Numbers.txt");
scan = new Scanner(file);
numbers = new double[11];
getNumbers();
}
It looks like it doesn't need to have the String argument, so you could remove that, unless you're still planing to implement something with it.
I've been struggling with a method that is meant to search through an array of objects and return a specific value.In my driver class, I read the periodic table csv file and split the variables read in each line send it to an object of the Element class. In my periodic table class, I create an array of Element objects that is meant to hold each element that is read from the driver. My current "findElement" method results in a nullpointer exception and I'm not sure if my array of objects is doing exactly what I want it to. Feel free to throw out suggestions. Below are my classes:(i went back to a driver only program)
Driver:This class opens an input file and splits a line into 7 different variables which are then sent to an Element class object.
public class PeriodicTableDriver
{
public static void main(String[] args)
{
Scanner keyboard= new Scanner(System.in);
Scanner inputStream=null;
String elementName="";
String atomicNumber="";
String symbol="";
double boilingPoint=0;
double meltingPoint=0;
double density=0;
double molecularWeight=0;
int choice=0;
String fileName1= "PeriodicTableData.csv";
String fileName2= "MolecularWeightInput.txt";
PeriodicTable periodicTable= new PeriodicTable();
try
{
inputStream=new Scanner(new File(fileName1));
}
catch(FileNotFoundException e){
System.out.println("Error opening the file.");
System.exit(0);
}
int count=0;
String title=inputStream.nextLine();
while(inputStream.hasNext()){
String periodicInfo=inputStream.nextLine();
String[] PeriodicTableData= periodicInfo.split(",");
elementName=PeriodicTableData [0];
atomicNumber= PeriodicTableData [1];
symbol= PeriodicTableData [2];
if (PeriodicTableData[3].equals(""))
boilingPoint = 0;
else
boilingPoint = Double.parseDouble(PeriodicTableData[3]);
if (PeriodicTableData[4].equals(""))
meltingPoint = 0;
else
meltingPoint = Double.parseDouble(PeriodicTableData[4]);
if (PeriodicTableData[5].equals(""))
density = 0;
else
density = Double.parseDouble(PeriodicTableData[5]);
if (PeriodicTableData[6].equals(""))
molecularWeight = 0;
else
molecularWeight = Double.parseDouble(PeriodicTableData[6]);
count++;
Element element= new Element(count,elementName,atomicNumber,symbol,boilingPoint,meltingPoint,density,molecularWeight);
periodicTable.readPeriodicTableInfo(element);
periodicTable.displayElement(symbol);
}
try
{
inputStream=new Scanner(new File(fileName2));
}
catch(FileNotFoundException e){
System.out.println("Error opening the file.");
System.exit(0);
}
while(inputStream.hasNextLine()){
}
}
}
Element class: holds all of the variables read from the driver and has a toString method for formatting them
public class Element
{
String elementName;
String atomicNumber;
String symbol;
double boilingPoint;
double meltingPoint;
double density;
double molecularWeight;
int count;
public Element(int count, String elementName, String atomicNumber, String symbol,
double boilingPoint, double meltingPoint, double density,
double molecularWeight)
{
super();
this.count=count;
this.elementName = elementName;
this.atomicNumber = atomicNumber;
this.symbol = symbol;
this.boilingPoint = boilingPoint;
this.meltingPoint = meltingPoint;
this.density = density;
this.molecularWeight = molecularWeight;
}
public String toString(){
String element = "Element name: " + elementName
+ "\nAtomic Number: " + atomicNumber
+ "\nSymbol: " + symbol;
if (boilingPoint == 0)
{
element = element + "\nBoiling Point: unknown";
}
else
{
element = element + "\nBoiling Point: " + boilingPoint + " K";
}
if (meltingPoint == 0)
{
element = element + "\nMelting Point: unknown";
}
else
{
element = element + "\nMelting Point: " + meltingPoint + " K";
}
if (density == 0)
{
element = element + "\nDensity: unknown";
}
else
{
element = element + "\nDensity: " + density + " g/L";
}
element=element+"\nMolecular Weight: " + molecularWeight + "g/mole";
return element;
}
/**
* #return the elementName
*/
public String getElementName()
{
return elementName;
}
/**
* #return the atomicNumber
*/
public String getAtomicNumber()
{
return atomicNumber;
}
/**
* #return the symbol
*/
public String getSymbol()
{
return symbol;
}
/**
* #return the boilingPoint
*/
public double getBoilingPoint()
{
return boilingPoint;
}
/**
* #return the meltingPoint
*/
public double getMeltingPoint()
{
return meltingPoint;
}
/**
* #return the density
*/
public double getDensity()
{
return density;
}
/**
* #return the molecularWeight
*/
public double getMolecularWeight()
{
return molecularWeight;
}
/**
* #return the count
*/
public int getCount()
{
return count;
}
}
PeriodicTable class: holds methods that will fulfill the menu items
public class PeriodicTable
{
private final static int ARRAY_SIZE= 120;
private Element[] elements;
private int count=110;
Scanner keyboard= new Scanner(System.in);
public PeriodicTable(){
elements = new Element[ARRAY_SIZE];
}
public void readPeriodicTableInfo(Element element){
for(int i=0; i<elements.length;i++){
elements[i]=element;
System.out.println(elements[i].toString());
}
}
public void displayMenu(){
System.out.println("1. Display information for all elements in the Periodic Table");
System.out.println("2. Display information for one element");
System.out.println("3. Display particle information for one element");
System.out.println("4. Display the element with the highest boiling point");
System.out.println("5. Display the element with the lowest melting point");
System.out.println("6. Display the molecular mass calculations for elements in file");
System.out.println("7. Quit");
System.out.print("Please enter your choice: ");
}
public int findElement(String symbol){
System.out.println("Enter element symbol: ");
String elementSymbol=keyboard.next();
for(int i=0; i<elements.length;i++){
if(elementSymbol.equalsIgnoreCase(elements[i].getSymbol())){
return i;
}
}
return -1;
}
public void displayElement(String symbol){
System.out.println();
System.out.println(elements[findElement(symbol)].toString());
}
}
You've got lots of issues in that code, not the least of which your PeriodicTable looks like it will hold multiple references to one and only one Element.
but as to your problem:
Your findElement method should have no println statements,
it should have no keyboard.next() or keyboard statements at all.
it should simply use the String that was passed in via its parameter and search the elements array for the matching element.
You'll also have to fix how it fills up the array so that each array item holds a unique element.
So findElement should be much simpler, something like:
public int findElement(String symbol){
for(int i=0; i<elements.length;i++) {
if(symbol.equalsIgnoreCase(elements[i].getSymbol())){
return i;
}
}
// I'd throw an exception here if no element is found
}
Even better would be to have the method return the found Element object and not the int array index.
Also, a side recommendation: Please look up and try to follow Java code formatting rules. By following these rules, others will more easily be able to read and understand your code, and then be able to help you. If you are using most IDE's they can help you format your code correctly for you.
Edit: This appears to be the most broken method of all:
public void readPeriodicTableInfo(Element element){
for (int i=0; i<elements.length;i++) {
elements[i]=element;
System.out.println(elements[i].toString());
}
}
Let's look at what it does: it loops through the entire elements array, placing the element that is passed into this method into every item within the array, something that I really don't think you want to have happen. Instead, you should add the element passed in to one and only one item in the array. This would be best performed by changing elements from an array to an ArrayList<Element>, and then you could simply call the ArrayList add method. If you can't use that, then you're going to have to use an index variable to keep track of how many elements have already been added, and then add the latest one into the next empty array slot.
I have my program complete. The one thing I need is a way for it to handle blank lines. I have read other posts but none have helped me implement them into my own code. I've tried various syntax within the loop that reads the file, but none have worked. Can someone help me please. This seems like it should be easier than it feels like currently. I'm trying to implement this into my code but am having trouble doing it. Below are my two classes and the input.txt. As is, this program runs as intended. Thanks for any help.
String line = in.nextLine();
while (line.length() == 0) {
if (in.hasNext()) {
line = in.nextLine();
} else {
break;
}
}
if (line.length() == 0) {
// reaches the end of input file
}
Product.java
/**
* Product
*
* A simple class framework used to demonstrate the design
* of Java classes.
*
* #author
* #version 02042015
*/
import java.util.*;
public class Product {
private String name;
private String code;
private int quantity;
private double price;
private String type;
private ArrayList<Integer> userRatings;
/*
* Product constructor
*/
public Product() {
name = "";
code = "";
quantity = 0;
price = 0.0;
type = "";
userRatings = new ArrayList<Integer>();
}
public Product(Product productObject) {
this.name = productObject.getName();
this.code = productObject.getInventoryCode();
this.quantity = productObject.getQuantity();
this.price = productObject.getPrice();
this.type = productObject.getType();
this.userRatings = new ArrayList<Integer>();
}
public Product(String name, String code, int quantity, double price, String type) {
this.name = name;
this.code = code;
this.quantity = quantity;
this.price = price;
this.type = type;
this.userRatings = new ArrayList<Integer>();
}
/*
* setName
* #param name - new name for the product
*/
public void setName(String name) {
this.name = name;
}
/*
* getName
* #return the name of the product
*/
public String getName() {
return name;
}
/*
* setType
* #param type - the type of the product
*/
public void setType(String type) {
this.type = type;
}
/*
* getType
* #return - the product type
*/
public String getType() {
return type;
}
/*
* setPrice
* #param price - the price of the product
*/
public void setPrice(double price) {
this.price = price;
}
/*
* getPrice
* #return the price of the product
*/
public double getPrice() {
return price;
}
/*
* setQuantity
* #param quantity - the number of this product in inventory
*/
public void setQuantity(int quantity) {
this.quantity = quantity;
}
/*
* getQuantity
* #return the number of this product in inventory
*/
public int getQuantity() {
return quantity;
}
/*
* setInventoryCode
* #param code - the new inventory code for the product
*/
public void setInventoryCode(String code) {
if(code.length()!= 8){
System.out.println("An invalid code has been entered. Please enter a code that is 8 characters in length.");
}
else{
}
this.code=code;
}
/*
* getInventoryCode
* #return the inventory code of the product
*/
public String getInventoryCode() {
return code;
}
/*
* setRatings
* #param code the new set of ratings for the product
*/
public void setRatings(ArrayList<Integer> Ratings){
this.userRatings = Ratings;
}
/*
* getRatings
* #return the ratings of the product
*/
public ArrayList<Integer> getRatings(){
return userRatings;
}
/*
* addUserRating
* NOTE: Each individual rating is stored with the product, so you need to maintain a list
* of user ratings. This method should append a new rating to the end of that list
* #param rating - the new rating to add to this product
*/
public void addUserRating(Integer rating1) {
if(rating1 > 5 || rating1 < 0){
System.out.println("You have entered an invalid rating. Please enter a rating between one and five stars.");
}
this.userRatings.add(rating1);
}
/*
* getUserRating
* NOTE: See note on addUserRating above. This method should be written to allow you
* to access an individual value from the list of user ratings
* #param index - the index of the rating we want to see
* #return the rating indexed by the value index
*/
public int getUserRating(int index) {
int a = this.userRatings.get(index);
return a;
}
/*
* getUserRatingCount
* NOTE: See note on addUserRating above. This method should be written to return
* the total number of ratings this product has associated with it
* #return the number of ratings associated with this product
*/
public int getUserRatingCount() {
int a = this.userRatings.size();
return a;
}
/*
* getAvgUserRating
* NOTE: see note on addUserRating above. This method should be written to compute
* the average user rating on demand from a stored list of ratings.
* #return the average rating for this product as a whole integer value (use integer math)
*/
public String getAvgUserRating() {
int sum = 0;
String avgRating = "";
if (userRatings.size() != 0){
for (int i = 0; i < this.userRatings.size(); i++) {
int a = getUserRating(i);
sum += a;
}
double avg = sum/this.userRatings.size();
if(avg >= 3.5){
avgRating = "****";
}
else if(avg >= 2.5){
avgRating = "***";
}
else if(avg >= 1.5){
avgRating = "**";
}
else if(avg >= 0.5){
avgRating = "*";
}
else{
}
}
else{
avgRating = "";
}
return avgRating;
}
}
Project02.java
/**
* Inventory Reporting Program
*
* A simple set of methods used to report and summarize
* the information read from an inventory file of product data
*
* #author
* #version 02042015
*/
import java.util.*;
import java.io.*;
public class Project02 {
public static void main(String[] args) {
//Establish the scanner so user input can be properly read.
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter an inventory filename: ");
String fname = keyboard.nextLine();
ArrayList<Product> products = loadProducts(fname);
generateSummaryReport(products);
highestAvgRating(products);
lowestAvgRating(products);
largestTotalDollarAmount(products);
smallestTotalDollarAmount(products);
}
public static void generateSummaryReport (ArrayList<Product> Products){
int counter = 0;
System.out.println("Product Inventory Summary Report");
System.out.println("----------------------------------------------------------------------------------");
System.out.println();
System.out.printf("%-33s%-10s%-6s%-7s%-7s%-7s%-7s", "Product Name", "I Code", "Type", "Rating", "# Rat.", "Quant.", "Price");
System.out.println();
System.out.printf("%-33s%-10s%-6s%-7s%-7s%-7s%-7s", "-------------------------------", "---------", "----", "------", "------", "------", "------");
System.out.println();
while(counter < Products.size()){
System.out.printf("%-33s%-10s%-6s%-7s%6s%7s%7s", Products.get(counter).getName(), Products.get(counter).getInventoryCode(), Products.get(counter).getType(), Products.get(counter).getAvgUserRating(), Products.get(counter).getUserRatingCount(), Products.get(counter).getQuantity(), Products.get(counter).getPrice());
System.out.println();
counter++;
}
System.out.println("----------------------------------------------------------------------------------");
System.out.println("Total products in the database: " + Products.size());
}
/*
* loadProducts
* Given a filename, opens the file and reads Products from
* the file into an ArrayList of Product objects. Returns
* the ArrayList.
*
*
* #param fname - String containing the input file name
* #return - An ArrayList of Product objects
*/
public static ArrayList<Product> loadProducts(String fname) {
int a = 0;
Integer b = 0;
ArrayList<Product> products = new ArrayList<Product>();
try {
Scanner inFile = new Scanner(new File(fname));
while (inFile.hasNext()) {
int counter = 0;
String name = inFile.nextLine();
String code = inFile.nextLine();
int quantity = inFile.nextInt();
double price = inFile.nextDouble();
String type = inFile.next();
Product productObject = new Product(name, code, quantity, price, type);
while(inFile.hasNextInt() && counter==0){
a = inFile.nextInt();
if(a != -1){
b = new Integer(a);
productObject.addUserRating(b);
}
else{
counter = 1;
}
}
products.add(productObject);
if(inFile.hasNext()){
inFile.nextLine();
}
}
inFile.close();
}
catch (FileNotFoundException e) {
System.out.println("ERROR: " + e);
}
return products;
}
//Finds the item with the highest average user rating in stock
public static void highestAvgRating(ArrayList<Product> Products){
int counter = 0;
int a = 1;
while (counter <= Products.size()-1){
if(Products.get(counter).getAvgUserRating().length() > Products.get(a).getAvgUserRating().length()){
a = counter;
}
else{
}
counter++;
}
System.out.println("Highest Average User Rating In Stock: " + Products.get(a).getName() + " ("+Products.get(a).getAvgUserRating() + ")");
}
//Finds the item with the lowest average user rating in stock
public static void lowestAvgRating(ArrayList<Product> Products){
int counter = 0;
int a = 1;
while (counter <= Products.size()-1){
if(Products.get(counter).getAvgUserRating().length()<Products.get(a).getAvgUserRating().length()){
a=counter;
}
else{
}
counter++;
}
System.out.println("Lowest Average User Rating In Stock: "+Products.get(a).getName() + " ("+Products.get(a).getAvgUserRating() + ")");
}
//Finds the item with the largest total dollar amount in inventory (quantity * price)
public static void largestTotalDollarAmount(ArrayList<Product> Products){
int counter = 0;
int a = 1;
while (counter <= Products.size()-1){
if((Products.get(counter).getPrice())*(Products.get(counter).getQuantity()) > ((Products.get(a).getPrice())*(Products.get(a).getQuantity()))){
a=counter;
}
else{
}
counter++;
}
System.out.println("Item With The Largest Total Dollar Amount In Inventory: " + Products.get(a).getName() + " ($" + ((Products.get(a).getPrice())*(Products.get(a).getQuantity())) + ")");
}
//Finds the item with the smallest total dollar amount in inventory (quantity * price)
public static void smallestTotalDollarAmount(ArrayList<Product> Products){
int counter = 0;
int a = 1;
while (counter <= Products.size()-1){
if((Products.get(counter).getPrice())*(Products.get(counter).getQuantity()) < ((Products.get(a).getPrice())*(Products.get(a).getQuantity()))){
a=counter;
}
else{
}
counter++;
}
System.out.println("Item With The Smallest Total Dollar Amount In Inventory: " + Products.get(a).getName() + " ($" + ((Products.get(a).getPrice())*(Products.get(a).getQuantity())) + ")");
}
}
input.txt
The Shawshank Redemption
C0000001
100
19.95
DVD
4
5
3
1
-1
The Dark Knight
C0000003
50
19.95
DVD
5
2
3
-1
Casablanca
C0000007
137
9.95
DVD
5
4
5
3
-1
The Girl With The Dragon Tattoo
C0000015
150
14.95
Book
4
4
2
-1
Vertigo
C0000023
55
9.95
DVD
5
5
3
5
2
4
-1
A Game of Thrones
C0000019
100
8.95
Book
-1
When you decompose your question, you find there are two main concerns:
Read the input line-by-line
Skip the blank lines.
The first concern can be addressed with while (in.hasNext) in.nextLine(). To address the second concern, simply add a continue when you find the line is empty:
while (in.hasNextLine()) {
line = in.nextLine();
// skip blank lines
if (line.length() == 0) continue;
// do your magic
}
Now, how to get this in to your main program? It would be nice if we could somehow do: inFile.nextNonBlankLine(), right? So let's create our own scanner that has that method!
First things first, how would we like to use our own scanner? One example could be:
SkipBlankScanner in = new SkipBlankScanner(inFile);
while (in.hasNextNonBlankLine()) {
line = in.nextNonBlankLine();
}
Unfortunately Scanner is a final class, so we can't extend it to add our functionality. The next best thing is to use a delegate:
public class SkipBlankScanner {
private Scanner delegate;
private String line;
public SkipBlankScanner(Scanner delegate) {
this.delegate = delegate;
}
public boolean hasNextNonBlankLine() {
while (delegate.hasNextLine())
// return true as soon as we find a non-blank line:
if ((line = delegate.nextLine()).length > 0)
return true;
// We've reached the end and didn't find any non-blank line:
return false;
}
public String nextNonBlankLine() {
String result = line;
// in case we didn't call "hasNextNonBlankLine" before:
if (result == null && hasNextNonBlankLine())
result = line;
// try to read past the end:
if (result == null) throw new IllegalStateException();
line = null;
return result;
}
}
And there you have it, your very own Scanner that will ignore blank lines!
You could take this even further, and create a Scanner that will scan for entire Products, e.g. (with some Java-8):
public class ProductScanner {
private SkipBlankScanner scanner;
private Product product;
public ProductScanner(SkipBlankScanner scanner) {
this.scanner = scanner;
}
public boolean hasNextProduct() {
Product next = new Product();
if (fill(line -> next.setTitle(line)) &&
fill(line -> next.setInventoryCode(line)) &&
fill(line -> next.setQuantity(Integer.parseInt(line))) &&
fill(line -> next.setPrice(Double.parseDouble(line))) &&
fill(line -> next.setType(line))) {
try {
while (scanner.hasNextNonBlankLine() {
int rating = Integer.parseInt(scanner.nextNonBlankLine());
if (rating < 0) {
product = next;
return true;
}
next.addUserRating(rating);
}
} catch (NumberFormatException e) {
}
}
return false;
}
private boolean fill(Consumer<String> action) {
if (scanner.hasNextNonBlankLine() {
try {
action.accept(scanner.nextNonBlankLine());
return true;
} catch (Exception e) {
}
}
return false;
}
public Product nextProduct() {
Product result = product;
if (result == null && hasNextProduct())
result = product;
if (result == null)
throw new IllegalStateException();
product = null;
return result;
}
}
import java.util.Scanner;
/**
* #(#)wefeqwrf.java
*
* wefeqwrf application
*
* #author
* #version 1.00 2013/11/15
*/
public class wefeqwrf {
public static void main(String[] args) {
// TODO, add your application code
Scanner scan= new Scanner(System.in);
String number = "000";
String a;
int count=0;
for(int i=0;a!="-1";i++)
{
for(int k=0;k<3;k++){
a=scan.next();
a.charAt(0)= number.charAt(k);
if(number.equals("110"))
{
System.out.print("Tebrikler!=110");
count++;
}
else
{
System.out.print("Maalesef olmadı:" + number);
}
}
}
}
}
It gives the error:
error: unexpected type at this code: `a.charAt(0)= number.charAt(k);`
how can I assign the content of a to the specified index of number?
and when I changed the string a to the char a scan.next() does not work why and what can I do is there a any scanner method for char?
You should do it this way:
a = number.charAt(k) + a.substring(1);
You can't assign something to a method. Methods only return something.
I am a beginner in java development field and still i am a learner of Java Programming. I wanted to see the output for the Support Vector Machine classifier on netbeans IDE. So i copied this attached piece of code and tried to run by using all the other required class and main method as well but i am getting Number format exception when i give a file containing input like 23,25,26,27 during the call of the method loadBinaryProblem() in main method and if i remove all the commas and replaced them with space ex: 23 25 26 27 then i am getting ArrayIndexOutOfBound exception instead of it. So anybody can help to get the output properly without any error.
package svmlearn;
import java.io.*;
import java.util.*;
/**
* Class representing an optimization problem (a data setting);
* taken from liblinear; "bias" excluded
* #author miafranc
*
*/
public class Problem {
/** The number of training data */
public int l;
/** The number of features (including the bias feature if bias >= 0) */
public int n;
/** Array containing the target values */
public int[] y;
/** Map of categories to allow various ID's to identify classes with. */
public CategoryMap<Integer> catmap;
/** Array of sparse feature nodes */
public FeatureNode[][] x;
public Problem() {
l = 0;
n = 0;
catmap = new CategoryMap<Integer>();
}
/**
* Loads a binary problem from file, i.e. having 2 classes.
* #param filename The filename containing the problem in LibSVM format.
*/
public void loadBinaryProblem(String filename) {
String row;
ArrayList<Integer> classes = new ArrayList<Integer>();
ArrayList<FeatureNode []> examples = new ArrayList<FeatureNode []>();
try {
BufferedReader r = new BufferedReader(new FileReader(filename));
while ((row = r.readLine()) != null) {
String [] elems = row.split(" ");
//Category:
Integer cat = Integer.parseInt(elems[0]);
catmap.addCategory(cat);
if (catmap.size() > 2) {
throw new IllegalArgumentException("only 2 classes allowed!");
}
classes.add(catmap.getNewCategoryOf(cat));
//Index/value pairs:
examples.add(parseRow(elems));
}
x = new FeatureNode[examples.size()][];
y = new int[examples.size()];
for (int i=0; i<examples.size(); i++) {
x[i] = examples.get(i);
y[i] = 2*classes.get(i)-1; //0,1 => -1,1
}
l = examples.size();
} catch (Exception e) {
System.out.println(e);
}
}
/**
* Parses a row from a LibSVM format file.
* #param row The already split row on spaces.
* #return The corresponding FeatureNode.
*/
public FeatureNode [] parseRow(String [] row) {
FeatureNode [] example = new FeatureNode[row.length-1];
int maxindex = 0;
for (int i=1; i<row.length; i++) {
String [] iv = row[i].split(":");
int index = Integer.parseInt(iv[0]);
if (index <= maxindex) {
throw new IllegalArgumentException("indices must be in increasing order!");
}
maxindex = index;
double value = Double.parseDouble(iv[1]);
example[i-1] = new FeatureNode(index, value);
}
if (n < maxindex)
n = maxindex;
return example;
}
}
i guess NumberformatExceptions comes from:
String [] elems = row.split(" "); //nothing done by "23,25,26,27"
//Category:
Integer cat = Integer.parseInt(elems[0]); //you are trying to parse "23,25,26,27"
ArrayIndexOutOfBound comes from:
String [] iv = row[i].split(":");//nothing done
...
double value = Double.parseDouble(iv[1]);//1 is out of bound