How can I fix these errors? java program - java

I have been working on a program.
I keep getting these errors:
StationInformation.java:65: error: non-static variable this cannot be referenced from a static context
Station mile_end = new Station();
^
StationInformation.java:66: error: non-static variable this cannot be referenced from a static context
Station oxford_circus = new Station();
^
StationInformation.java:67: error: non-static variable this cannot be referenced from a static context
Station kings_cross = new Station();
^
StationInformation.java:68: error: non-static variable this cannot be referenced from a static context
Station stepney_green = new Station();
^
4 errors
I want to fix the program.

I have made Station class as static and returning a list from create_messages().
//this program tells the user whether a station is a step free access station or not and how far is it from the platform
import java.util.Scanner; // imports the scanner function to input data from the user
import java.util.ArrayList;
import java.util.List;
class StationInformation {
public static void main(String[] args) // main method where methods are sequenced
{
int numberOfStations = inputint("how many stations do you want to know about?");
String station;
for (int i = 1; i <= numberOfStations; i++) {
station = inputstring("what station do you want to know about?");
search_station(station);
}
System.exit(0);
}
// A method to input integers
public static int inputint(String message) {
Scanner scanner = new Scanner(System.in);
int answer;
System.out.println(message);
answer = Integer.parseInt(scanner.nextLine());
return answer;
} // END inputInt
public static String inputstring(String message) {
Scanner scanner = new Scanner(System.in);
String answer;
System.out.println(message);
answer = scanner.nextLine();
return answer;
}
public static String create_message(Station station) {
String message;
if (station.step_free_access == true) {
message = (station.name + "does have step free access. " + "it is " + station.distance_from_platform
+ "m away from the entrance");
} else {
message = (station.name + "does not have step free access. " + "it is " + station.distance_from_platform
+ "m away from the entrance");
}
return message;
}
public static List<String> create_messages() {
Station mile_end = new StationInformation.Station();
Station oxford_circus = new Station();
Station kings_cross = new Station();
Station stepney_green = new Station();
mile_end.distance_from_platform = 50;
mile_end.name = "Mile End ";
mile_end.step_free_access = false;
String message1 = create_message(mile_end);
oxford_circus.distance_from_platform = 200;
oxford_circus.name = " Oxford Circus ";
oxford_circus.step_free_access = true;
String message2 = create_message(oxford_circus);
kings_cross.distance_from_platform = 700;
kings_cross.name = " kings cross ";
kings_cross.step_free_access = true;
String message3 = create_message(kings_cross);
stepney_green.distance_from_platform = 300;
stepney_green.name = " Stepney Green ";
stepney_green.step_free_access = false;
String message4 = create_message(stepney_green);
List<String> list = new ArrayList<>();
list.add(message1);
list.add(message2);
list.add(message3);
list.add(message4);
return list;
}
public static void search_station(String station) {
List<String> list = create_messages();
String mileEndMessage = list.get(0);
String oxfordCircusMessage = list.get(1);
String kingsCrossMessage = list.get(2);
String stepneyGreenMessage = list.get(3);
if (station.equals("Mile End")) {
System.out.println(mileEndMessage);
} else if (station.equals("kings cross")) {
System.out.println(kingsCrossMessage);
} else if (station.equals("oxford circus")) {
System.out.println(oxfordCircusMessage);
} else if (station.equals("stepney green")) {
System.out.println(stepneyGreenMessage);
} else {
System.out.println(station + " is not a London underground station ");
}
}
static class Station // a record to store information about stations
{
int distance_from_platform;
String name;
boolean step_free_access;
}
}

