Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I need to use a variable from one method in another. Here is the code:
public static void secondMain() {
BufferedReader reader;
var lines = new ArrayList<String>();
var rooms = new ArrayList<Room>();
try {
reader = new BufferedReader(new FileReader("rooms.txt"));
String line = reader.readLine();
lines.add(line);
while (line != null) {
line = reader.readLine();
lines.add(line);
}
reader.close();
for (int i = 0; i < lines.size() - 1; i++){
String[] words = lines.get(i).split(" ");
var room = new Room();
room.roomNum = Integer.parseInt(words[0]);
room.roomType = (words[1]);
room.roomPrice = Double.parseDouble(words[2]);
room.hasBalcony = Boolean.parseBoolean(words[3]);
room.hasLounge = Boolean.parseBoolean(words[4]);
room.eMail = (words[5]);
rooms.add(room);
}
Here is where it needs to be used:
public static void reserveRoom() {
// TODO Auto-generated method stub
String choice = "";
do {
secondMain();
System.out.println("\n-- ROOM RESERVATION --");
System.out.println("Please enter the room number you wish to reserve");
System.out.println("Q - Quit");
Room selectedRoom = null;
var searchRoomNum = input.nextInt();
for(int i = 0; i < rooms.size(); i++){
if(rooms.get(i).roomNum == searchRoomNum){
selectedRoom = rooms.get(i);
System.out.println("Room Number: " + selectedRoom.roomNum);
System.out.println("Room Type: " + selectedRoom.roomType);
System.out.println("Room Price: " + selectedRoom.roomPrice);
System.out.println("Balcony: " + selectedRoom.hasBalcony);
System.out.println("Lounge: " + selectedRoom.hasLounge);
System.out.println("Email: " + selectedRoom.eMail);
System.out.println("-------------------");
}
}
}
my current error is on the for loop where im testing the conditions against the array. "rooms cannot be resolved".
If you want to access rooms from the secondMain() method in the reserveRoom(), you should return it from secondMain() when you make the call. This can be done by changing the return type of the method
public static void secondMain() to become public static ArrayList<Room> secondMain()
Then after the for loop in secondMain() when you have finished adding all the rooms to the array list, you should return rooms to the caller. This can be added as one statement after your try catch block.
return rooms;
This way you can access this property from reserveRoom(). The line where the call is made
do {
secondMain();
should become:
do{
var rooms = secondMain();
This should allow you to access rooms in reserveRoom()
Instead of public static void secondMain, you can make it public static ArrayList<Room> secondMain
At the end of the secondMain: return rooms.
In the reserveRoom method: when you call the secondMain method: ArrayList<Room> rooms = secondMain();
Now you should be able to use rooms inside reserveRoom method
Related
I'm new to Java, and i'm trying to create an automatic working shift schedule.
I want the code to mix four different employees to handle a morning shift and afternoon shift every work day.
I have made some code that just pick a random employee into a shift:
import java.util.Arrays;
import java.util.Random;
public class CreateNewShift {
public static void main(String[] args) {
int startWeek = 30; //Which week would start from?
int endWeek = 32; //which week will you end on?
generateShift(startWeek, endWeek);
}
private static void generateShift(int startWeek, int endWeek) {
String Employees[] = {"Employee1", "Employee2", "Employee3", "Employee4"};
String morningShift;
String afternoonShift;
for (int x = 0; x <= (endWeek - startWeek); x++) { //This is counting the number of weeks
System.out.println("\nWeek: " + (startWeek+x));
for (int i = 1; i <= 5; i++) { //this is finding the next working shift day
morningShift = p.chooseRandomEmployee(Employees);
afternoonShift = p.chooseRandomEmployee(Employees);
if (i == 1) {
System.out.println("Mon: " + morningShift + " + " + afternoonShift);
}
else if (i == 2) {
System.out.println("Tue: " + morningShift + " + " + afternoonShift);
}
else if (i == 3) {
System.out.println("Wed: " + morningShift + " + " + afternoonShift);
}
else if (i == 4) {
System.out.println("Thu: " + morningShift + " + " + afternoonShift);
}
else {
System.out.println("Fri: " + morningShift + " + " + afternoonShift);
}
}
}
}
public class Employee {
public String chooseRandomEmployee(String[] Employees) {
Random r = new Random();
int randomNumber = r.nextInt(Employees.length);
return Employees[randomNumber];
}
}
However, I now want the code to handle more restictions.
So i'm currently trying to add the option for the employees to choose some specific days that they dont want to have a shift. I have done this by adding this code to the Employee class:
public class Employee {
boolean monShift = true;
boolean tueShift = true;
boolean wedShift = true;
boolean thuShift = true;
boolean friShift = true;
public String chooseRandomEmployee(String[] Employees) {
Random r = new Random();
int randomNumber = r.nextInt(Employees.length);
return Employees[randomNumber];
}
}
And then i had tried to create new objects in my main class:
private static void generateShift(int startWeek, int endWeek) {
Employee Employee1 = new Employee("Employee1");
Employee Employee2 = new Employee("Employee2");
Employee Employee3 = new Employee("Employee3");
Employee Employee4 = new Employee("Employee4");
String Employees[] = {"Employee1", "Employee2", "Employee3", "Employee4"};
String morningShift;
String afternoonShift;
....
Quetions:
How can I improve my code in the Employee class to do a check if the random chosen employee have
monShift = true;
I have tried something like this, but i know it will not work, (and does not work either):
import java.util.Random;
public class Employee {
public String chooseRandomEmployee(String[] Employees) {
Random r = new Random();
int randomNumber = r.nextInt(Employees.length);
**if (("Employee" + randomNumber).monShift == false) {**
// Go back and try find a new random employee
}
else {
return Employees[randomNumber];
}
}
}
So i need a way to make my code dynamic to know which object (employee) it has to check if they are available that specific day or not.
Feel free to ask for a deepening if my question is not clear.
Since this i my first question on this forum, I also appriciate feedback if my question and thoughts are too long, or any other comments.
I dont think that putting the chooseRandomEmployee() function inside the Employee object is a good idea beacuse is not a part of the employee, is not an "action" of it. I think you shiudl put it outside but I want to respect your decision so shoudl check the do while loop.
import java.util.Random;
public class Employee {
public String chooseRandomEmployee(String[] Employees) {
int randomNumber;
do {
//Generate a new random number
Random r = new Random();
randomNumber = r.nextInt(Employees.length);
//The line under is the same that saying "If monSift == false return to
//the beginning and start again generating a new number"
} while ("Employee" + randomNumber).monShift == false);
return Employees[randomNumber];
}
}
So here's the question I need to answer: Implement a method that takes a research area as an input and returns the names of scientists associated with that area.
I've got a lot of the base code necessary but am struggling because I am trying to filter out the array of scientist professions to only return the scientist whose profession is the specified input. What I need help with is finding a way to make a new array with only certain filtered scientists and excluding the unspecified scientist. Any idea on how to change the code to return an array of only certain scientists would be very helpful! The issue is in the CheckField method, and I'll put my code below of the program:
public class computerScientists {
String name;
String researchArea;
String contribution;
// Constructor
public computerScientists(String NM, String RA, String C) {
this.name = NM;
this.researchArea = RA;
this.contribution = C;
}
public static void main(String[] args) {
computerScientists[] personDatabase = {
new computerScientists("Katherine Johnson", "Mathematician", "Mathmetician for NASA during space race"),
new computerScientists("Kimberely Bryant", "Entrepreneur & Activist", "Founded black girls code"),
new computerScientists("Mark Dean", "Inventor and Engineer", "Helped design and release some of the first computers"),
new computerScientists("Marie Van Brittan Brown", "Inventor and Pioneer", "Pieneered and invented an audio-video alarm system"),
new computerScientists("Marian R Croak", "Engineer", "Helped develop the Voice Over Internet Protocol (VOIP)")
};
//int size = person1.length
for(int i=0; i<personDatabase.length; i++){
System.out.println("Innovator " + String.valueOf(i + 1) + ": \n");
System.out.println("Name: " + personDatabase[i].name + "\n"
+ "Research Area: " + personDatabase[i].researchArea + "\n"
+ "Contribution: " + personDatabase[i].contribution);
System.out.println();
}
checkField("Inventor", personDatabase);
}
public static computerScientists[] checkField(String researchField, computerScientists[] array1) {
computerScientists[] newArray1 = new computerScientists[array1.length];
//int difference = newArray1.length - array1.length;
for (int i=0; i < array1.length; i++) {
if (array1[i].researchArea.contains(researchField)) {
newArray1[i].researchArea = String.valueOf(array1[i]);
}
}
for (int j=0; j<newArray1.length; j++) {
System.out.println(newArray1[j].researchArea);
}
return newArray1;
}
}
i'm trying to create a void method that will read csv file and count the reputaion number of state such that how many times TX,how many times Oh and how many times of Dc. the out should be-TX=4; Oh=2;DC=2. but my out put is "For input string: "F" "- and i really couldn't get where is the problem.can someone help me?
"Crimerate.csv"
State county Rate
Tx,DALLAs,39
TX,Aderson,10
Oh,Archer,20
DC,DC,50
Tx,Houston,31
TX,Claude,13
Oh,Bexar,10
DC,SE,40
public static void countnumber()
{
try{
List<String>number=Files.readAllLines(Paths.get("Crimerate.csv"));
double sum=0,num=0;
for (String line:number){
if(num==0){
++num;
continue;
}
line=line.replace("\"","");
String []result=line.split(",");
double close = Double.parseDouble(result[6]);
String numberAsString = Double.toString(close);
if(numberAsString.equals("Tx"))
{
sum++;
System.out.println("number of Tx =" + sum);
}
else if(numberAsString.equals("Oh"))
{
sum++;
System.out.println("number of Oh =" + sum);
}
else if(numberAsString.equals("Dc"))
{
sum++;
System.out.println("number of Dc =" + sum);
}
}
}catch(Exception e){
System.out.println(e.getMessage());
}
}
public static void main (String args[])
{
countnumber();
}
While the previously suggested answers will address the specific question of why there was only a single response (a result of having only a single sum variable), they have two issues.
They are not accounting for the fact that in the example data, Texas is shown both as "Tx" and "TX". Thus, the current other answers will not give the correct result of 4 for Texas (they will only show 2).
The approaches assume that the full data set was shown. If other states are present, then the code would need to be continually expanded to support the new states.
This solution handles both situations.
public static void main(String[] args)
{
Map<String, Integer> countByState = new HashMap<>();
List<String> number;
try {
number = Files.readAllLines(Paths.get("f:/tmp/Crimerate.csv"));
int cntr = 0;
for (String line : number) {
// skip first line
if (cntr++ == 0) {
continue;
}
String []result=line.split(",");
// should add error checking
String state = result[0].toUpperCase();
Integer cnt = countByState.get(state);
if (cnt == null) {
cnt = new Integer(0);
}
countByState.put(state, ++cnt);
}
System.out.println(countByState);
}
catch (IOException e) {
e.printStackTrace();
}
}
Sample Results based upon the data presented in the question (there is only one DC in that data):
{TX=4, OH=2, DC=1}
int txCount = 0;
int ohCount = 0;
int dcCount = 0; //create this variables inside the class(instance variables)
if(numberAsString.equals("Tx"))
{
++txCount;
System.out.println("number of Tx =" + txCount);
}
else if(numberAsString.equals("Oh"))
{
++ohCount;
System.out.println("number of Oh =" + ohCount);
}
else if(numberAsString.equals("Dc"))
{
++dcCount;
System.out.println("number of Dc =" + dcCount);
} //its better if u use equalsIgnoreCase on if Statements
you were referring to same sum variable on each if loops, i have fixed that .
i assume that the code you have written on reading the file is correct.
You just need different sum variables for each sum. And print the results after the loop.
try{
List<String>number=Files.readAllLines(Paths.get("Crimerate.csv"));
double sumTx=0,sumOh=0,sumDc=0,num=0;
for (String line:number){
if(num==0){
++num;
continue;
}
line=line.replace("\"","");
String []result=line.split(",");
double close = Double.parseDouble(result[6]);
String numberAsString = Double.toString(close);
if(numberAsString.equals("Tx")) {
sumTx++;
} else if(numberAsString.equals("Oh")){
sumOh++;
} else if(numberAsString.equals("Dc")){
sumDc++;
}
}
System.out.println("number of Tx =" + sumTx);
System.out.println("number of Oh =" + sumOh);
System.out.println("number of Dc =" + sumDc);
}catch(Exception e){
System.out.println(e.getMessage());
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have two classes, MarathonAdmin and Runner.
I want to sort list (runners) holding objects of Runner class. I have done all
the coding up to the method sortRunnerList, which says sort the list. I have created
a compareTo method in Runner class and when I compare objects of Runner, they pick the default time values not the ones which I have assigned to objects generating random numbers (done in MarathonAdmin class).
Can someone help with this issue?
class Marathon
import java.util.*;
import java.io.*;
import ou.*;
import java.util.Random;
public class MarathonAdmin
{
// instance variables - replace the example below with your own
private List<Runner> runners;
private String ageGroup;
private String age;
private Random randomNumber;
private String result;
String ageRunner;
String ageGrouprunners;
Scanner lineScanner;
int ans ;
Runner runnerobj = new Runner();
Runner obj2 = new Runner();
public MarathonAdmin()
{
runners = new ArrayList<>();
}
public void readInRunners(){
String pathName = OUFileChooser.getFilename();
File aFile = new File(pathName);
String nameRunner;
BufferedReader bufferedFileReader = null;
try
{
bufferedFileReader = new BufferedReader(new FileReader(aFile));
String currentLine = bufferedFileReader.readLine();
while ( currentLine != null){
lineScanner = new Scanner(currentLine);
lineScanner.useDelimiter(",");
nameRunner = lineScanner.next();
ageRunner = lineScanner.next();
if (Integer.parseInt(ageRunner) < 18)
{
result = "junior";
System.out.println(currentLine +" category" + " : Junior");
}
if (Integer.parseInt(ageRunner) > 55)
{
result = "senior";
System.out.println(currentLine +" category"+ " : Senior");
}
if (Integer.parseInt(ageRunner) > 18 && Integer.parseInt(ageRunner) < 55)
{
result = "standard";
System.out.println(currentLine +" category"+ " : Standard");
}
ageGrouprunners = result;
Runner runnerobj = new Runner();
runnerobj.setName(nameRunner);
runnerobj.setAgeGroup(ageGrouprunners);
System.out.println(runnerobj); //rough test
runners.add(runnerobj);
currentLine = bufferedFileReader.readLine();
}
}
catch (Exception anException)
{
System.out.println("Error: " + anException);
}
finally
{
try
{
bufferedFileReader.close();
}
catch (Exception anException)
{
System.out.println("Error: " + anException);
}
}
}
public void runMarathon(){
int size = runners.size();
// for ( int runnersIndex = 0; runnersIndex <= size; runnersIndex ++ ){
for( Runner nameRunner : runners){
this.randomNumber = new Random();
ans = randomNumber.nextInt(190 - 80 +1 ) + 90 ;
System.out.println(ans);
nameRunner.setTime(ans);
}
}
public void sortRunnerList(){
for(Runner nameRunner : runners){
int time = nameRunner.getTime();
System.out.println(time);
Runner obj = new Runner();
obj.setTime(ans);
int res = nameRunner.compareTo(obj);
System.out.println(res);
}
}
}
//(This is method of class Runner)
Class Runner
Method compareTo()
#Override
public int compareTo(Runner anotherRunner)
{
return this.getTime()-(anotherRunner.getTime());
}
Try replacing
return this.getTime()-(anotherRunner.getTime());
with
return Integer.valueOf(this.getTime()).compareTo(anotherRunner.getTime());
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am a beginner in java programming. I am trying to recreate a simplified version of the card game war. I ran my program which is posted below and it came back with this error:
Exception in thread "main" java.lang.NullPointerException
at cardgame.BuildDeck(cardgame.java:36)
at cardgame.main(cardgame.java:60)
I have been trying to solve this issue on my own through research, but I could not solve it. I was wondering if anyone can help me. If you do need any other information about my program, please just ask. Thanks in advance!
-FGxMatta
public class cardgame
{
static class TheCard
{
// Java getter & setter
private String CardName;
private int CardRank;
private int Chosen;
public TheCard(int rank, String name)
{
this.CardName = name;
this.CardRank = rank;
this.Chosen = 0;
}
}
#SuppressWarnings("null")
private static TheCard[] BuildDeck()
{
TheCard[] TheDeck = null;
String[] Cards = {"2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"};
String[] Suits = {"Spades","Hearts","Diamonds","Clubs"};
int[] Rank = {2,3,4,5,6,7,8,9,10,11,12,13,14};
int cardnumber = 0;
for (int i = 0; i < Cards.length; i++)
{
for (int j = 0; j < Suits.length; j++)
{
String deckcard = Cards[i];
String suitcard = Suits[j];
String cardname = deckcard + "-" + suitcard;
TheDeck[cardnumber] = new TheCard(Rank[i], cardname);
cardnumber++;
}
}
return TheDeck;
}
private static TheCard GetRandomCard(TheCard[] OrderedDeck)
{
TheCard thecard;
int random = (int) (51*Math.random ());
thecard = OrderedDeck[random];
if (thecard.Chosen == 0 ) // if available...
{
thecard.Chosen = 1; // mark it taken...
return thecard;
}
else
{
return GetRandomCard(OrderedDeck);
}
}
public static void main(String args[])
{
TheCard[] OrderedDeck = BuildDeck();
System.out.println ("Welcome, Prepare for War!");
int decksize = OrderedDeck.length;
int player1wincount = 0;
int player2wincount = 0;
int tiecount = 0;
for (int cardcount = 0; cardcount < decksize;)
{
TheCard Player1 = GetRandomCard(OrderedDeck);
cardcount++;
TheCard Player2 = GetRandomCard(OrderedDeck);
cardcount++;
System.out.println ("Player 1's card is: " + Player1.CardName);
System.out.println ("Player 2's card is: " + Player2.CardName);
if (Player1.CardRank > Player2.CardRank)
{
System.out.println("Player 1 wins this hand");
player1wincount++;
}
if (Player1.CardRank < Player2.CardRank)
{
System.out.println("Player 2 wins this hand");
player2wincount++;
}
if (Player1.CardRank == Player2.CardRank)
{
System.out.println("Player 1 and Player 2 played the same valued card");
tiecount++;
}
}
System.out.println ("Player 1 won " + String.valueOf(player1wincount) + " hands");
System.out.println ("Player 1 won " + String.valueOf(player2wincount) + " hands");
System.out.println ("There were " + String.valueOf(tiecount) + " ties");
}
}
Replace:
TheCard[] theDeck = null;
with:
TheCard[] theDeck = new TheCard[Cards.length * Suits.length];
and move it to below the declarations for Cards and Suits.
Null Pointer Exception is a situation in code where you try to access/ modify an object which has not been initialized yet. It essentially means that object reference variable is not pointing anywhere and refers to nothing or ‘null’. A simple example can be:
package au.com.copl;
public class Demo{
public static void main(String[] args) {
String d = null;
System.out.println(d.toString()); // d is un-initialized and is null
}
}
right here
TheDeck[cardnumber] = new TheCard(Rank[i], cardname);
you never initialized TheDeck. You probably want something like
TheDeck = new TheCard[52];
before you start putting things in the array.
as a note, java convention is that variable names be camel cased. So "CardName" should be cardName. Just a convention.
TheCard[] theDeck = null; ?
dont you need to inialize it?
You should also use new in main method:
TheCard[] OrderedDeck = BuildDeck();
should be replaced by:
TheCard[] OrderedDeck = new BuildDeck();