how to implement a linked list properly using java - java

I am working in a project with linked list (JAVA) but I am not being able to figure out how to insert the person. How could I get the switch to work? Or should I use something else? I also thought about creating a class outside the main method and just call it but it did not work as well. Any help will be much appreciate
public void listOfPeople() { // Beginning of the method listOfPeople where shows the employees
// *** instance the person object ad loading your variables
Personqueue p1 = new Personqueue(); //saving the employee in a variable???
p1.setFname("John");
p1.setLname("Smith");
p1.setDOA(15);
p1.setPassportN(306589);
p1.setNumber(1);
vectorObj.add(p1); // add the employee in a vector
Personqueue p2 = new Personqueue(); //saving the employee in a variable???
p1.setFname("Paul");
p1.setLname("Clooney");
p1.setDOA(5);
p1.setPassportN(30614584);
p1.setNumber(2);
vectorObj.add(p2); // add the employee in a vector
}
public void ascendingOrder(Vector<Personqueue> vector) { // bubble sort method to order the vector
int j;
boolean flag = true; // set flag to true to begin first pass
Personqueue temp; // holding the variable temporarily
while (flag) {
flag = false; // set flag to false awaiting a possible swap
for (j = 0; j < vector.size() - 1; j++) {
if (vector.get(j).getNumber() > vector.get(j + 1).getNumber()) {
temp = vector.get(j); // swap elements
vector.set(j, vector.get(j + 1));
vector.set(j + 1, temp);
flag = true; // shows a swap occurred
}
}
}
}
public void newPerson(int positionPerson) { // beginning of newPerson method
String Option = null; // declaration of local variables that are used only in this method and don't use too much space
Personqueue p = new Personqueue(); //instead of setting it to null, here we are calling
// a constructor which was declared in Personqueue class.
// switch (positionPerson) {
// case 1: // insert a person at the start of the queue
// // p = new QueueStart();
// break; // executes in order to end the switch in case one of the options is valid
// case 2: // insert a person at a chosen point in the queue
// // p = new ChoosePosition();
// case 3: // insert a person at the end of the queue
// // p = new EndQueue();
// break;
// default:
// System.out.println("Invalid Option!!!"); // in case the option is not one of the cases above, print this...
// return; // return to the do/while loop in Principal method
// }
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Name:"); // user input
try {
Option = br.readLine();
String name = Option;
p.setFname(name);
} catch (IOException e) {
System.out.println(e);
}
System.out.println("Surname:"); // user input
try {
Option = br.readLine();
String lname = Option;
p.setLname(lname);
} catch (IOException e) {
System.out.println(e);
}
System.out.println("Date Of Arrival: "); // user input
try {
Option = br.readLine();
int doa = Integer.parseInt(Option); // use parseInt in order to convert Integer to String to be read by BufferedReader.
p.setDOA(doa);
} catch (IOException e) {
System.out.println(e);
}
System.out.println("Passport Number:"); // user input
try {
Option = br.readLine();
int pn = Integer.parseInt(Option);
p.setPassportN(pn);
} catch (IOException e) {
System.out.println(e);
}
System.out.println("Number:"); // user input
try {
Option = br.readLine();
int no = Integer.parseInt(Option);
p.setNumber(no);
} catch (IOException e) {
System.out.println(e);
}
vectorObj.addElement(p); // save all the data in the vector
System.out.print("Saving Person :" + p.getFname()); // print to the user the name's been saved
try {
for (int i = 0; i < 6; i++) {
System.out.print(".");
Thread.sleep(300); // suspend the "." execution for a specified period.
}
} catch (InterruptedException e) { // exception p o method thread // catch for thread above
e.printStackTrace();
}
System.out.println();
System.out.println("Person: " + p.getFname() + " is saved!!!");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} // end of the Method newPerson

Check your variables in listOfPeople(...), p2 was not used correctly.
Take a look at Example of LinkedList in Java

Related

Java creating a temp file , deleting a specific string and rename to original

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

for loop with ArrayList in java