Edit: This answer might seem outdated since the OP decided to edit the question, removing his code in the process.
There are 2 errors in your code:
Your inner class Station is not static, meaning you cannot instantiate it in a static context. This is producing the error messages you see.
You are thinking that Java is pass-by-reference, and are trying to override the value the variable(s) are pointing to (which you cannot do in Java).
You can fix your mistakes by making your Station-class static (static class Station), and by making the stations you use class-variables, and using their fields to create a String.
You could also implement a getInfo()-method for the Station-class that prepares its info on its own. With this, you can just call System.out.println(STATION_YOU_WANT.getInfo()).
I have taken a bit of my time to write a commented solution to the question.
The most confusing part of it is probably the use of varargs (String... in the code below). They basically allow you to pass any number of arguments to a method, which will inherently be converted to an array by Java.
import java.util.HashMap;
import java.util.Locale;
import java.util.Scanner;
public class StationInformation {
private static class Station {
private String name;
private int distanceToPlatform;
private boolean stepFree;
private String[] alternateNames;
Station(String name, int distanceToPlatform, boolean stepFree, String...alternateNames) {
this.name = name;
this.distanceToPlatform = distanceToPlatform;
this.stepFree = stepFree;
this.alternateNames = alternateNames; // 'String...' makes that parameter optional, resulting in 'null' if no value is passed
}
String getInfo() {
return name + " does" + (stepFree ? " " : " not ")
+ "have step free access.\nIt is " + distanceToPlatform + "m from entrance to platform.";
}
}
private static HashMap<String, Station> stations = new HashMap<String, Station>();
public static void main(String[] args) {
createStations();
// The Program
Scanner scanner = new Scanner(System.in);
// Keep requesting input until receiving a valid number
int num;
for (;;) { // 'for (;;) ...' is effectively the same as 'while (true) ...'
System.out.print("How many stations do you need to know about? ");
String input = scanner.nextLine();
try {
num = Integer.parseInt(input);
break;
} catch (Exception exc) {
// Do nothing
}
System.out.println("Please enter a correct number.");
}
for (int i = 0; i < num; ++i) {
System.out.print("\nWhat station do you need to know about? ");
String input = scanner.nextLine();
// If available, show Station-information
if (stations.containsKey(input.toLowerCase(Locale.ROOT))) {
System.out.println(stations.get(input.toLowerCase(Locale.ROOT)).getInfo());
} else {
System.out.println("\"" + input + "\" is not a London Underground Station.");
}
}
scanner.close(); // Close Scanner; Here actually not needed because program will be closed right after, freeing its resources anyway
}
private static void createStations() {
// Add new Stations here to automatically add them to the HashMap
Station[] stations = new Station[] {
new Station("Stepney Green", 100, false),
new Station("King's Cross", 700, true, "Kings Cross"),
new Station("Oxford Circus", 200, true)
};
for (Station station : stations) {
StationInformation.stations.put(station.name.toLowerCase(Locale.ROOT), station);
// Alternative names will be mapped to the same Station
if (station.alternateNames == null) continue;
for (String altName : station.alternateNames)
StationInformation.stations.put(altName.toLowerCase(Locale.ROOT), station);
}
}
}

Related

Can't loop properly through list of objects

