Good day. I am trying to get the code below to write to a txt file. Yet, I cannot get it to. It just prints the code within the ("") on the output section. My goal is to create the text file to store the output data to retrieve later.
public class Charlesshaw3Test {
public static void main(String[] args) throws Exception{
**//checking id command line argument provided
if(args.length==0) {
System.out.println("C:\\Users\\bryon\\Desktop\\Java Programming");
System.exit(1);
}
String fileName = args[0];
BufferedWriter out = null;
try {
FileWriter fstream = new FileWriter(fileName);
out = new BufferedWriter(fstream);
}
catch (IOException ex) {
System.out.println("\nCould not create file: "+ fileName+".");
System.exit(1);
}**
//a) 10 Instances of the violin testing.
CharlesShaw3Tst voilin[] = new CharlesShaw3Tst[10];
for (int i = 0; i < 10; i++) {
out.write("\n\n***Creating new violin object [" + (i + 1) + "]***");
voilin[i] = new CharlesShaw3Tst();
out.write("\nCreated");
//b) tune your instruments,
out.write("\nchecking if tuned?");
out.write("\nVoilin tuned? " + voilin[i].isTuned());
out.write("\nTuning...");
voilin[i].setTuned(true);
out.write("\nVoilin tuned? " + voilin[i].isTuned());
//c) Start playing your instrument,
out.write("\nVoilin playing? " + voilin[i].isPlaying());
out.write("\nVoilin tuned? " + voilin[i].isTuned());
out.write("\nCalling playVoilin method");
voilin[i].playViolin();
out.write("\nVoilin playing? " + voilin[i].isPlaying());
// d) Call your unique method, and
int num = voilin[i].getNumString();
out.write("\nNumber of strings: " + num);
out.write("\nString name: ");
String strings[] = voilin[i].getviolinStrings();
for (int s = 0; s < num; s++) {
out.write(strings[s] + " ");
}
out.write("\n");
//e) Stop playing your instruments.
out.write("\nStopping playing..");
voilin[i].stopViolin();
out.write("\nVoilin playing? " + voilin[i].isPlaying());
out.write("\nStopping tuning..");
voilin[i].stopTuneViolin();
out.write("\nVoilin tuned? " + voilin[i].isTuned());
}
//Close the output stream
out.close();
}
}
Try using FileWriter's append method:
try {
FileWriter writer = new FileWriter(file);
writer.append("Your string");
//Append all strings
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
The previous program it is referring to is:
public class CharlesShaw3Tst {
private final int numString = 5; // number of strings
private final String violinStrings[] = {"E", "B", "G", "D", "A"}; //an array of strings
//fields to determine if the instrument is tuned,
private boolean tuned;
//and if the instrument is currently playing.
private boolean playing;
//A constructor method that set the tuned and currently playing fields to false.
public CharlesShaw3Tst() {
this.tuned = false;
this.playing = false;
}
// Other methods
public boolean isPlaying() {
return playing;
}
public void setPlaying(boolean playing) {
this.playing = playing;
}
public boolean isTuned() {
return tuned;
}
public void setTuned(boolean isTuned) {
this.tuned = isTuned;
}
public void playViolin() {
System.out.println("The violin is now playing.");
playing = true;
}
public void stopViolin() {
System.out.println("The violin is now playing.");
playing = true;
}
public void tuneViolin() {
System.out.println("The violin is tuned.");
tuned = true;
}
public void stopTuneViolin() {
System.out.println("The violin is tuned.");
tuned = false;
}
public int getNumString() {
return this.numString ;
}
public String[] getviolinStrings() {
return violinStrings;
}
}
Related
I have a method to read a text file of five stocks using Scanner and delimiter. I also have a method which should take a double multiplier and an array of stock objects and change the price with that multiplier. The method which reads the stock file functions correctly, however, when I attempt to change the stock objects that have been assigned values with the filereading method, it does not change the price. After I use method updateStocks(), I test stock[1] to see if the value has changed and it has not.
After I run this:
public class Main {
public static void main (String args[]) {
// stock object with which to call methods
Stock theStock = new Stock("", "", 0);
// this array holds the stocks to be read
Stock[] stocks = new Stock[100];
// here is the multiplier I am attempting to use
double multiplier = 1/3;
// first I read in the stocks file
theStock.readStocksWithScanner(stocks);
// then I call the updateStockPrices method
theStock.updateStockPrices(multiplier,stocks);
// lastly, I test to see if the method has functioned correctly
System.out.println(stocks[1]);
}
}
This is my output:
Apple AAPLE 152.70
Alphabet GOOGLE 873.96
IBM IBM 194.37
Microsoft MSFT 65.67
Oracle ORCLE 62.82
Company name: Apple Stock symbol: AAPLE Stock Price: 152.7
Press any key to continue . . .
Here is the method updateStockPrices:
// this is the method which does not seem to function as intended
public void updateStockPrices(double multiplier, Stock[] objects)
{
// I loop to the length of the array in the parameter
for(int i = 1; i < objects.length; i++)
{
// try to manipulate the stock
try{
double subtractThis = stocks[i].getPrice() * multiplier;
objects[i].setPrice(stocks[i].getPrice() - subtractThis);
}// and catch any null objects
catch(NullPointerException e){
// if null I then increment the counter
i++;}
// Is code missing in order for this to function as intended? or have I made a mistake?
}
}
and here is stocks.java:
import java.util.Scanner ;
import java.util.InputMismatchException ;
import java.io.FileInputStream ;
import java.io.IOException ;
import java.io.FileNotFoundException ;
import java.io.PrintWriter ;
public class Stock {
private static final double MULTIPLIER = (1/3);
public static final String FILE_NAME = "stocks1.txt";
public String newFile = "stocks2.txt";
public static final String FORMAT = "%-10s%6s\t%.2f%n";
private PrintWriter writer = null;
private String name = "";
private String symbol = "";
private double price = 0;
protected Stock stocks[] = new Stock[100];
FileInputStream inputStream = null;
String workingDirectory = System.getProperty("user.dir");
String absolutePath = workingDirectory + "\\" + FILE_NAME;
public Stock(String aName, String aSymbol, double aPrice)
{
this.name = aName;
this.symbol = aSymbol;
this.price = aPrice;
}
// the fileReading method reads the stocks in
public void readStocksWithScanner(Stock[] stocks)
{
this.stocks = stocks;
String workingDirectory = System.getProperty("user.dir");
String absolutePath = workingDirectory + "\\" + FILE_NAME;
FileInputStream inputStream = null;
try{
inputStream = new FileInputStream(absolutePath);
}
catch (FileNotFoundException e)
{
System.out.println("File not found: " + FILE_NAME);
System.out.println("Exiting program.");
System.exit(0) ;
}
Scanner inputFile = new Scanner(inputStream);
int lineNumber = 1;
try{
while(inputFile.hasNextLine())
{
inputFile.useDelimiter(",");
String name = inputFile.next();
inputFile.useDelimiter(",");
String symbol = inputFile.next();
inputFile.useDelimiter("[,\\s]") ;
Double thePrice = inputFile.nextDouble();
inputFile.nextLine();
// here the stocks are given the values found in the text file and initialized above
stocks[lineNumber] = new Stock(name, symbol, thePrice);
// I print them out using a format constant, in order to ensure the method has functioned correcly
System.out.printf(FORMAT, name, symbol, thePrice);
// then I increment the lineNumber
lineNumber++;
}
// I close the stream and should be left with a partially filled array of stock items
inputStream.close();
}catch (IOException e) {
System.out.println("Error reading line " + lineNumber + " from file " + FILE_NAME) ;
System.exit(0) ;
}
catch(InputMismatchException e) {
System.out.println("Couldn't convert price to a number on line " + lineNumber) ;
System.exit(0) ;}
}
public void setName(String name)
{
this.name = name;
}
public void setSymbol(String symbol)
{
this.symbol = symbol;
}
public void setPrice(double aPrice)
{
this.price = aPrice;
}
public String getName()
{
return name;
}
public String getSymbol()
{
return symbol;
}
public double getPrice()
{
return price;
}
public boolean equals(Object other)
{
if(other.getClass() != getClass() || other == null )
{
return false;
}
Stock stock = (Stock) other;
{
if(stock.getName() == getName() && stock.getSymbol() == getSymbol() && stock.getPrice() == getPrice())
{
return true;
}
return false;
}
}
public String toString()
{
return "Company name: " + getName() + " Stock symbol: " + getSymbol() + " Stock Price: " + getPrice();
}
// this is the method which does not seem to function as intended
public void updateStockPrices(double multiplier, Stock[] objects)
{
// I loop to the length of the array in the parameter
for(int i = 1; i < objects.length; i++)
{
// try to manipulate the stock
try{
double subtractThis = stocks[i].getPrice() * multiplier;
objects[i].setPrice(stocks[i].getPrice() - subtractThis);
}// and catch any null objects
catch(NullPointerException e){
// if null I then increment the counter
i++;}
// Is code missing in order for this to function as intended? or have I made a mistake?
}
}
public void createStocks(int stockAmount)
{
Stock[] stocks = new Stock[stockAmount];
}
public void writeStocks(String fileName, Stock[] objects)
{
try{
writer = new PrintWriter(fileName);
}
catch(FileNotFoundException e){
System.out.println("Couldn't create file " + fileName);
System.exit(0);
}
for(Stock s: objects)
{
writer.printf(FORMAT, getName(), getSymbol(), getPrice());
if(objects == null)
writer.close() ;
}
}
public Stock[] getStocks()
{
return stocks;
}
}
simple test
double multiplier = 1/3;
System.out.println(multiplier);
compared to
double multiplier = 1/3f;
System.out.println(multiplier);
Many of you have can help me with this question. I went through many question answers on stackoverflow, but in someway the code which I wrote doesnt seem to work the way I want it to work.
Any help will be appreciated.
I also came across this excellent article http://blog.bdoughan.com/2010/09/jaxb-collection-properties.html and it explained to me a lot of things.
I tried implementing it but not getting the required format of xml. Any help will be much appreciated.
Thank you.
Below I am posting the code :
There are 2 classes in my program:
DSC.java and Identity.java , The former class sets the values by calling the get/set methods in the Identity class.
::::::::::Identity.java::::::::::::
#XmlRootElement(name="LabbuddyArray")
public class Identity {
public String toString()
{
return "DSC_XML_OUTPUT [Company_name=" + company_name + ", Model_Number=" + model_number + ", Serial_Number=" + serial_number + ", New_BIAS=" + new_bias +", New_TEMP=" + new_temp + "]";
}
//DECLARE VARIABLES
String company_name;
String model_number;
String serial_number;
String port_number;
float photo_current;
float actual_bias;
float new_bias;
float actual_temp;
float new_temp;
List<String> slots;
public Identity(){}
//DECLARING CLASSES FOR XML FORMATTING
//GETTING AND SETTING SLOTS TO XML
#XmlElementWrapper
#XmlElement(name="slot")
public List<String> getSlots (){
return slots;
}
public void setSlots (List<String> slots){
this.slots = slots;
}
public String getIdentityCompanyName() {
return company_name;
}
#XmlElement(name="setIdentityCompanyName")
public void setIdentityCompanyName(String identity_company_name) {
this.company_name = identity_company_name;
}
//GETTING AND SETTING MODEL_NUMBER TO XML
public String getIdentityModelNumber() {
return model_number;
}
#XmlElement(name="setIdentityModelNumber")
public void setIdentityModelNumber(String model_number) {
this.model_number = model_number;
}
//GETTING AND SETTING SERIAL_NUMBER TO XML
public String getIdentitySerialNumber() {
return serial_number;
}
#XmlElement(name="setIdentitySerialNumber")
public void setIdentitySerialNumber(String serial_number) {
this.serial_number = serial_number;
}
//GETTING AND SETTING PORT_NUMBER TO XML
public String getIdentityPortNumber() {
return port_number;
}
#XmlElement (name="setIdentityPortNumber")
public void setIdentityPortNumber(String port_number) {
this.port_number = port_number;
}
//GETTING AND SETTING PHOTOCURRENT TO XML
public float getMonitorPhotoCurrent() {
return photo_current;
}
#XmlElement(name="setMonitorPhotoCurrent")
public void setMonitorPhotoCurrent(float photo_current) {
this.photo_current = photo_current;
}
//GETTING AND SETTING BIAS TO XML
//ACTUAL BIAS (READ)
public float getControlActualBias() {
return actual_bias;
}
#XmlElement (name="setControlActualBias")
public void setControlActualBias(float actual_bias) {
this.actual_bias = actual_bias;
}
//NEW BIAS (WRITE)
public float getControlNewBias(){
return new_bias;
}
#XmlElement (name="setControlNewBias")
public void setControlNewBias(float new_bias){
this.new_bias = new_bias;
}
//GETTING AND SETTING TEMP TO XML
//ACTUAL TEMP (READ)
public float getControlActualTemp() {
return actual_temp;
}
#XmlElement (name="setControlActualTemp")
public void setControlActualTemp(float actual_temp) {
this.actual_temp = actual_temp;
}
//NEW TEMP (WRITE)
public float getControlNewTemp(){
return new_temp;
}
#XmlElement(name ="setControlNewTemp")
public void setControlNewTemp(float new_temp){
this.new_temp = new_temp;
}
}
:::::::::::DSC.java::::::::::::
public class Dsc {
public static void main(String[] args) throws InterruptedException {
//INITIALIZING SCANNER TO TAKE INPUTS
Scanner input = new Scanner(System.in);
//CALLING ALL FUNCTIONS
Identity identity = new Identity();
List<String> strings = new ArrayList<String>(2);
strings.add("1");
identity.setSlots(strings);
//CREATING SERIAL PORT OBJECT
SerialPort serialPort = new SerialPort("COM4");
//GETTING SERIALPORTS
String[] portNames = SerialPortList.getPortNames();
for(int i = 0; i < portNames.length; i++)
{
System.out.println("Port Available on this machine: " +portNames[i]);
}
identity.setIdentityPortNumber("COM4");
//STARTING TRY BLOCK TO CATCH ERRORS THROUGHOUT THE EXECUTION
try
{
//OPENING PORT AND ASSIGNING PARAMETERS FOR COMMUNICATION
System.out.println("Port opened: " + serialPort.openPort());
System.out.println("Params setted: " + serialPort.setParams(57600, 8, 1, 0));
System.out.println("--------------------------------------------------------");
//IDENTIFYING THE COMPANY NAME ; MODEL NUMBER ; SERIAL NUMBER ; PORT NUMBER
System.out.println("Passing *IDN? to identify the Device: " +serialPort.writeString("*IDN? \n"));
Thread.sleep(500);
String str = serialPort.readString();
System.out.println("The Device ID is: " +str);
String[] deviceid = str.split(",");
System.out.println("Company :" + deviceid[0]);
identity.setIdentityCompanyName(deviceid[0]);
System.out.println("Model Number :" + deviceid[1]);
identity.setIdentityModelNumber(deviceid[1]);
System.out.println("Serial Number :" + deviceid[2]);
identity.setIdentitySerialNumber(deviceid[2]);
System.out.println("--------------------------------------------------------");
//IDENTIFYING THE PHOTOCURRENT
System.out.println("Passing MEAS:IDC? to identify the Photocurrent: " +serialPort.writeString("MEAS:IDC? \n"));
Thread.sleep(500);
String str1 = serialPort.readString();
System.out.println("The Photocurrent is :" +str1);
float photoCurrent = Float.parseFloat(str1);
identity.setMonitorPhotoCurrent(photoCurrent);
System.out.println("--------------------------------------------------------");
//IDENTIFYING THE ACTUAL BIAS
System.out.println("Passing MEAS:BIAS? to identify the Actual BIAS: " +serialPort.writeString("MEAS:BIAS? \n"));
Thread.sleep(500);
String str2 = serialPort.readString();
System.out.println("The Actual BIAS is :" +str2);
float control_actualBias = Float.parseFloat(str2);
identity.setControlActualBias(control_actualBias);
System.out.println("--------------------------------------------------------");
//SETTING THE BIAS
System.out.println("Set the Bias to ?");
float setBias = input.nextFloat();
System.out.println("Setting the user input BIAS to " +setBias +": " +serialPort.writeString("INP:BIAS " +setBias +"\n" ));
Thread.sleep(500);
identity.setControlNewBias(setBias);
System.out.println("--------------------------------------------------------");
//IDENTIFYING THE ACTUAL TEMPERATURE
System.out.println("Passing MEAS:TEMP? to identify the Temperature: " +serialPort.writeString("MEAS:TEMP? \n"));
Thread.sleep(500);
String str3 = serialPort.readString();
System.out.println("The Actual TEMP is: " +str3);
float actualTemp = Float.parseFloat(str3);
identity.setControlActualTemp(actualTemp);
System.out.println("--------------------------------------------------------");
//SETTING THE TEMPERATURE
System.out.println("Set the new TEMP to ?");
float setTemp = input.nextFloat();
System.out.println("Setting the user input TEMP to " +setTemp +": " +serialPort.writeString("INP:TEMP " +setTemp +"\n" ));
Thread.sleep(500);
identity.setControlNewTemp(setTemp);
System.out.println("--------------------------------------------------------");
}
catch (SerialPortException ex)
{
System.out.println(ex);
}
//STARTING THE JAXBCONTEXT & JAXBMARSHALLER CODE TO WRITE OUTPUT IN XML FILE
try
{
File file = new File("C:\\xampp\\htdocs\\StateMachine.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Identity.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(identity, file);
jaxbMarshaller.marshal(identity, System.out);
}
catch (JAXBException e)
{
e.printStackTrace();
}
}
}
:::::::: Current XML output ::::::::
<LabbuddyArray>
<setControlActualBias>5.999</setControlActualBias>
<setControlActualTemp>21.9</setControlActualTemp>
<setControlNewBias>5.0</setControlNewBias>
<setControlNewTemp>23.0</setControlNewTemp>
<setIdentityCompanyName>DSC</setIdentityCompanyName>
<setIdentityModelNumber>HLPD Lab Buddy</setIdentityModelNumber>
<setIdentityPortNumber>COM4</setIdentityPortNumber>
<setIdentitySerialNumber>50311602</setIdentitySerialNumber>
<setMonitorPhotoCurrent>0.0</setMonitorPhotoCurrent>
<slots>
<slot>1</slot>
</slots>
</LabbuddyArray>
::::::Required XML OUTPUT::::::
<LabbuddyArray>
<slot1>
<setControlActualBias></setControlActualBias>
<setControlActualTemp></setControlActualTemp>
<setControlNewBias></setControlNewBias>
<setControlNewTemp></setControlNewTemp>
<setIdentityCompanyName></setIdentityCompanyName>
<setIdentityModelNumber></setIdentityModelNumber>
<setIdentityPortNumber></setIdentityPortNumber>
<setIdentitySerialNumber></setIdentitySerialNumber>
<setMonitorPhotoCurrent></setMonitorPhotoCurrent>
</slot1>
<slot2>
<setControlActualBias></setControlActualBias>
<setControlActualTemp></setControlActualTemp>
<setControlNewBias></setControlNewBias>
<setControlNewTemp></setControlNewTemp>
<setIdentityCompanyName></setIdentityCompanyName>
<setIdentityModelNumber></setIdentityModelNumber>
<setIdentityPortNumber></setIdentityPortNumber>
<setIdentitySerialNumber></setIdentitySerialNumber>
<setMonitorPhotoCurrent></setMonitorPhotoCurrent>
</slot2>
</LabbuddyArray>
Then you should have something like this...
#XmlRootElement(name="LabbuddyArray")
public class Identity {
List<Slots> slots;
#XmlElement(name="slot")
public List<Slots> getSlots() {
return slots;
}
public void setSlots(List<Slots> slots) {
this.slots = slots;
}
}
Create a class 'Slots', copy all the elements and mapping to it.
And in the Dsc class populate the values as required.
Identity identity = new Identity();
List<Slots> slots = new ArrayList<Slots>();
Slots slot = new Slots();
slot.setControlActualBias(Float.valueOf("1.23"));
slots.add(slot);
slot = new Slots();
slot.setControlActualBias(Float.valueOf("1.24"));
slots.add(slot);
identity.setSlots(slots);
This will yield you the response similar to the one below.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<LabbuddyArray>
<slot>
<setControlActualBias>1.23</setControlActualBias>
<setControlActualTemp>0.0</setControlActualTemp>
<setControlNewBias>0.0</setControlNewBias>
<setControlNewTemp>0.0</setControlNewTemp>
<setMonitorPhotoCurrent>0.0</setMonitorPhotoCurrent>
</slot>
<slot>
<setControlActualBias>1.24</setControlActualBias>
<setControlActualTemp>0.0</setControlActualTemp>
<setControlNewBias>0.0</setControlNewBias>
<setControlNewTemp>0.0</setControlNewTemp>
<setMonitorPhotoCurrent>0.0</setMonitorPhotoCurrent>
</slot>
</LabbuddyArray>
I am trying to use I/O to give a report on the stock that I need (if the stock is below 8).
It tells me it requires an int for myShop.listLowStockToFile());; when I add a number it tells me that 'void is not allowed here'. How can I fix this?
public void listLowStockToFile(int threshhold)
{
System.out.println("****The Stock that is getting low is: " + " Minimum " +threshhold + " Report for Bob Shaw****\n");
for (Item nextItem : items)
{
if(nextItem.getNuminStock() < threshhold)
{
System.out.println(nextItem);
}
}
}
public class Report {
public static void main(String[] args) {
Shop myShop = new Shop();
CD cd1 = new CD("Abba Gold", "Abba", 15);
myShop.addItem(cd1);
Game game1 = new Game("Chess", 2, 39.95);
myShop.addItem(game1);
ElectronicGame eg1 = new ElectronicGame("Shrek", "PS2", 1, 79.50);
myShop.addItem(eg1);
ElectronicGame eg2 = new ElectronicGame("Doom", "PC", 2, 30.20);
myShop.addItem(eg2);
ElectronicGame eg3 = new ElectronicGame("AFL", "PS2", 2, 49.95);
myShop.addItem(eg3);
cd1.receiveStock(3);
game1.receiveStock(5);
eg1.receiveStock(10);
eg2.receiveStock(1);
cd1.receiveStock(7);
cd1.sellCopy(true);
cd1.sellCopy(true);
eg2.sellCopy(true);
myShop.listItems();
myShop.listLowStockToFile(8);
myShop.listGamesByPlatform("PS2");
myShop.calcTotalSales();
Game game2 = new Game("Chess", 2, 39.95);
myShop.addItem(game2);
eg2.sellCopy(false);
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("LowStock.txt"));
writer.write("Report dated" + new Date() + "\n");
writer.write(myShop.listLowStockToFile()); // This line.
writer.close();
System.out.println("Report finished");
} catch (Exception ex) {
System.out.println("File I/O error" + ex);
}
}
}
You need listLowStockToFile to return a String:
public String listLowStockToFile(int threshhold) {
String rtn = "****The Stock that is getting low is: " + " Minimum " +threshhold + " Report for Bob Shaw****\n";
for (Item nextItem : items) {
if(nextItem.getNuminStock() < threshhold) {
rtn += nextItem.toString() + "\n";
}
}
System.out.print(rtn);
return rtn;
}
The reason is that BufferedWritter.write takes a String as an argument.
As the topic states im trying to get a specific string that is usually auto generated into the same string and it seems to work because the temp file is created and the string is replaced with "" but its seems that there is an IOException when it comes to renaming to original when deleting , help please?
import java.io.*;
import java.util.Scanner;
/**
* Main class to test the Road and Settlement classes
*
* #author Chris Loftus (add your name and change version number/date)
* #version 1.0 (24th February 2016)
*
*/
public class Application {
private Scanner scan;
private Map map;
private static int setting;
public Application() {
scan = new Scanner(System.in);
map = new Map();
}
private void runMenu() {
setting = scan.nextInt();
scan.nextLine();
}
// STEP 1: ADD PRIVATE UTILITY MENTHODS HERE. askForRoadClassifier, save and
// load provided
private Classification askForRoadClassifier() {
Classification result = null;
boolean valid;
do {
valid = false;
System.out.print("Enter a road classification: ");
for (Classification cls : Classification.values()) {
System.out.print(cls + " ");
}
String choice = scan.nextLine().toUpperCase();
try {
result = Classification.valueOf(choice);
valid = true;
} catch (IllegalArgumentException iae) {
System.out.println(choice + " is not one of the options. Try again.");
}
} while (!valid);
return result;
}
private void deleteSettlement() {
String name;
int p;
SettlementType newSetK = SettlementType.CITY;
int set;
System.out.println("Please type in the name of the settlement");
name = scan.nextLine();
System.out.println("Please type in the population of the settlment");
p = scan.nextInt();
scan.nextLine();
System.out.println("Please type in the number of the type of settlement .");
System.out.println("1: Hamlet");
System.out.println("2: Village");
System.out.println("3: Town");
System.out.println("4: City");
set = scan.nextInt();
scan.nextLine();
if (set == 1) {
newSetK = SettlementType.HAMLET;
}
if (set == 2) {
newSetK = SettlementType.VILLAGE;
}
if (set == 3) {
newSetK = SettlementType.TOWN;
}
if (set == 4) {
newSetK = SettlementType.CITY;
}
String generatedResult = "Name: " + name + " Population: " + p + " SettlementType " + newSetK;
String status = searchAndDestroy(generatedResult);
}
private String searchAndDestroy(String delete) {
File file = new File("C:\\Users\\Pikachu\\workspace\\MiniAssignment2\\settlements.txt");
try {
File temp = File.createTempFile("settlement", ".txt", file.getParentFile());
String charset = "UTF-8";
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
for (String line; (line = reader.readLine()) != null;) {
line = line.replace(delete, "");
writer.println(line);
}
System.out.println("Deletion complete");
reader.close();
writer.close();
file.delete();
temp.renameTo(file);
}
catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
System.out.println("Sorry! Can't do that! 1");
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("Sorry! Can't do that! 2");
}
}
catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Sorry! Can't do that! , IO Exception error incurred 3");
}
return null;
}
private void save() {
map.save();
}
private void load() {
map.load();
}
public void addSettlement() {
String name;
int p;
SettlementType newSetK = SettlementType.CITY;
int set;
System.out.println("Please type in the name of the settlement");
name = scan.nextLine();
System.out.println("Please type in the population of the settlment");
p = scan.nextInt();
scan.nextLine();
System.out.println("Please type in the number of the type of settlement .");
System.out.println("1: Hamlet");
System.out.println("2: Village");
System.out.println("3: Town");
System.out.println("4: City");
set = scan.nextInt();
scan.nextLine();
if (set == 1) {
newSetK = SettlementType.HAMLET;
}
if (set == 2) {
newSetK = SettlementType.VILLAGE;
}
if (set == 3) {
newSetK = SettlementType.TOWN;
}
if (set == 4) {
newSetK = SettlementType.CITY;
}
new Settlement(name, newSetK, p);
}
private void printMenu() {
System.out.println("Please type in the number of the action that you would like to perform");
System.out.println("1: Create Settlement");
System.out.println("2: Delete Settlement");
System.out.println("3: Create Road");
System.out.println("4: Delete Road");
System.out.println("5:Display Map");
System.out.println("6:Save Map");
}
public static void main(String args[]) {
Application app = new Application();
app.printMenu();
app.runMenu();
System.out.println(setting);
if (setting == 1) {
app.addSettlement();
}
if (setting == 2) {
app.deleteSettlement();
}
app.load();
app.runMenu();
app.save();
}
}
I checked if it was deletable (file.delete throws a boolean exception) so I tried deleting it directly via windows and apparently it was being used by java so I assumed eclipsed glitch and upon closing and booting up eclipse again it worked..... well... that was rather anti-climactic .... Thank you so much for the discussion , I would definitely never had figured it out if not for the discussion :D <3 You are all in my heart
I'm taking Java Introductory Programming class and currently i'm working on a final project. The assignment description can be found here link
I'm having hard time with accomplishing this "Write the output from your Instrument class methods to a text file that a user entered from the command line arguments (e.g. java Mynamep3tst myfilename.txt)." Here's some of my code:
import java.io.*;
public class Test{
public static void main(String[] args) {
String outputFile = "";
if (0 < args.length) {
outputFile = args[0];
System.out.println("This program will write output to this file: " + outputFile + "\n");
try {
File file = new File(outputFile);
PrintWriter output = new PrintWriter(outputFile);
output.println("hello"); //to check if ir prints anything
Violin[] simpleViolin = new Violin[5];
//Create 5 violin objects
for (int i = 0; i < simpleViolin.length; i++){
simpleViolin[i] = new Violin();
}
output.println("\nLet's tune " + Violin.getNumberOfViolins() + " violins.");
for(int i = 0; i < simpleViolin.length; i++){
output.print(i + 1);
simpleViolin[i].tuneOn();
}
output.println("\nNow let's start playing " + Violin.getNumberOfViolins() + " violins.");
for(int i = 0; i < simpleViolin.length; i++){
output.print(i + 1);
simpleViolin[i].startPlaying();
}
output.println("\nIt looks like " + Violin.getNumberOfViolins() + " violins have untuned.");
for(int i = 0; i < simpleViolin.length; i++){
output.print(i + 1);
simpleViolin[i].tuneOff();
}
output.println("\nThis music is terrible! Let's stop it!");
for(int i = 0; i < simpleViolin.length; i++){
output.print(i + 1);
simpleViolin[i].stopPlaying();
}
output.close();
}
catch (IOException io){
System.out.println("Sorry that file is not found " + io);
}
}//end if
}//end main
}//end Test
class Violin{
private final int numberOfStrings = 4;
private final char[] stringNames = {'E', 'A', 'D', 'G'};
private boolean isTuned = false;
private boolean isPlaying = false;
private static int numberOfViolins = 0;
private PrintWriter output;
public Violin(){
numberOfViolins++;
}
public void startPlaying() {
isPlaying = true;
System.out.println(" violin is now playing.");
}
public void stopPlaying() {
isPlaying = false;
System.out.println(" violin has stopped playing.");
}
public void tuneOn() {
isTuned = true;
System.out.println(" violin is now tuned.");
}
public void tuneOff() {
isTuned = false;
System.out.println(" violin is untuned.");
}
static int getNumberOfViolins(){
return numberOfViolins;
}
}//end class Violin
So my question is how do I make my Violin class methods to print to a user specified file?
When you create your Violin object you can pass the output as a reference on the constructor so inside the violin you will use output instead of System.out.println.
Change the Violoin constructor to:
public Violin (PrintStream output){
this.output = output;
}
And then just use the outpu inside the violin.