specifying the path for input data and output data - java

I am new in java and I have to use the code below but the code it does work because I have to specifying the path for input data and output data. The code is got it from the internet. please help me
class Svm_scale
{
private BufferedReader rewind(BufferedReader fp, String filename) throws IOException
{
fp.close();
return new BufferedReader(new FileReader(filename));
}
private void output_target(double value)
{
LnCount++;
if(y_scaling)
{
if(value == y_min)
value = y_lower;
else if(value == y_max)
value = y_upper;
else
value = y_lower + (y_upper-y_lower) *
(value-y_min) / (y_max-y_min);
}
formatterscaled.format(value+" ");
System.out.println(" Line Number "+LnCount + " ");
}
private void output(int index, double value)
{
count++;
double Threshold1=0,Threshold2=0;
Threshold1= Avg[index]+(STDV[index]/2);
Threshold2= Avg[index]-(STDV[index]/2);
if(value > Threshold1 )
value = 2;
else if(value < Threshold2 )
value = -2;
else
value = 0;
formatterscaled.format( formatter.format(value) + ",");
// System.out.println(" Counter "+count);
// }
}

String save_filename =Save1; // = null?
String restore_filename =null;
String scale_data_filename =Disc; // set this to the path where the output should be stored, e.g. = "C:\\temp\\scaled";
String data_filename =Libsvm; // set this to the path where the input can be get, e.g. = "C:\\temp\\inputdata"
These are the Strings you need to adapt in order that the program can read and write. Save1, Disc, Libsvm are not in your code, so it can only be guessed where they come from.
data_filename and scale_data_filename are required. save_filename seems to be optional and may be set to null.

Related

Getting NullPointerException when dealing with passing String variables [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I'm trying to code a project that deals with a dumb downed version of an excel sheet. One of the commands I am allowing from the user is assigning a value into specific cells in the format of = . i.e A3 = 72.3%. Once it assigns the value to the cell, it then prints out the entire spreadsheet with the updated changes.
I created different classes to represent different types of cells.
Value Cell is a cell that will contain any double value, Percent Cell is a cell that will contain any percentage value, Text Cell is a cell that will contain text.
While I was trying to run my program, I tried assigning a percentage value to a cell. (A2 = 7.25%)
When the program prints out the entire spreadsheet with the newly assigned A2 percentage cell, it's supposed to truncate the decimal from the percentage and just display 7%.
However, I keep getting this error message
Exception in thread "main" java.lang.NullPointerException
at PercentCell.abbreviatedCellText(PercentCell.java:18)
at Spreadsheet.getGridText(Spreadsheet.java:127)
at Spreadsheet.processCommand(Spreadsheet.java:73)
at TextExcel.main(TextExcel.java:20)
This is part of my code that assigns specific cell types depending on what the user inputs:
//assignment command
} else if (command.contains("=")) {
int eqIndex = command.indexOf("=");
if (!command.substring(eqIndex - 1, eqIndex).equals(" ") || !command.substring(eqIndex + 1, eqIndex + 2).equals(" ")) {
return "Formatting Error: please include a space before and after the ="; //error message
} else {
String[] input = command.split(" ", 3);
SpreadsheetLocation cell = new SpreadsheetLocation(input[0]);
int col = cell.getCol();
int row = cell.getRow();
if (col > COLUMNS || row > ROWS) {
return "Error: cell outside of spreadsheet"; //error message
}
//assigning a textcell
if (input[2].contains("\"")) {
String inputValue = input[2].substring(1, input[2].length() - 1);
TextCell textCell = new TextCell(inputValue);
spreadsheet[row][col] = textCell;
//assigning a percent cell
} else if (input[2].contains("%")) {
PercentCell percentCell = new PercentCell(input[2]);
spreadsheet[row][col] = percentCell;
The percent cell extends super class, Real Cell:
public class RealCell implements Cell {
private String fullText;
public RealCell(String input) {
this.fullText = input;
}
//method that returns the display of the abbreviated cell
public String abbreviatedCellText() {
if (fullText.length() > 10) {
return fullText.substring(0, CELLWIDTH);
} else {
String output = fullText;
while(output.length() < CELLWIDTH) {
output += " ";
}
return output;
}
}
//method that returns the actual value in a real cell
public String fullCellText() {
return fullText;
}
//method that parses the user input into a double
public double getDoubleValue() {
return Double.parseDouble(fullText);
}
}
Here is now the problem part of my code, the Percent Cell class:
public class PercentCell extends RealCell {
private String fullText;
public PercentCell(String input) {
super(input);
}
//method that returns the display of the abbreviated cell, truncating the decimal
public String abbreviatedCellText() {
String value = fullText;
if (value.contains(".")) {
int decIndex = fullText.indexOf(".");
value = value.substring(0, decIndex) + "%";
}
if (value.length() > 10) {
return value.substring(0, CELLWIDTH);
} else {
String output = value;
while(output.length() < CELLWIDTH) {
output += " ";
}
return output;
}
}
//method that parses the user input into a double and returns the percent value into a decimal
public double getDoubleValue() {
double decimal = Double.parseDouble(fullText.substring(0, fullText.length() - 1));
return decimal/100;
}
}
How could I fix this error?
If any clarifications regarding my code are needed (because this is not my entire project) please let me know!
public class PercentCell extends RealCell {
public PercentCell(String input) {
super(input);
}
//method that returns the display of the abbreviated cell, truncating the decimal
public String abbreviatedCellText() {
String value = super.fullCellText();
if (value.contains(".")) {
int decIndex = value.indexOf(".");
value = value.substring(0, decIndex) + "%";
}
if (value.length() > 10) {
return value.substring(0, CELLWIDTH);
} else {
String output = value;
while(output.length() < CELLWIDTH) {
output += " ";
}
return output;
}
}
You used fullText field without giving value and fullText value was always null
I think that was the problem, but let me know please if it helps!

Java - read file into array of objects

I am in need of some guidance. I am not sure how to go about reading in the sample text file into an array of objects. I know that the work needs to be in the while loop I have in main. I just do not know what I need to accomplish this.
I understand that I need to read in the file line by line (that's what the while loop is doing), but I don't know how to parse that line into an object in my array.
I know all of you like to see what people have tried before you help, but I honestly don't know what to try. I don't need a hand out, just some guidance.
Sample Text File:
100 3
120 5
646 7
224 9
761 4
Main:
public static void main(String[] args) {
Weight[] arrWeights = new Weight[25];
int count = 0;
JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
int returnValue = jfc.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = jfc.getSelectedFile();
System.out.println(selectedFile.getAbsolutePath());
BufferedReader inputStream = null;
String fileLine;
inputStream = new BufferedReader(new FileReader(selectedFile.getAbsoluteFile()));
System.out.println("Weights:");
// Read one Line using BufferedReader
while ((fileLine = inputStream.readLine()) != null) {
count++;
System.out.println(fileLine);
}
System.out.println("Total entries: " + count);
}
}
Weight Class:
public class Weight {
private int pounds;
private double ounces;
private final int OUNCES_IN_POUNDS = 16;
public Weight(int pounds, double ounces) {
this.pounds = pounds;
this.ounces = ounces;
}
public boolean lessThan(Weight weight) {
return toOunces() < weight.toOunces();
}
public void addTo(Weight weight) {
this.ounces += weight.toOunces();
normalize();
}
public void divide(int divisor) {
if (divisor != 0) {
this.ounces = (this.toOunces() / divisor);
this.pounds = 0;
normalize();
}
}
public String toString() {
return this.pounds + " lbs " + String.format("%.3f", this.ounces) + " oz";
}
private double toOunces() {
return this.pounds * OUNCES_IN_POUNDS + this.ounces;
}
private void normalize() {
if (ounces >=16) {
this.pounds += (int) (this.ounces /OUNCES_IN_POUNDS);
this.ounces = this.ounces % OUNCES_IN_POUNDS;
}
}
}
I don't remember how to do that exactly in Java but I think this general guidance could help you:
In the while loop -
Parse the line you input from the read line using split function, you can use this as reference(first example can do the trick): http://pages.cs.wisc.edu/~hasti/cs302/examples/Parsing/parseString.html
Take the parsed line values, cast them to desired values per your class and create your object.
Append the created object to your list of objects: arrWeights

Use JLine to Complete Multiple Commands on One Line

I was wondering how I could implement an ArgumentCompleter such that if I complete a full and valid command, then it would begin tab completing for a new command.
I would have assumed it could be constructed doing something like this:
final ConsoleReader consoleReader = new ConsoleReader()
final ArgumentCompleter cyclicalArgument = new ArgumentCompleter();
cyclicalArgument.getCompleters().addAll(Arrays.asList(
new StringsCompleter("foo"),
new StringsCompleter("bar"),
cyclicalArgument));
consoleReader.addCompleter(cyclicalArgument);
consoleReader.readLine();
However right now this stops working after tab completeing the first foo bar
Is anyone familiar enough with the library to tell me how I would go about implementing this? Or is there a known way to do this that I am missing? Also this is using JLine2.
That was quite a task :-)
It is handled by the completer you are using. The complete() method of the completer has to use for the search only what comes after the last blank.
If you look for example at the FileNameCompleter of the library: this is not done at all, so you will find no completion, because the completer searches for <input1> <input2> and not only for <input2> :-)
You will have to do your own implementation of a completer that is able to find input2.
Additionally the CompletionHandler has to append what you found to what you already typed.
Here is a basic implementation changing the default FileNameCompleter:
protected int matchFiles(final String buffer, final String translated, final File[] files,
final List<CharSequence> candidates) {
// THIS IS NEW
String[] allWords = translated.split(" ");
String lastWord = allWords[allWords.length - 1];
// the lastWord is used when searching the files now
// ---
if (files == null) {
return -1;
}
int matches = 0;
// first pass: just count the matches
for (File file : files) {
if (file.getAbsolutePath().startsWith(lastWord)) {
matches++;
}
}
for (File file : files) {
if (file.getAbsolutePath().startsWith(lastWord)) {
CharSequence name = file.getName() + (matches == 1 && file.isDirectory() ? this.separator() : " ");
candidates.add(this.render(file, name).toString());
}
}
final int index = buffer.lastIndexOf(this.separator());
return index + this.separator().length();
}
And here the complete()-Method of the CompletionHandler changing the default CandidateListCompletionHandler:
#Override
public boolean complete(final ConsoleReader reader, final List<CharSequence> candidates, final int pos)
throws IOException {
CursorBuffer buf = reader.getCursorBuffer();
// THIS IS NEW
String[] allWords = buf.toString().split(" ");
String firstWords = "";
if (allWords.length > 1) {
for (int i = 0; i < allWords.length - 1; i++) {
firstWords += allWords[i] + " ";
}
}
//-----
// if there is only one completion, then fill in the buffer
if (candidates.size() == 1) {
String value = Ansi.stripAnsi(candidates.get(0).toString());
if (buf.cursor == buf.buffer.length() && this.printSpaceAfterFullCompletion && !value.endsWith(" ")) {
value += " ";
}
// fail if the only candidate is the same as the current buffer
if (value.equals(buf.toString())) {
return false;
}
CandidateListCompletionHandler.setBuffer(reader, firstWords + " " + value, pos);
return true;
} else if (candidates.size() > 1) {
String value = this.getUnambiguousCompletions(candidates);
CandidateListCompletionHandler.setBuffer(reader, value, pos);
}
CandidateListCompletionHandler.printCandidates(reader, candidates);
// redraw the current console buffer
reader.drawLine();
return true;
}

How do I implement HashMap in my code, I am trying to use it as a memory?

So I am working on a PostFix calculator that is used in command line for a class project, and I am having a little trouble on developing a memory for it. I have been told to create a hashMap and I have researched it and understand the basics of it. I have the calculating method working, but what I am having trouble trying to implement a way for the user to declare variables. For example this what the user should be able to do:
> a = 3 5 + 1 -
7
> bee = a 3 *
21
> a bee +
28
> bee 3 %
0
> a = 4
4
> 57
57
> 2 c +
c not found
> mem
a: 4
bee: 21
> exit
As you can see the user can declare variables in the format " ="
My problem is, that I am not really sure how to Implement the hashMap, I have tried doing it by setting the variable name for the hashmap by getting it from an array list, and getting the integer value from it by getting the return value from my compute method, but all I get is this error:
>Exception in thread "main" java.lang.NumberFormatException: For input string: "
Error"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Program6.main(Program6.java:42)
Here is my code currently:
import java.util.*;
import java.io.*;
public class Program6
{
private static HashMap<String,Integer> memory = new HashMap<>();
public static void main(String args[])
{
System.out.println("Servando Hernandez");
System.out.println("RPN command line calculator");
Scanner scan = new Scanner(System.in);
System.out.print(">");
while(scan.hasNextLine())
{
System.out.print("> ");
String a = scan.nextLine();
String b = "quit";
String c = "mem";
String d = "clear";
if(a.equals(b))
{
System.exit(0);
}
else
{
System.out.println(compute(a));
}
System.out.print(">");
List<String> list = new ArrayList<String>();
if(!a.isEmpty())
{
StringTokenizer var = new StringTokenizer(a);
while(var.hasMoreTokens())
{
list.add(var.nextToken());
}
}
int pos = 0;
if (compute(a) != null)
{
pos = Integer.parseInt(compute(a));
}
memory.put(list.get(list.size()-1),pos);
}
}
public static String compute(String input)
{
List<String> processedList = new ArrayList<String>();
if (!input.isEmpty())
{
String myRegex = "[^a-zA-Z]";
StringTokenizer st = new StringTokenizer(input);
while (st.hasMoreTokens())
{
processedList.add(st.nextToken());
processedList.remove(myRegex);
processedList.remove("=");
}
}
else
{
return "Error";
}
Stack<String> tempList = new Stack<String>();
Iterator<String> iter = processedList.iterator();
while (iter.hasNext())
{
String temp = iter.next();
if (temp.matches("[0-9]*"))
{
tempList.push(temp);
}
else if (temp.matches("[*-/+]"))
{
if (temp.equals("*"))
{
int rs = Integer.parseInt(tempList.pop());
int ls = Integer.parseInt(tempList.pop());
int result = ls * rs;
tempList.push("" + result);
}
else if (temp.equals("-"))
{
int rs = Integer.parseInt(tempList.pop());
int ls = Integer.parseInt(tempList.pop());
int result = ls - rs;
tempList.push("" + result);
}
else if (temp.equals("/"))
{
int rs = Integer.parseInt(tempList.pop());
int ls = Integer.parseInt(tempList.pop());
int result = ls / rs;
tempList.push("" + result);
}
else if (temp.equals("+"))
{
int rs = Integer.parseInt(tempList.pop());
int ls = Integer.parseInt(tempList.pop());
int result = ls + rs;
tempList.push("" + result);
}
}
else
{
return "Error";
}
}
return tempList.pop();
}
}
Does anyone know how i can make the hashMap memory on the post fix calculator work to where the user can assign variables and be able to call them back, or a better way to approach this?
Your problem is you are adding "Error" from you else clause in the compute method and then trying to parse it as a int.
public static String compute(String input)
{
List<String> processedList = new ArrayList<String>();
if (!input.isEmpty())
{
String myRegex = "[^a-zA-Z]";
StringTokenizer st = new StringTokenizer(input);
while (st.hasMoreTokens())
{
processedList.add(st.nextToken());
processedList.remove(myRegex);
processedList.remove("=");
}
}
else
{
return "Error"; //-->> problem
}
Parsing it as an int. This point compute(a) will not be null as it has "Error".
Next step you are trying to parse it as an int.
if (compute(a) != null)
{
pos = Integer.parseInt(compute(a));
}
You can change your code as
if (compute(a) != null && !compute(a).equals("Error"))
{
pos = Integer.parseInt(compute(a));
}
Also you should try you put your Integer.parseInt() code in a try catch.
Your HashMap can be used to store the variable names and their values. The key for the map will be the variable name, and the value is the number assigned to it. You currently have Integer but you might want something that handles decimals if you're going to allow things like a = 10 3 /.
In your compute(..) method you expect the input to be of the form var = <calculation> so you should first parse out the variable name which will be the key used in the hashmap memory, and after computing the calculation, store that result with memory.put(var,result);.
When computing the <calculation> part, if a variable name is encountered, look it up to find its value using memory.get(var) and use that value in the computation. With a postfix calculator, you just have to get the 2 values, followed by the operation and perform the math. The result of that is the first value of the next pair to operate on, and so on until you run out of operations and finally assign the result to the variable.

Returning a double from a method

I am currently writing a program that will read through a designated text file that checks the transaction values of each buy/sell/summary and checks the arithmetic such that if the transactions from the buy and sell statements do not equal the total transaction amount that was given in the summary then it outputs an error and closes the program. But currently my method scanMoneyValue has an error that says it's not returning a double, when in fact it is. Is there a different way I should go about returning the values from my method? Here is my code for reference:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class RecurrsionFileChecker {
public static void main(String[] args) {
int result;
//File Chooser Window
JFileChooser chooser = new JFileChooser("/home/nick/workspace/CS 1410-001/src/assignment03");
chooser.setDialogTitle("Please choose a file to be checked");
result = chooser.showOpenDialog(null);
//User Cancelled the chooser
if (result == JFileChooser.CANCEL_OPTION)
return;
File inputfile = chooser.getSelectedFile();
try
{
Scanner in = new Scanner(inputfile);
//Call Method to look at next transaction
scanNextTransaction(in);
}
catch (IOException e)
{
System.out.println("Could not read file: " + inputfile);
}
}
/**
* Returns double if the parameter Scanner has an error that does,
* not match the summary before it.
*
* #param s Any scanner
* #return double if Summaries don't match.
*/
public static double scanNextTransaction(Scanner s)
{
String buy, sell, summary, date;
double amount = 0, referenceValue, total = 0;
summary = s.next();
date = s.next();
referenceValue = scanMoneyValue(s);
while (s.hasNext())
{
if (s.next() == "Buy")
{
date = s.next();
amount = scanMoneyValue(s);
}
if(s.next() == "Sell")
{
date = s.next();
amount = scanMoneyValue(s);
}
if(s.next() == "Summary")
{
amount = scanSubSummary(s);
}
//add the transactions
total = total + amount;
}
return total;
}
public static double scanMoneyValue(Scanner in)
{
String dollar = in.next();
if(dollar.charAt(0) == '$')
{ //convert string to a double
String amount = dollar.substring(1);
double complete = Double.parseDouble(amount);
complete = complete * 100;
return complete;
}
}
public static double scanSubSummary(Scanner sub)
{
String summaryDate, transDate, transType;
int summarySubEntries, count = 0;
double transValue, summaryValue = 0, totalValue = 0, summaryAmount;
summaryDate = sub.next();
summaryAmount = scanMoneyValue(sub);
summarySubEntries = sub.nextInt();
while (count != summarySubEntries)
{
transType = sub.next();
if (transType == "Summary")
{
summaryValue = scanSubSummary(sub);
}
transValue = scanMoneyValue(sub);
totalValue = transValue + totalValue + summaryValue;
count++;
}
if (totalValue != summaryAmount)
{
System.out.print("Summary error on " + summaryDate + ".");
System.out.println("Amount is $" + summaryAmount + ", " + "should be $" + totalValue + ".");
}
return totalValue;
}
}
public static double scanMoneyValue(Scanner in)
{
String dollar = in.next();
if(dollar.charAt(0) == '$')
{ //convert string to a double
String amount = dollar.substring(1);
double complete = Double.parseDouble(amount);
complete = complete * 100;
return complete;
}
}
If the if condition fails then there's no return statement. You have a return inside of the condition but not outside. You'll need to add a return statement at the end, or throw an exception if not having a dollar sign is an error.
Okay, looking at the only relevant part of your code:
public static double scanMoneyValue(Scanner in)
{
String dollar = in.next();
if(dollar.charAt(0) == '$')
{ //convert string to a double
String amount = dollar.substring(1);
double complete = Double.parseDouble(amount);
complete = complete * 100;
return complete;
}
}
You do return a value if dollar starts with a $... but what do you expect to happen if it doesn't start with $? Currently you reach the end of the method without returning anything, which isn't valid.
You should probably throw an exception, if this is unexpected data that you can't actually handle.
Additionally, you shouldn't really use double for currency values anyway, due to the nature of binary floating point types. Consider using BigDecimal instead.
public static double scanMoneyValue(Scanner in)
{
String dollar = in.next();
if(dollar.charAt(0) == '$')
{ //convert string to a double
String amount = dollar.substring(1);
double complete = Double.parseDouble(amount);
complete = complete * 100;
return complete;
}
//NEED RETURN STATEMENT HERE
}
The error you get is because when you write a function all branches of that function must return a value of the correct type. In your case, if the if-statement fails it hits the end of the function without returning anything.
Its better to change it on
public static double scanMoneyValue(Scanner in)
{
String dollar = in.next();
String amount = dollar.replaceAll("[^\\d.]+", "")
double complete = Double.parseDouble(amount);
complete = complete * 100;
return complete;
}
link on explain - Parsing a currency String in java

Categories

Resources