I'm having the following issue.
I have a list filled with instances of the "God" class, 12 instances, for now, but will add more in the future.
I also have an list empty.
Both lists can take type God instances.
The user will pick 6 of these gods, and these gods will be added to the empty list, and also be remove of the filled list, so they can't get picked again.
The goal of this part of the project is, to:
The user will pick 6 times. So I have a for loop from 0 to 5;
The Scanner takes the id of the god
The second for loop, from 0 to listFilledWithGods.size(), will check if the scanner matches the id
If the id matches, it will add to the empty list, and remove from the List filled with gods
If it does not match the user needs to be asked constantly to pick another one, until the user picks an available god. (here is where I'm having trouble)
Github: https://github.com/OrlandoVSilva/battleSimulatorJava.git
The issue in question resides in the class player in the method selectGodsForTeam
There is a JSON jar added to the project: json-simple-1.1.1
*Edit:
I added the while loop, as an exmaple of one of the ways that I tried to fix the issue.
If the user on the first pick picks id 3, it should work, because no god has been picked yet, however the loop when comparing it with the first position (id 1) it says to pick another one, which should is not the intended objective.
Main:
import java.util.List;
public class Main {
public Main() {
}
public static void main(String[] args) {
Launcher launch = new Launcher();
godSelection(launch.loadGods());
}
private static void godSelection(List<God> listOfloadedGods) {
Player player = new Player(listOfloadedGods);
player.selectGodsForTeam();
}
}
Launcher:
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class Launcher {
private List<God> godCollection;
public Launcher(){
godCollection = new ArrayList<>();
}
List<God> loadGods(){ // load all gods from Json file into list
String strJson = getJSONFromFile("C:\\Users\\OrlandoVSilva\\Desktop\\JavaBattleSimulator\\battlesimulator\\src\\projectStructure\\gods.json");
// Try-catch block
try {
JSONParser parser = new JSONParser();
Object object = parser.parse(strJson); // converting the contents of the file into an object
JSONObject mainJsonObject = (JSONObject) object; // converting the object into a json object
//-------------------
JSONArray jsonArrayGods = (JSONArray) mainJsonObject.get("gods");
//System.out.println("Gods: ");
for(int i = 0; i < jsonArrayGods.size(); i++){
JSONObject jsonGodsData = (JSONObject) jsonArrayGods.get(i);
String godName = (String) jsonGodsData.get("name");
//System.out.println("Name: " + godName);
double godHealth = (double) jsonGodsData.get("health");
//System.out.println("Health: " + godHealth);
double godAttack = (double) jsonGodsData.get("attack");
//System.out.println("Attack: " + godAttack);
double godSpecialAttack = (double) jsonGodsData.get("specialAttack");
//System.out.println("Special Attack: " + godSpecialAttack);
double godDefense = (double) jsonGodsData.get("defense");
//System.out.println("Defense: " + godDefense);
double godSpecialDefence = (double) jsonGodsData.get("specialDefense");
//System.out.println("Special Defence: " + godSpecialDefence);
double godSpeed = (double) jsonGodsData.get("speed");
//System.out.println("Speed: " + godSpeed);
double godMana = (double) jsonGodsData.get("mana");
//System.out.println("Mana: " + godMana);
String godPantheon = (String) jsonGodsData.get("pantheon");
//System.out.println("Pantheon: " + godPantheon);
long godId = (long) jsonGodsData.get("id");
int newGodId = (int) godId;
//System.out.println("Id: " + newGodId);
godCollection.add(new God(godName, godHealth, godAttack, godSpecialAttack, godDefense, godSpecialDefence, godSpeed, godMana, godPantheon, newGodId));
//System.out.println();
}
} catch (Exception ex){
ex.printStackTrace();
}
// Try-catch block
//System.out.println("Size: " + godCollection.size());
return godCollection;
}
public static String getJSONFromFile(String filename) { // requires file name
String jsonText = "";
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(filename)); // read the file
String line; // read the file line by line
while ((line = bufferedReader.readLine()) != null) {
jsonText += line + "\n"; // store json dat into "jsonText" variable
}
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
return jsonText;
}
}
Player:
import java.util.*;
public class Player {
// --- Properties ---
private List<God> listOfAllGods; // List of all the gods;
private List<God> selectedGods; // list for the selected gods;
// --- Properties ---
// --- Constructor ---
Player(List<God> listOfAllGods){
this.listOfAllGods = listOfAllGods;
selectedGods = new ArrayList<>();
}
// --- Constructor ---
// --- Getters & Setters ---
public List<God> getSelectedGods() {
return listOfAllGods;
}
// --- Getters & Setters ---
// --- Methods ---
void selectGodsForTeam(){
Scanner scanner = new Scanner(System.in);
boolean isGodAvailable;
int chooseGodId;
/*
char answerChar = 'n';
while (answerChar == 'n'){
answerChar = informationAboutGods();
// Do you want to see information about any of the gods first?
// y or n
while(answerChar == 'y'){
answerChar = informationAboutAnyOtherGods();
// Which of the gods, do you want to see information of?
// godId
// Do you want to see information about any other gods?
// y or n
}
answerChar = proceedWithGodPick();
// Do you want to proceed with the God pick?
// y or n
}
System.out.println();
*/
System.out.println("Please choose the 6 id's of the gods, you wish to pick:");
for(int i = 0; i <= 5; i++){
chooseGodId = scanner.nextInt();
for(int j = 0; j < listOfAllGods.size(); j++){
if(chooseGodId == listOfAllGods.get(j).getId()){
selectedGods.add(listOfAllGods.get(j));
listOfAllGods.remove(j);
} else {
isGodAvailable = false;
while (!isGodAvailable){
System.out.println("Please pick another one");
chooseGodId = scanner.nextInt();
if(chooseGodId == listOfAllGods.get(j).getId()) {
isGodAvailable = true;
selectedGods.add(listOfAllGods.get(j));
listOfAllGods.remove(j);
}
}
}
}
}
}
char informationAboutGods(){
Scanner scanner = new Scanner(System.in);
char answerChar = 'n';
//-----------
System.out.println("This is a list, of all the selectable gods: ");
System.out.println();
for (int i = 0; i < listOfAllGods.size(); i++){
System.out.println(listOfAllGods.get(i).getName() + " = " + "Id: " + listOfAllGods.get(i).getId());
}
System.out.println();
System.out.println("Do you want to see information about any of the gods first?");
System.out.println("[y] or [n]");
answerChar = scanner.next().charAt(0);
return answerChar;
}
char informationAboutAnyOtherGods(){
Scanner scanner = new Scanner(System.in);
char answerChar = 'n';
int answerInt;
//------------
System.out.println();
System.out.println("Which of the gods, do you want to see information of?");
System.out.println("Please input it's id number: ");
answerInt = scanner.nextInt();
System.out.println();
System.out.println("Display god information here!");
System.out.println();
System.out.println("Do you want to see information about any other gods?");
System.out.println("[y] or [n]");
answerChar = scanner.next().charAt(0);
return answerChar;
}
char proceedWithGodPick(){
Scanner scanner = new Scanner(System.in);
char answerChar = 'n';
//----------
System.out.println();
System.out.println("Do you want to proceed with the God pick?");
System.out.println("[y] or [n]");
answerChar = scanner.next().charAt(0);
return answerChar;
}
// --- Methods ---
}
God:
public class God {
private final String name;
private double health;
private double attack;
private double specialAttack;
private double defense;
private double specialDefense;
private double speed;
private double mana;
private final String pantheon;
private final int id;
public God(String name, double health, double attack, double specialAttack, double defense, double specialDefense, double speed, double mana, String pantheon, int id) {
this.name = name;
this.health = health;
this.attack = attack;
this.specialAttack = specialAttack;
this.defense = defense;
this.specialDefense = specialDefense;
this.speed = speed;
this.mana = mana;
this.pantheon = pantheon;
this.id = id;
}
public double getHealth() {
return this.health;
}
public void setHealth(double health) {
this.health = health;
}
public double getAttack() {
return this.attack;
}
public void setAttack(double attack) {
this.attack = attack;
}
public double getSpecialAttack() {
return this.specialAttack;
}
public void setSpecialAttack(double specialAttack) {
this.specialAttack = specialAttack;
}
public double getDefense() {
return this.defense;
}
public void setDefense(double defense) {
this.defense = defense;
}
public double getSpecialDefense() {
return this.specialDefense;
}
public void setSpecialDefense(double specialDefense) {
this.specialDefense = specialDefense;
}
public double getSpeed() {
return this.speed;
}
public void setSpeed(double speed) {
this.speed = speed;
}
public double getMana() {
return this.mana;
}
public void setMana(double mana) {
this.mana = mana;
}
public String getName() {
return this.name;
}
public String getPantheon() {
return this.pantheon;
}
public int getId() {
return this.id;
}
}
If I understand correctly, the key is to replace the for loop, which will have 6 iterations, with a while loop, which will iterate until the user has successfully selected 6 gods. Use continue; when there is a failure to select a god.
System.out.println("Please choose the 6 id's of the gods, you wish to pick:");
while (selectedGods.size () < 6) {
System.out.print ("You have selected " + selectedGods.size ()
+ "gods. Please enter I.D. of next god >");
chooseGodId = scanner.nextInt();
if (findGod (selectedGods, chooseGodID) >= 0) {
System.out.println ("You already selected god " + chooseGodId
+ ". Please select again.");
continue;
}
int godSelectedIndex = findGod (listOfAllGods, chooseGodId);
if (godSelectedIndex < 0) {
System.out.println ("God " + chooseGodID + " is not available."
+ " Please select again.");
continue;
}
selectedGods.add (listOfAllGods.get(godSelectedIndex));
listOfAllGods.remove (godSelectedIndex);
}
This assumes the existence of
static public int findGod (List<God> godList, int targetGodID)
This findGod method searches godList for an element in which .getId() is equal to gargetGodID. When a match is found, it returns the index of element where the match was found. When a match is not found, it returns -1. The O/P has shown the ability to create this method.
Note: I have not verified the code in this answer. If you find an error, you may correct it by editing this answer.