i got a Productclass stored in ArrayList myValues.
I want to go trough each xth ( for example each 3th) element and have the user
add some Integer values to that class.
In my for(...) he tells me: The left-hand side of an assignment must be a variable. I wonder if i messed up some of the .get(j) or if i have to synchronize my methods so that the size wont change ( there is no multi-threading but maybe thats why i get an error?
) or the solution is more simple.
Thx
public void prioPerProduct (){
System.out.println("");
System.out.println("Please enter storing and upgrading cost:");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
int storingCost = 0;
int ruestCost = 0;
int countRes = countRessources;
int sizemyValues = myValues.size();
for(int j = 0; j < sizemyValues; j = j+countRes){
System.out.println("Please enter storingcost " + myValues.get(j).getProduct() +":" );
try {
storingCost = Integer.valueOf(br.readLine());
} catch (NumberFormatException e) {
System.out.println("No number entered");
e.printStackTrace();
} catch (IOException e) {
System.out.println("No number entered");
e.printStackTrace();
}
System.out.println("Please enter upgradingcost " + myValues.get(j).getProduct() +":" );
try {
ruestCost = Integer.valueOf(br.readLine());
} catch (NumberFormatException e) {
System.out.println("No number entered");
e.printStackTrace();
} catch (IOException e) {
System.out.println("No number entered");
e.printStackTrace();
}
myValues.get(j).setstoringCost(storingCost);
myValues.get(j).setupgradingCost(ruestCost);
}
}
The left-hand side of an assignment must be a variable is generally caused by something like this:
methodCall() = somvalue...
The left hand side must be a variable rather than a method call. Your code looks fine in this regard.
The code where you declare your model class and a full stack trace are more helpful.
Use the set method to change the value of an object inside of an ArrayList.
myValues.set(j,myValues.get().setstoringCost(storingCost));
myValues.set(j,myValues.get().setupgradingCost(ruestCost));

print out from switch statement java

here is a piece of code:
class Main {
public static void main(String[] args) {
try {
CLI.parse (args, new String[0]);
InputStream inputStream = args.length == 0 ?
System.in : new java.io.FileInputStream(CLI.infile);
ANTLRInputStream antlrIOS = new ANTLRInputStream(inputStream);
if (CLI.target == CLI.SCAN || CLI.target == CLI.DEFAULT)
{
DecafScanner lexer = new DecafScanner(antlrIOS);
Token token;
boolean done = false;
while (!done)
{
try
{
for (token=lexer.nextToken();
token.getType()!=Token.EOF; token=lexer.nextToken())
{
String type = "";
String text = token.getText();
switch (token.getType())
{
case DecafScanner.ID:
type = " CHARLITERAL";
break;
}
System.out.println (token.getLine() + type + " " + text);
}
done = true;
} catch(Exception e) {
// print the error:
System.out.println(CLI.infile+" "+e);
}
}
}
else if (CLI.target == CLI.PARSE)
{
DecafScanner lexer = new DecafScanner(antlrIOS);
CommonTokenStream tokens = new CommonTokenStream(lexer);
DecafParser parser = new DecafParser (tokens);
parser.program();
}
} catch(Exception e) {
// print the error:
System.out.println(CLI.infile+" "+e);
}
}
}
It prints out as it is but somehow it does not print the type out only the default value of it which is an empty string. How can I make it to print out from the switch statement?
Thanks!
Try debugging.
Try printing the value from within the switch section, to see if you ever get into it.
Try replacing the switch with a simple "==" to see if you ever get "token.getType() == DecafScanner.ID"
General suggestion - move the definition of "type" and "next" outside the loop to avoid recreating them again and again.

Why does a integer, after put into an array, change values?

