Deleting a specific part of a text file - java

So I have a program that stores dates.
This is the function that counts the number of dates in the file.
public static int getLineCount() throws FileNotFoundException {
System.out.println("Line count called");
int datenumber = 0;
int attrnumber = 0;
try {
Scanner readLine = new Scanner(new FileReader(dates));
readLine.useDelimiter("<>");
while (readLine.hasNext()) {
readLine.next();
if (attrnumber == 3) {
datenumber++;
attrnumber = 0;
} else {
attrnumber++;
}
}
} catch (IOException e) {
System.out.print("Cannot read file!");
}
;
System.out.println("Line count is: " + datenumber);
return datenumber;
}
This is how the file looks
14<>7<>2014<>sdfsdf<>14<>4<>2016<>asdas<>
The Format is DAY<>MONTH<>YEAR<>NAME<>
Lets say I have 3 dates store and I want to delete the second date, how could I accomplish this ?
Could I use the same code here but instead once it gets to the position that I want to delete, it will somehow remove the data ?
I have
DAY1<>MONTH1<>YEAR1<>NAME1<>DAY2<>MONTH2<>YEAR2<>NAME2<>DAY3<>MONTH3<>YEAR3<>NAME3<>
I want
DAY1<>MONTH1<>YEAR1<>NAME1<>DAY3<>MONTH3<>YEAR3<>NAME3<>

public static void main(String args[]){
String str = "DAY1<>MONTH1<>YEAR1<>NAME1<>DAY2<>MONTH2<>YEAR2<>NAME2<>DAY3<>MONTH3<>YEAR3<>NAME3<>";
System.out.println(remove(str, "<>", 4, 2));
}
/**
*
* #param sentence your main sentence
* #param delimeter delimeter which sentence contains like <>
* #param range range of line, for this example as you can see each row contains 4 items, so its range is 4
* #param removed_range, whing range is removed, for example 2 range etc
* #return
*/
public static String remove(String sentence, String delimeter, int range, int removed_range){
String str= "";
ArrayList<String> items = new ArrayList<>();
if(sentence.contains(delimeter)){
items.addAll(Arrays.asList(sentence.split(delimeter)));
}
int cnt = 0;
for(String item : items){
if(cnt<range || cnt>= removed_range*range)
str+=item+delimeter;
cnt++;
}
return str;
}
result:
DAY1<>MONTH1<>YEAR1<>NAME1<>DAY3<>MONTH3<>YEAR3<>NAME3<>

Related

So my NumberOperations class can't be found?