Why does my output not match the expected output and how can I make it match?

here is a dictionary program.
Code Provided
import java.util.*;
public enum Dictionary {
DistinctADJECTIVEONE("Distinct","adjective","Familiar. Worked in Java."),
DistinctADJECTIVETWO("Distinct","adjective","Unique. No duplicates. Clearly different or of a different kind."),
DistinctADVERB("Distinct","adverb","Uniquely. Written 'distinctly.'"),
DistinctNOUNONE("Distinct","noun","A keyword in this assignment."),
DistinctNOUNTWO("Distinct","noun","A keyword in this assignment."),
DistinctNOUNTHREE("Distinct","noun","A keyword in this assignment."),
DistinctNOUNFOUR("Distinct","noun","An advanced search option."),
DistinctNOUNFIVE("Distinct","noun","Distinct is a parameter in this assignment.");
private final String generalNote = "Dictionary";
private String keyword;
private String partOfSpeech;
private String definition;
private Dictionary(String keyword, String partOfSpeech, String definition) {
this.keyword = keyword;
this.partOfSpeech = partOfSpeech;
this.definition = definition;
}
public String getKeyword() {
return this.keyword.toUpperCase();
}
public String definition(){
return this.definition;
}
#Override
public String toString() {
return this.keyword + " [" + this.partOfSpeech + "] : " + this.definition;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("! Loading data...");
HashMap<String, ArrayList<Dictionary>> hmap = new HashMap<String, ArrayList<Dictionary>>();
for (Dictionary dict : Dictionary.values()) {
String keyword = dict.getKeyword();
ArrayList<Dictionary> list = (hmap.containsKey(keyword)) ? hmap.get(keyword) : new ArrayList<Dictionary>();
list.add(dict);
hmap.put(keyword, list);
}
System.out.println("! Loading Complete...");
Boolean quite = true;
int counter = 7;
do {
counter++;
System.out.print("[" + counter + "] Search: ");
String userinput = input.nextLine();
String[] splited = userinput.split(" ");
String word = null;
Boolean requestDistinct = false;
if (splited.length > 0) {
word = splited[0];
}
if (splited.length > 1 && splited[1]!= null) {
if (splited[1].equalsIgnoreCase("distinct")) {
requestDistinct = true;
}
else {
System.out.println(" |");
System.out.println(" <The entered 2nd parameter " + userinput + " is NOT 'distinct'.>\n" +
" <The 2nd parameter should be a part of speech or 'distinct'.>");
System.out.println(" |");
continue;
}
}
if(!userinput.equalsIgnoreCase("!q")) {
System.out.println(" |");
ArrayList<Dictionary> result = hmap.get(word.toUpperCase());
ArrayList<Dictionary> secondResult = (requestDistinct) ? returnDictionaryWithDistinctDefinition(result) : result;
if (secondResult != null && secondResult.size()>0) {
for(Dictionary key : secondResult) {
System.out.print(" " + key + "\n");
}
}
System.out.println(" |");
} else {
System.out.println("\n----Thank You---");
quite = false;
}
requestDistinct = false;
} while(quite);
}
public static ArrayList<Dictionary> returnDictionaryWithDistinctDefinition(ArrayList<Dictionary> dictList) {
HashMap<String, Dictionary> hMap = new HashMap<String, Dictionary>();
if (dictList != null) {
for (Dictionary dict : dictList) {
String definition = dict.definition();
if (!hMap.containsKey(definition)) {
hMap.put(definition, dict);
}
}
}
return new ArrayList<Dictionary>(hMap.values());
}
}
The user can type in up to two arguments.
The first argument would be just 'Distinct' and the Dictionary would display all the definitions of distinct stored as Enums.
The second argument can be 'Distinct', which would display all the UNIQUE definitions.
So while my program does function as intended, why doesn't my output in photo #1 match up with the output shown in photo #2? (It went out of order) And how can this be fixed?
Photo #1 (My Output)
Photo #2 (The required output)
HashMap does not maintain insertion order. Please try using LinkedHashMap. LinkedHashMap maintains insertion order, and you will not see this issue.