SOLVED IT
I've written a program that loads Strings after an equal sign, and has it count how many times its done this. After counting, I tell it to tell me how large the int is. The value I'm looking for is 3, and it tells me, 3. I then change it to an String, the value stays three. Then, I put it into an 4d array, and It tells me the value is 2. What happened?
The Code:
int times=0;
else if (list.equals("Weapon")) {//If the word weapon is before the =
weapon = value; //take the string after the = and put it into String weapon
troopStats[times][1][weaponTimes][0] = weapon;
weaponTimes++;
System.out.println(weaponTimes+"weapontimes"+times);
}
weaponTimesStr = Integer.toString(weaponTimes);
System.out.println(weaponTimesStr+"string");
troopStats[times][1][0][1] = weaponTimesStr;
System.out.println(troopStats[times][1][0][1]+"InArray");
times++
//loops
The Output:
3weapontimes //Counted the equals sign 3 times, Note that this is from the part of the
omitted code
3string // Changed the integer to a string and got 3
2InArray // Put it into an array, and got 2 back
What Is going on?
(I know that I could just add 1 to the value, but I want to use this code for a unknown number of things later on)
To help, I've posted the entire code:
public class TroopLoader {
static String[][][][] troopStats;
static int times = 0;
static int weaponTimes = 0;
static int armorTimes = 0;
static int animalTimes = 0;
static String weaponTimesStr;
static String armorTimesStr;
static String animalTimesStr;
static String troop;
static String weapon;
static String armor;
static String animal;
static String speed;
static int total = 0;
/*
* [][][]
*
* [total number of troops (total)]
*
* [stats] 0= name 1= weapon 2= armor 3= animal 4= speed
*
* [different things within stat]
*/
public void readTroop() {
File file = new File("resources/objects/troops.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
// repeat until all lines is read
while ((text = reader.readLine()) != null) {
StringTokenizer troops = new StringTokenizer(text, "=");
if (troops.countTokens() == 2) {
String list = troops.nextToken();
if (list.equals("Troop")) {
total++;
}
else {
}
} else {
}
}
troopStats = new String[total][5][10][2];
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
File file2 = new File("resources/objects/troops.txt");
BufferedReader reader2 = null;
try {
reader2 = new BufferedReader(new FileReader(file2));
String text = null;
// repeat until all lines is read
while ((text = reader2.readLine()) != null) {
StringTokenizer troops = new StringTokenizer(text, "=");
if (troops.countTokens() == 2) {
String list = troops.nextToken();
String value = troops.nextToken();
if (list.equals("Troop")) {
troop = value;
troopStats[times][0][0][0] = troop;
}
else if (list.equals("Weapon")) {
weapon = value;
troopStats[times][1][weaponTimes][0] = weapon;
weaponTimes++;
System.out.println(weaponTimes+"weapontimes"+times);
}
else if (list.equals("Armor")) {
armor = value;
troopStats[times][2][armorTimes][0] = armor;
armorTimes++;
}
else if (list.equals("Animal")) {
animal = value;
troopStats[times][3][animalTimes][0] = animal;
animalTimes++;
}
else if (list.equals("Speed")) {
speed = value;
troopStats[times][4][0][0] = speed;
}
else if (list.equals("Done")) {
weaponTimesStr = Integer.toString(weaponTimes);
System.out.println(weaponTimesStr+"string");
armorTimesStr = Integer.toString(armorTimes);
animalTimesStr = Integer.toString(animalTimes);
troopStats[times][1][0][1] = weaponTimesStr;
troopStats[times][1][0][1] = armorTimesStr;
troopStats[times][1][0][1] = animalTimesStr;
System.out.println(troopStats[times][1][0][1]+"InArray"+times);
times++;
troop = "";
weapon = "";
armor = "";
animal = "";
speed = "";
weaponTimes = 0;
armorTimes = 0;
animalTimes = 0;
}
else {
}
} else {
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
if (reader2 != null) {
reader2.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
In the earlier part of the code, I had the program store a value in the location on the array with the weaponTimes variable, not storing the weaponTimes variable. My mistake, sorry for wasting your time.
I wrote a SSCCE with what you posted and it prints what you would expect:
public static void main(String[] args) {
String[][][][] troopStats = new String[4][4][4][4];
int times = 2;
int weaponTimes = 3;
String weaponTimesStr = Integer.toString(weaponTimes);
System.out.println(weaponTimesStr + "string"); //prints 3string
troopStats[times][1][0][1] = weaponTimesStr;
System.out.println(troopStats[times][1][0][1] + "InArray"); //prints 3InArray
}
So the problem is most likely something/somewhere else.
The following:
public class Foo {
public static void main(String[] args) {
String[][][][] troopStats = new String[2][2][2][2];
String weaponTimesStr = Integer.toString(3);
System.out.println(weaponTimesStr+"string");
troopStats[0][1][0][1] = weaponTimesStr;
// You said in a comment that 'times' is equal to 0 in this case so have subbed that in
System.out.println(troopStats[0][1][0][1]+"InArray");
}
}
Gives me the expected output:
3string
3InArray
Sorry I've wasted your time, my mistake was because I stored values in the array using the values of weaponTimes, and not storing weaponTimes in the array.
troopStats[times][1][weaponTimes][0] = weapon;
That was the mistake.

how to reset program to main string args?

I am writing a program and if it catches an Exception I want to reset the whole program is there anyway please tell me I really need to finish it tonight ?
public static void readinfile(ArrayList<ArrayList> table,
int numberOfColumns,ArrayList<String> header,
ArrayList<ArrayList<String>> original,
ArrayList<String> sntypes, ArrayList<Integer> displaySize,
ArrayList<String> writeOut, Scanner inputStream) {
//System.out.print("enter data file: ");
Scanner keyboard = new Scanner(System.in);
System.out.print("enter data file: ");
String fileName = keyboard.nextLine();
try {
System.out.println("try " + fileName);
inputStream = new Scanner(new FileInputStream(fileName));
System.out.println(inputStream);
} catch (FileNotFoundException E) {
System.out.println("Error in opening file ");
//readinfile(table, numberOfColumns, header,
//original, sntypes,displaySize, writeOut, inputStream );
}
// file is now open and input scanner attached
if (inputStream.hasNextLine()) {
String Line = inputStream.nextLine();
Scanner lineparse = new Scanner(Line);
lineparse.useDelimiter(",");
ArrayList<String> rowOne = new ArrayList<String>();
while (lineparse.hasNext()) {
String temp = lineparse.next();
String originaltemp = temp;
writeOut.add(temp);
temp = temp + "(" + (++numberOfColumns) + ")";
displaySize.add(temp.length());
// row.add(lineparse.next());
if (temp.trim().substring(0, 2).equalsIgnoreCase("S ")
|| temp.trim().substring(0, 2).equalsIgnoreCase("N ")) {
rowOne.add(originaltemp);
header.add(temp.substring(2));
sntypes.add(temp.toUpperCase().substring(0, 2).trim());
} else {
System.out.println("Invalid file please enter a new file: ");
//readinfile(table, numberOfColumns, header, original, sntypes,displaySize,writeOut,Name);
readinfile(table, numberOfColumns, header,
original, sntypes, displaySize, writeOut, inputStream);
}
}
// add table here it gives problem later on...
original.add(rowOne);
}
while (inputStream.hasNextLine()) {
String Line = inputStream.nextLine();
Scanner lineparse = new Scanner(Line);
lineparse.useDelimiter(",");
ArrayList row = new ArrayList();
int j = 0;
while (lineparse.hasNextLine()) {
String temp = lineparse.next().trim();
int sizeOfrow = temp.trim().length();
if (sizeOfrow > displaySize.get(j)) {
displaySize.set(j, sizeOfrow);
}
if (j < numberOfColumns && sntypes.get(j).equalsIgnoreCase("N")) {
try {
if (temp.equalsIgnoreCase("")) {
row.add(new Double(0.0));
} else {
row.add(new Double(temp.trim()));
}
} catch (NumberFormatException E) {
System.out.println("Opps there is a mistake "
+ "I was expecting a number and I found: " + temp);
System.out.println("This row will be ignored");
// break;
}
} else {
if (temp.equalsIgnoreCase("")) {
row.add((" "));
} else {
row.add(temp);
}
}
j++;
}
if (row.size() == numberOfColumns) {
table.add(row);
}
}// close for while
inputStream.close();
}
homework?
Here's a clue on how to think about it:
main:
start loop
start
do stuff
set ok to end
catch exception
set not ok to end
loop if not ok to end
I'm not sure if you meant this, but the following code will run again and again until it succeeds (as in: doesn't throw an exception):
public static void main(String[] args){
while(true){
try{
// execute your code
break; // if successful, exit loop
}catch(SomeException e){
// handle exception
}catch(SomeOtherException e){
// handle exception
}finally{
// clean up, if necessary
}
}
}
Note: while(true) is an awful construct that I'm sure your teachers won't like. Perhaps you'll find a better way to rephrase that.
This is a bit of a hack but you could try calling the main method again, passing the arguments. As long as you didn't modify the string array of arguments, just call main(args); from a try/catch block in the main routine. Of course, if the exception keeps happening you'll loop infinitely and blow the stack:P

Categories