Sort Objects From a File [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
(At time of posting, I do not have access to code, will add later)
I have an array of Employee objects, which hold a name, availability, and preferred hours. And I sort the objects by Alphabetical order, according to the employees name.
When the program starts, it checks the files, and if they are empty, it asks you how many employees, and then you proceed to fill in the data. And it sorts properly A-Z.
This issue comes that when I try to add a new employee, after resizing the array, it adds it to the end, even though the sort completes.
So it sorts the first time, but not again after re running the program. I will post the code when I get home, but wanted to see if anyone had any answers in the mean time. Thank you
static void employeeSort(Employee[] emply, int size)
{
int i;
Employee temp;
boolean flag = true;
while(flag)
{
flag = false;
for(i = 0; i < size; i++)
{
if (emply[i].getName().compareTo(emply[i+1].getName())>0)
{
System.out.println(emply[i].getName());
temp = emply[i];
emply[i] = emply[i+1];
emply[i+1] = temp;
flag = true;
}
}
}
}
On the first run through, it sorts everything correctly, but once the array is read from a file, the program terminates in the sort. I tried implementing the priority queue, but i needed to make the Class comparable, and its already implemented Serializable.
public class Employee implements Serializable
{
int prefHours;
String name;
String avail;
Employee( String nam, int hours, String aval )
{
name = nam;
prefHours = hours;
avail = aval;
}
void prnEmpl()
{
System.out.print("Name: " + name);
System.out.println();
System.out.print("Prefered hours: " + prefHours);
System.out.println();
System.out.print("Availability: " + avail);
System.out.println();
}
String getName()
{
return name;
}
String getAvail()
{
return avail;
}
}

Without your code it is hard to figure out what's the problem. As far as I understand I think you should use java.util.PriorityQueue instead of Array.

Related

Projekt Hangman game [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am a beginner in Java and I am working right now with a small projekt, a hangman game. One of the functions I am working on right now is a method where it takes a char input, check if the input is already added to the list or not, if it is, a message will show up saying "You have already used that character!" and the user will have to guess again, otherwise the input will be added to the list. My issue right now is that nothing is happening, inputs are not added to the list at all.
This is what I have done so far:
Any advice/help would be appreciated!
public static ArrayList<Character> getGuesses(ArrayList<Character> allGuesses, char input){
for (int i = 0; i < allGuesses.size(); i++) {
if (allGuesses.get(i) == input) {
System.out.println("You have already used that character!");
}else {
allGuesses.add(input);
}
}
return allGuesses;
}
You are adding the input character on each iteration as you search the collection. You should only add it after you have searched the collection and not found it.
for (int index = 0 ; index < allGuesses.size() ; ++index) {
if (allGuesses.get(index) == input) {
System.out.println("You already used that character!");
return allGuesses;
}
}
allGuesses.add(input);
return allGuesses;
However, this can be simplified by using the Collection contains method such that you do not employ a loop.
if (allGuesses.contains(input)) {
System.out.println("You already used that character!");
return allGuesses;
}
allGuesses.add(input);
return allGuesses;
If possible, consider switching the type of allGuesses to a Set implementation (e.g. HashSet). A Set seems to better match how you are using your collection and allows you to reduce this method to...
if (! allGuesses.add(input)) {
System.out.println("You already used that character!");
}
return allGuesses;

Can't reach information Java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm writing a program with 3 options. So the first one is about the employee- (create / remove / update / get information about employee / save to file). Before creating a new employee I have to choose his type(programmer or qa)(difference between them is that programmer have a specific programming language and qa have amount of worked hours). So moving forward when I create a new user I have to enter name / surname / age / prog.language;
The second option in my program is that I can create a team which must be made from 3 employees. So from a list of employees you select one for team lead and other 2 for 'workers'.
And the last one is that you can create a task.
(you need to give a name for task, specific language which is required from a second team member and amount of worked hours from a third member). So this task can be later assigned to a specific team.
So lets talk about my problem right now:
Creating new employees, making new teams works 100%, also creating new tasks works fine as well, but when I try to check does my selected team meets requirements for tasks I'm receiving tons of errors. I've tried to select specific member from a team and check his programming language and receiving null. However, after debugging I saw that information comes,but when i try to reach exactly that language appears null.
Here's my code how looks my programmer class:
package com.wep;
public class Programuotojas extends Darbuotojas {
protected String programavimoKalba;
#Override
public String toString() {
return "Programuotojas: " + vardas + ",pavarde " + pavarde + ",amzius " + amzius + ",programavimo kalba " + programavimoKalba;
}
public Programuotojas(String vardas, String pavarde, int amzius, String programavimoKalba) {
super(vardas, pavarde, amzius);
this.programavimoKalba = programavimoKalba;
}
Programuotojas(){}
public String getProgramavimoKalba() {
return programavimoKalba;
}
public void setProgramavimoKalba(String programavimoKalba) {
this.programavimoKalba = programavimoKalba;
}
}
And here's my try to check his language:
KomanduValdymas.getInstance().komanduArray.get(0).getPirmasDarbuotojas(programuotojas.getProgramavimoKalba());
KomanduValdymas is a class where I create new teams. If u need more code from there let me know. Thanks, hope you guys got my problem
private void pridetiDarbuotoja() {
System.out.println("[1] Pridėti programuotoją");
System.out.println("[2] Pridėti testuotoją");
Scanner SI = new Scanner(System.in);
int userSelects = Integer.parseInt(SI.nextLine());
if (userSelects == 1) {
System.out.println("Iveskite:");
System.out.println("Varda, pavarde, amziu, darbine programavimo kalba");
String enters[] = SI.nextLine().split(" ");
darbuotojuArray.add(new Programuotojas(enters[0], enters[1], Integer.parseInt(enters[2]), enters[3]));
System.out.println("Darbuotojas itrauktas i sarasa");
} else {
System.out.println("Iveskite:");
System.out.println("Varda, pavarde, amziu, isdirbtas testavimo valandas");
String enters[] = SI.nextLine().split(" ");
darbuotojuArray.add(new Testuotojas(enters[0], enters[1], Integer.parseInt(enters[2]), Integer.parseInt(enters[3])));
}
darbuotojuValdiklis();
}
You appear to be under the impression that creating a new Programuotojas will update the value of your variable programuotojas automatically. That is not the case.
You need a statement that starts with programuotojas = in order to affect such a change.

Problems with calling a method using an array

I'm relevantly new to Java and just started my first semi serious assignment. I'm confident most of my code is working, the only problem is because I've been using classes I can't seem to call a method which uses an array into my main class. Every other method I want to call seems to work. I wonder if anyone has any explanation or easy solution to this?
Thanks in advance for taking time looking into, really appreciate it!
import java.util.Scanner;
public class GeographyQuizMain
{
public static void main(String[] args)
{
takeQuiz();
}
public static void takeQuiz(Question[][] questions)
{
int score = 0;
RandomNumber randomQuestion = new RandomNumber();
//user chooses catergory
int cat = pickCatergory();
//ask 10 questions
for(int i = 0; i < 10;)
{
Scanner answerChoice = new Scanner(System.in);
randomQuestion.dice();
int q = (randomQuestion.dice() - 1);
//checks to see if question as been asked before
if (!questions[cat][q].beenAsked)
{
questions[cat][q].beenAsked = true; //changes question status to beenAsked
System.out.println(questions[cat][q].promt);
String answer = answerChoice.nextLine();
System.out.println("\nYou picked: " + answer + "\nThe correct answer was: " + questions[cat][q].answer + "\n");
if(answer.equals(questions[cat][q].answer))
{
score++;
}
i++;
}
}
System.out.println("That is the end of the quiz!\n"
+ "You got " + score + "/10");
}
Your problem is with the call itself,
This line public static void takeQuiz(Question[][] questions) states that the method will accept a two dimensional array ([][]) of an object named Question.
On the other hand, your call - takeQuiz(); passes no array of such.
You should initialise an array of such to make this compile and pass it to the function. i.e.
Question[][] questionArray = GenerateQuestionArray(); //you should write this method
takeQuiz(questionArray);
Like you stated, it's clearly you're new to Java and I strongly suggest you to read the instructions and the information provided to you in class about that. I bet the details of Object initialisation, methods and arrays are covered there.
It seems that problem with your method call, in your method takeQuiz(); is taking 2 dimensional array for questions but at the calling time you are not providing that parameter so, compiler not able to found the method.
That's the problem.
try to use like this, this is simple an example for you. replace this with your actual values.
String[][] questions= new String[3][3];
takeQuiz(questions);
this will work.
You have called your method takeQuiz() without actually supplying its arguments Question[][] questions

NullPointerException error in Java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm making a class involving objects. I'm having trouble with the retrieveMessage method, because when I test it, it returns a NullPointerException.
public class PostOffice
{
public PostOffice(int size)
{
boxbox = new Letter[size];
}
public boolean placeLetter(Letter mail, int boxNum)
{
if(((boxNum>(boxbox.length-1))||(boxNum<0))||(boxbox[boxNum]!=null))
return false;
else{
boxbox[boxNum]=mail;
return true;
}
}
/**Returns the message contained within the Letter located in the specific box number.
* Returns "Empty!" if the post office box specified by the integer does not contain a Letter.
* Returns "Box does not exist!" if there is no box with the specified integer.
* #param boxNum The post office box number to be checked.
*/
public String retrieveMsg(int boxNum)
{
if(boxNum<=boxbox.length-1)
{
String swag = boxbox[boxNum].getMsg();
if(swag!=null && swag.isEmpty()==false)
{
return swag;
}
return "Empty!";
}
return "Box does not exist!";
}
public Letter findSender(String name)
{
String sender;
int index =0;
for(int i = 0; i<boxbox.length; i++)
{
if((boxbox[i].getSender()).equals(name)){
index= i;
}
else{
return null;
}
}
return boxbox[index];
}
}
I guess the NullPointerException is thrown on this line :
String swag = boxbox[boxNum].getMsg();
When created, boxbox have size values, all of them are null.
You should first check if boxbox[boxNum] is null or not. If it is, it means that the post box does not contain a letter.

Obtain the largest number in an array of numbers [closed]

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 8 years ago.
Improve this question
This is my first time doing java and I am am trying to get the largest number from an array of x numbers using a method called bigNum(). Can anyone tell me why this doesn't work?
class project3
{
public static void main(String args[])
{
int total =0;
int b;
System.out.println("How many numbers do you want in the array");
int maxItems = EasyIn.getInt();
int[] numbers = new int[maxItems];
for (int i=0; i < maxItems; i++)
{
b = EasyIn.getInt();
}
bigNum(b);
}
public static void bigNum(int maxItems)
{
for (int i = 1; i >= maxItems; i++)
{
if (bigNum(b) >= maxItems)
bigNum(b) = maxItems;
}
return bigNum(b);
}
}
You're probably getting compiler errors at this point due to unmatched braces. You want your program to have matched braces, and you also want to avoid having methods inside of other methods.
You want to have something that has the following form
class project3
{
public static void main(String args[])
{
...
}
public static int bigNum(int maxItems[])
{
...
return someInt;
}
}
// capital letter for the class (convention)
public class Project3 {
public static void main(String args[]) {
//int total = 0; // you never used this number
System.out.println("How many numbers do you want in the array");
int maxItems = EasyIn.getInt();
int[] numbers = new int[maxItems];
for(int i = 0; i < maxItems; ++i) {
int newNumber = EasyIn.getInt();
/* you want to put the numbers into an array,
so don't call "bigNum" but put them there: */
numbers[i] = newNumber;
}
// now find the big number:
int bigNumber = bigNum(numbers);
System.out.println("The biggest number: " + bigNumber);
}
// first: change the return type to get the biggest number
// second: pass the reference to the array, not a single number
// public static void bigNum(int maxItems) {
public static int bigNum(int[] items) {
// create big number, assume it's very small:
int bigNumber = Integer.MIN_VALUE;
// this for loop will never run, change it a bit:
//for(int i = 1; i >= maxItems; i++) {
for(int i = 0; i < items.length; i++) {
// your idea is correct, but you can not use the
// method here, see explanations below
// Also don't check for the number of Items, but for
if(items[i] > bigNumber) {
bigNumber = items[i];
}
}
return bigNumber;
}
}
Explanations and further readings
Class name: Java has lots of different naming conventions, but the most common rules are: ClassNames/Types in CamelCase with a Capital at the beginning, variableNames following a similar convention but with a leading small letter. This makes it much easier to read code.
Indentation: Try to use a more consistent indentation. Also supports readability. Actually some other programming languages even rely on correct indentation.
Try to understand what variables and what methods are and how to use them (and return from them, you can not assign values to a method in Java. While you read the latter tutorial focus on return types and how to call methods correctly, you can not return an int when your method is of type void. Also the parameters need to be exactly defined.
Apart from that try to compile your code before you post it. As your code went, it should have thrown lots of compile errors, e.g. bigNum(b) = maxItems; should tell you that the left-hand side of an assignment needs to be a variable. This can help you a lot while tracking down mistakes.
Another error is that for most people EasyIn will not be defined (as it is for me, so the code I posted above might actually not be working, I didn't try). I suppose it's a learning library (we had our AlgoTools back in our first Java lectures). Still it would be nice to tell us what it is and what other imports you use (common mistake when I let my IDE decide my imports for me: java.util.Date and java.sql.Date).
Also try to make clear to yourself what you want to achieve with your program and how. Your algorithm actually looks like you didn't think too much about it: You try to find a biggest number and always check "a big number" against the number of expected items, which then might become "the big number" as well. Or something like that.
Programming is being concise and exact, so make a plan before. If it's too hard for you to think about a solution directly, you can maybe draw it on paper.
And if you then have problems, after compiling, asking your program, asking google, asking stack overflow: provide us with as many details as you can and we will be able to help you without just posting some code.
Good luck!

Categories

Resources