Profanity Filter: I just need some help on how to make it recognize _only_ the values in an array

/*
Profanity Filter:
- Cat
- Dog
- LLama
- Has to differ cases, like cAt
- Has to differ words that contain the words to be filtered, "Cataclysm", for example. Hello, World of Warcraft.
*/
import java.util.Scanner;
public class ProfanityFilter
{
public static void main (String[] args)
{
Scanner kb = new Scanner(System.in);
String userInput, toLowerCase;
boolean flag = false;
int i;
String[] list = new String[12];
list[0] = "cat";
list[1] = " cat";
list[2] = "cat ";
list[3] = " cat ";
list[4] = "dog";
list[5] = " dog";
list[6] = "dog ";
list[7] = " dog ";
list[8] = "llama";
list[9] = " llama";
list[10] = "llama ";
list[11] = " llama ";
System.out.println("Enter a string:");
userInput = kb.nextLine();
toLowerCase = userInput.toLowerCase();
for (i = 0; i < list.length; i++)
{
if(toLowerCase.contains(list[i]) | toLowerCase.equals(list[i]))
{
flag = true;
}
}
if (flag)
{
System.out.println("Something you said is forbidden.");
}
else
{
System.out.println("Nothing was found");
}
}
}
I'm just having trouble finding the proper exception to what I need. I know I'm pretty close, but I'm also tired after trying many many hours to solve this problem and coming out empty of a solution that will return true for the instances I need (the ones in the array). Can you point me out to what I'm doing wrong in here or to a proper solution without regular expressions?
I've already tried to put a break; after I turn the boolean flag to true but it didn't work, it keeps iterating and thus the output keeps being false.
Thanks!
Here is a potential solution:
public class Class {
private static final String[] profaneWords = {
"cat",
"dog",
"llama"
};
public static void main(String... args) {
System.out.println(isProfane("this is some user input."));
System.out.println(isProfane("this is some user input containing the dirty word 'Cat'."));
System.out.println(isProfane(" cat "));
System.out.println(isProfane("Cat"));
}
private static boolean isProfane(final String input) {
for (final String profanity : profaneWords) {
if (input.toLowerCase().contains(profanity)) {
return true;
}
}
return false;
}
}
Here is a streaming java8 version:
import java.util.Arrays;
public class Class {
private static final String[] profaneWords = {
"cat",
"dog",
"llama"
};
private static boolean isProfane(final String input) {
return Arrays.stream(profaneWords)
.anyMatch(input.toLowerCase()::contains);
}
}