Here's the code (number operations class is the second listed):
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// declare and instantiate ArrayList with generic type <NumberOperations>
ArrayList<NumberOperations> numOpsList
= new ArrayList<NumberOperations>();
// prompt user for set of numbers
System.out.println("Enter a list of positive integers separated "
+ "with a space followed by 0:");
// get first user input using in.nextInt()
int number = in.nextInt();
// add a while loop as described below:
// while the input is not equal to 0
// add a new NumberOperations object to numOpsList based on user
input
// get the next user input using in.nextInt()
while (number != 0) {
numOpsList.add(new NumberOperations(number));
number = in.nextInt();
}
int index = 0;
while (index < numOpsList.size()) {
NumberOperations num = numOpsList.get(index);
System.out.println("For: " + num);
// add print statement for odds under num
// add print statement for powers of 2 under num
index++;
}
public class NumberOperations {
// instance variables
private int number;
// constructor
/**
* #param numberIn is number
*/
public NumberOperations (int numberIn) {
number = numberIn;
}
// methods
/**
* #return value
*/
public int getValue()
{
return number;
}
public String oddsUnder()
{
String output = "";
int i = 0;
while (i < number) {
if(i % 2 != 0) {
output += i + "\t";
}
i++;
}
return output;
}
public String powersTwoUnder()
{
String output = "";
int powers = 1;
while (powers < number) {
output += powers + "\t";
powers = powers * 2;
}
return output;
}
public int isGreater (int compareNumber)
{
if (number > compareNumber)
{
return 1;
}
else if (number < compareNumber)
{
return -1;
}
else
{
return 0;
}
}
public String toString()
{
String output = "";
return number + "";
}
}
The error I'm getting is that the compiler can't find "NumberOperations" anywhere. Its probably a very rudimentary issue I have, but I'm lost.
Edit: I added the class for numberoperations in case it helps. I thought I did everything right as far as this goes though.
Enter a list of positive integers separated with a space followed by 0:
1 2 3 4 0
For: 1
For: 2
For: 3
For: 4
I decorated the main method with a class
import java.util.*;
public class NumberOperationsTest {
yes, import was left to the helping User, too.
Closed the class just before the class NumberOperations, which I freed from the public declaration, to have it compilable in a single file.
In a different file, the public keyword is fine.
On compilation, you have to tell the classpath, to look in the current directory:
javac -cp . NumberOperationsTest.java

Getting ArrayOutOfBounds and NullPointerException But I don't Know Why

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.

how to compare strings in java and save the result in string array?

I have the following string array:
February_Report_files\customerst.rptdesign
February_Report_files\Top10Percent.rptdesign
February_Report_files\TopNPercent.rptdesign
March_Report_files\by_sup_ML.rptdesign
March_Report_files\chart__cwong.rptdesign
March_Report_files\HTML5 Chart.rptdesign
I want save report files(*.rptdesign) file in different string arrays according to different folder names .for example :
result[0]="customerst.rptdesign,Top10Percent.rptdesign,TopNPercent.rptdesign"
result[1]="by_sup_ML.rptdesign,chart__cwong.rptdesign,HTML5 Chart.rptdesign"
how can I get this result ? could you give me some suggestions ?
Here is a quick code snippet:
public static void main (String[] args)
{
/* Sample Space */
String[] strArr = new String[] {
"February_Report_files\\customerst.rptdesign",
"February_Report_files\\Top10Percent.rptdesign",
"February_Report_files\\TopNPercent.rptdesign",
"March_Report_files\\by_sup_ML.rptdesign",
"March_Report_files\\chart__cwong.rptdesign",
"March_Report_files\\HTML5 Chart.rptdesign",
};
/* Sort Sample Space */
Arrays.sort(strArr);
/* Initialize Result ArrayList */
List<String> resultList = new ArrayList<>();
/* Initialize */
String[] strInit = strArr[0].split("\\\\");
String prefix = strInit[0];
StringBuilder result = new StringBuilder(strInit[1]);
for(int i = 1; i < strArr.length; i++) {
/* Split Using Backslash */
String[] strSplit = strArr[i].split("\\\\");
if(strSplit[0].equals(prefix)) {
/* Append */
result.append("," + strSplit[1]);
} else {
/* Add Result To List */
resultList.add(result.toString());
/* Reset Prefix, Result Strings */
prefix = strSplit[0];
result = new StringBuilder(strSplit[1]);
}
}
/* Add Last Entry To List */
resultList.add(result.toString());
/* Print The Results */
for(int i = 0; i < resultList.size(); i++) {
System.out.println(resultList.get(i));
}
}
Output of this program:
customerst.rptdesign,Top10Percent.rptdesign,TopNPercent.rptdesign
by_sup_ML.rptdesign,chart__cwong.rptdesign,HTML5 Chart.rptdesign
Below is the implementation with hashmap
for(int i=0;i<strarr.length;i++){
boolean blnExists=false;
String key = strarr[i].substring(0,strarr[i].indexOf("\\"));
String value=strarr[i].substring(strarr[i].indexOf("\\")+1);
blnExists = result.containsKey(key);
if(blnExists){
value=result.get(key) + ","+value;
}
else{
result.put(key, value);
}
result.put(key, value);
}
`
Use startsWith():
if(fileName[i].startsWith("March_Report_files"))
saveItHere(fileName[i]);
else
saveItThere(fileName[i]);
You might want to shorten your String afterwards with
fileName[i]=fileName[i].replaceFirst.("March_Report_files","");
For example:
public class StringTest {
public static void main(String[] args){
String text = "Hello\\World";
if(text.startsWith("Hello\\"))
text=text.replaceFirst("Hello\\\\","");
System.out.println(text);
}
}

Setting an array of objects and searching through it for variables

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.

Resolving ArrayIndexOutOfBoundException while using ArrayList

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

Categories

Resources