Getting returned wrong values, but reading in fine in system? Java

I am trying to read in this input:
processcount 2 # Read 2 processes
runfor 15 # Run for 15 time units
use rr # Can be fcfs, sjf, or rr
quantum 2 # Time quantum – only if using rr
process name P1 arrival 3 burst 5
process name P2 arrival 0 burst 9
end
My job is to only parse in the values and not the words, and to keep out the comments (#).
Here is the main file:
public class main {
static String[] token = new String[10];
static List<Schedule> p;
public static void schedule()
{
for(Schedule c: p)
{
System.out.println("ProcessInfo: " + c.getProcess().processName);
System.out.println("count: " + c.getProcessCount());
System.out.println("quant: " + c.getQuantum());
System.out.println("runtime: " + c.getRunTime());
System.out.println("Type: " + c.getType());
}
}
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
// sc = new Scanner(new File("processes.in"));
p = new ArrayList<>();
while(sc.hasNextLine() && !sc.equals("end"))
{
token = sc.nextLine().replace(" ","-").replace("#", "-").split("-");
System.out.println(token[0].toString());
if(!token[0].startsWith("#") || !sc.nextLine().startsWith("end"))
{
Schedule s = new Schedule();
int pCount=0, runfor=0, quantum=0, arrival=0, burst=0;
String type = null, pName = null;
if(token[0].startsWith("processcount"))
{
s.setProcessCount(Integer.parseInt(token[1]));
System.out.println(Integer.parseInt(token[1] +""));
}
else if(token[0].startsWith("runfor"))
{
s.setRunTime(Integer.valueOf(token[1].toString()));
System.out.println(Integer.parseInt(token[1]) +"");
}
else if(token[0].startsWith("use"))
{
s.setType(token[1].toString());
System.out.println(token[1] +"");
}
else if(token[0].startsWith("quantum"))
{
s.setQuantum(Integer.valueOf(token[1].toString()));
System.out.println(token[1] + "");
}
else if(token[0].startsWith("process"))
{
Processes pl = new Processes();
pl.setProcessName(token[2]);
System.out.println(token[2]+ "");
pl.setArrivalTime(Integer.valueOf(token[4].toString()));
System.out.println(""+ Integer.valueOf(token[4]));
pl.setBurstTime(Integer.valueOf(token[6].toString()));
System.out.println("" + token[6]);
s.setProcess(pl);
// add info
p.add(s);
}
else if(token[0].startsWith("end"))
{
schedule();
}
}
}
}
}
Here is the Schedule:
public class Schedule {
int processCount;
int runTime;
String type;
int quantum;
Processes process;
public int getProcessCount() {
return processCount;
}
public void setProcessCount(int processCount) {
this.processCount = processCount;
}
public int getRunTime() {
return runTime;
}
public void setRunTime(int runTime) {
this.runTime = runTime;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getQuantum() {
return quantum;
}
public void setQuantum(int quantum) {
this.quantum = quantum;
}
public Processes getProcess() {
return process;
}
public void setProcess(Processes p) {
process = p;
}
}
Here is the Process:
public class Processes {
String processName;
int arrivalTime;
int burstTime;
public String getProcessName() {
return processName;
}
public void setProcessName(String processName) {
this.processName = processName;
}
public int getArrivalTime() {
return arrivalTime;
}
public void setArrivalTime(int arrivalTime) {
this.arrivalTime = arrivalTime;
}
public int getBurstTime() {
return burstTime;
}
public void setBurstTime(int burstTime) {
this.burstTime = burstTime;
}
}
Here is the output I am getting with my code:
ProcessInfo: P1
count: 0
quant: 0
runtime: 0
Type: null
ProcessInfo: P2
count: 0
quant: 0
runtime: 0
Type: null
why am I getting returned wrong results?
There's couple of issue here. You create a new schedule at each iteration of your while loop; you don't get all the relevant values of your current line before the new iteration plus you have couple of useless variables right after you create a new Schedule() which override the previously collected values.
Also, you use toString on a String element of your array which is meaningless. Personnaly I don't try not to use filters and you don't really need any for this. Always try to KISS(Keep It Simple Stupid)
Here's how I'll go about it without using filters.
public static void main (String args [])
{
// Will help us identify the key words
String current_token;
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
//Remove spaces at the beginning and end of the string
input = input.trim();
Schedule s = new Schedule();
// New source for the scanner
sc =new Scanner(input);
p = new ArrayList<>();
while(sc.hasNext())
{
current_token = sc.next();
if(current_token.equals("end"))
{schedule(); break;}
switch(current_token)
{
case "processcount":
s.setProcessCount(sc.nextInt());
System.out.println(s.getProcessCount()+ " ");
break;
case "runfor":
s.setRunTime(sc.nextInt());
System.out.println(s.getRuntime +" ");
case "use":
s.setType(sc.next());
System.out.println(s.getType() +" ");
break;
case "quantum":
s.setQuantum(sc.nextInt());
System.out.println(s.getQuantum + " ");
break;
case "process":
Processes pl = new Processes();
pl.setProcessName(sc.next());
System.out.println(pl.GetProcessName()+ " ");
pl.setArrivalTime(sc.nextInt());
System.out.println(" "+ pl.getArrivalTime());
pl.setBurstTime(sc.nextInt());
System.out.println(" " + pl.getBurstTime());
s.setProcess(pl);
// add info
p.add(s);
break;
default:
// the current_token is not what we are looking for
break;
}
}
}
You're having an issue because of the way you split the string. The way you have right now first replaces each space with a dash. For example, the string
"processcount 2 # a comment"
would become
"processcount-2---#-a-comment"
and then splitting that gives you an empty string between every pair of dashes, so you'll end up with
token = ["processcount", "2", "","", ... etc]
I suggest that you do this:
String str = (sc.nextLine().split("#"))[0]; //get the string before the pound sign
str = str.trim(); //remove the leading/trailing whitespace
token = str.split("\\s+"); //split the string by the whitespaces

How can I access my private variables across different classes?

I am working on creating a hangman-like game. It reads from a .txt file of four letter words and randomly selects one of the words and the player will then have 7 tries to guess the word...I have not completed that all yet, I am having trouble accessing my variables from one class to the other. Here is my code:
package wordguessinggame2;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class WordGuessingGame2 {
static class RandomWordProvider {
public final List<String> words;
public RandomWordProvider() {
words = readFile();
}
public int randomInteger() {
int randomInt = (int) (Math.random() * words.size());
return randomInt;
}
private String getWord() {
int randomPosition = randomInteger();
String randomWord = words.get(randomPosition);
return randomWord;
}
private List<String> readFile() {
List<String> wordsList = new ArrayList<>();
try {
File fourLetterWords = new File(System.getProperty("user.home"),"Documents/FourLetterWords.txt");
Scanner in = new Scanner(fourLetterWords);
while (in.hasNextLine()) {
String line = in.nextLine();
if (line!=null && !line.isEmpty()) {
wordsList.add(line);
}
}
}
catch (FileNotFoundException ex) {
System.out.println("File not found.");
}
return wordsList ;
}
}
public static class PlayerCharacterEntry {
private String playerEntry() {
Scanner characterEntry = new Scanner(System.in);
System.out.print("Enter a character: ");
String playerInput = characterEntry.next();
playerInput = playerInput.toUpperCase();
return playerInput;
}
}
public static void main(String[] args) {
Scanner wantToPlay = new Scanner(System.in);
System.out.print("Welcome to the word guessing game! Would you like to play? ");
String playerAnswer = wantToPlay.next();
if (playerAnswer.equalsIgnoreCase("Yes")) {
System.out.print("\nYour objective is to guess a four letter word by entering"
+ "\nletters on your keyboard. If you can not guess the word in seven attempts,"
+ "\nyou lose! You will be told if the letter you entered is in the word, and"
+ "\nyou will be told if the letter you entered is not in the word. You will be"
+ "\nallowed to guess the word any time during your seven attempts. If at anytime"
+ "\nyou would like to terminate the game, enter the word 'terminate'. Good Luck!"
+ "\n \n");
}
if (playerAnswer.equalsIgnoreCase("No")) {
System.out.print("Maybe another time!");
System.exit(0);
}
RandomWordProvider randomWordProvider = new RandomWordProvider();
PlayerCharacterEntry playerCharacterEntry = new PlayerCharacterEntry();
randomWordProvider.getWord();
playerCharacterEntry.playerEntry();
if (randomWord.containsIgnoreCase(playerInput)){
}
}
}
Here at the bottom I am trying to access randomWord and playerInput from my other classes but I don't know how to do that. I am still fairly new to programming so I don't know how to do everything yet. Would I do a get and set method for each variable? I have tried doing that and I'm having a lot of trouble with that. If someone could show me how to access variables across classes it would be greatly appreciated!
Here's a slightly simplified example where the RandomWordProvider and PlayerCharacterEntry classes are NOT nested inside WordGuessingGame2.
I show only the methods I needed to modify:
class RandomWordProvider {
String getWord() {
int randomPosition = randomInteger();
String randomWord = words.get(randomPosition);
return randomWord;
}
// ...
}
class PlayerCharacterEntry {
String playerEntry() {
Scanner characterEntry = new Scanner(System.in);
System.out.print("Enter a character: ");
String playerInput = characterEntry.next();
playerInput = playerInput.toUpperCase();
return playerInput;
}
}
class WordGuessingGame2 {
public static void main(String[] args) {
// ...
RandomWordProvider randomWordProvider = new RandomWordProvider();
PlayerCharacterEntry playerCharacterEntry = new PlayerCharacterEntry();
randomWordProvider.getWord();
playerCharacterEntry.playerEntry();
}
}
Notice that I dropped the private modifier from the getWord and playerEntry methods,
otherwise they are not accessible from WordGuessingGame2.
It's good to start with the strictest possible modifiers,
and then reduce the restrictions as necessary.
No, private variables are only accessable from within the class it self. It's highly recommended that you create public getters and setters to maintain the OO principle of encapsulation.

Categories

Resources