Can't reach information Java [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 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.

Related

trying to get an int and a double from my main method to a non-static method [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
Improve this question
I'm working on a project for school and I've run into a wall where I need to get a user inputted Int and double from my main method to a required non-static method. this non-static method is supposed to be used for the calculation and printing of the answer based on the price (double) and the amount paid (int).
public static void main (String[] args){
Scanner check = new Scanner(System.in);// import of the scanner
char cents = '\u00a2';//Unicode of cent symbol
System.out.print("Your item costs (25" + cents + " minimum, Increments of 5" + cents + "): ");
Double price = check.nextDouble(); //price of the item
System.out.println("You paid (whole dollars only): ");
int paid = check.nextInt(); //amount paid
VendingChange newVend = new VendingChange();//creates a copy of the class
newVend.Secondary();// calls the nonstatic
that's the main method
public void Secondary () {
System.out.println("your change is " +/*this is where the equation is supposed to go*/ );
and this is the non-static
I've tried adding an extra static method, which eliminated the errors, but the int and double still wouldn't go through. meaning I can't use the int and double in any other method, because it doesn't recognize the names.
try replacing
Double price = check.nextDouble();
with
double price = check.nextDouble();
or even
String price1 = check.nextLine(); // gets input in form of string
double price = Double.parseInt(price1); // converts to double
Similarly, integers can also be changed:
int paid = check.nextInt();
to
String paid1 = check.nextLine();
int paid = Integer.parseInt(paid1);
I would also recommend reading (as mentioned in the comments) tutorials and really understanding the difference with static and non-static methods (instance).
(uppercase represents the class, while lowercase represents an instance)
Let's say we have a Person class. A static method would be like
Person.getPopulation(). That would return the population. This method is not instance (person) specific, rather it applies to the type of thing a person is.
An instance method would be better when you have something like person.changeName(). This would change the name of a person. An instance of a person. However, if you create it static, like Person.changeName(), which person's name would you be changing?
Think of the class Person like a type of object. People are objects (in this analogy). Person class is a type. Every person instance is every person that lives (in the program).
This same 'type of thing' vs actual 'thing' that exists under that type can be applied to a lot of things in programming, and is the basis of Object Oriented Programming (OOP).

Sort Objects From a File [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 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.

Creating a database of foods in Java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
Ive just started learning Java and I spent most of the day watching video tutorials, however now I've decided to do something practical, as I dont think I can absorb anymore information today.
I had an idea to develop a fitness app a while ago, but was hit by how difficult that actually is without any knowledge, so I thought I will start by just creating a macro counter. I created a class:
public class Food {
private String name;
public int weight;
private int calories;
private int protein;
private int fat;
private int carbs;
public int tCals = weight * calories;
public int tProtein = weight * protein;
public int tFat = weight * fat;
public int tCarbs = weight * carbs;
public void macrocounter(){
System.out.println("Total calories: " + tCals);
System.out.println("\nProtein: " + tProtein);
System.out.println("\nCarbs: " + tCarbs);
System.out.println("\nFat: " + tFat);
System.out.println("-------------");
}
}
Now what I am having problems with is creating a database. I want to add at least 10 simple meals to begin with, they would all have the macros set in stone, the user would just type in the name of the meal and how many grams he ate, then the app would recognize the food from the database, fill in weight, and print out the total macros.
I am not asking here how to write the specific code, just can you point me to what I should read up on more to be able to do this? Java is an insanely vast language, and I am having trouble to find the actual information I need on creating a database.
Thank you.
Some oneline tutorials are good. But I would consider investing in a good Java book. I found BigJava Cay S. Horstmann a really helpful source of information. It gives you plenty of exercises and opportunity to practice code, and explains things in a very clear way. I would only go to online tutorials if I had trouble following a certain methodology in a book. But I wouldnt use them as a learning resource, as they may not be correct.
It is an expensive book though but you might be able to get an older edition for cheeap or a second hand copy. Oracle's website also has useful written tutorials for you to follow https://docs.oracle.com/javase/tutorial/ But I found the book easier to follow.
You want just to store the data in main memory? or in a real database to disk?
If it is the first option, you can do this:
ArrayList<Food> foods = new ArrayList<Food>();
Once you have your list, you can add things like this:
Food f = new Food(...data...); //You need a constructor
//to pass the data.
foods.add(f);
To consult it you can do a number of things:
Food f0 = foods.get(0);
Food f1 = foods.get(1);
You can also query for a particular object:
if (foods.contains(f0) {
// ...
}
Google for "java class ArrayList" and you'll see what you can do.
If, on the contrary, you want to create a real database, you need to read about JDBC drivers. To begin, I recommend you sqlite.
package consultarcalibredb;
import java.sql.*;
public class ConsultarCalibreDB {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Connection conn = null;
int id;
String title, author, path;
try {
DriverManager.registerDriver(new org.sqlite.JDBC());
conn = DriverManager.getConnection("jdbc:sqlite:/home/user/folder/file.db");
String sql = "select id, title, author_sort, path from books where author_sort like '%orwell%'";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
System.out.println("id\ttitulo\tautor\tpath");
while (rs.next()) {
id = rs.getInt("id");
title = rs.getString("title");
author = rs.getString("author_sort");
path = rs.getString("path");
System.out.println(id+"\n"+title+
"\n"+author+"\n"+path);
System.out.println();
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Thank you for your help, I got a lot of suggestions on what I should learn and from where. I dont know how to close the question, but if you do, please do so.

Beginner Java Scope Issue [duplicate]

This question already has an answer here:
Beginner Java: Variable Scope Issue
(1 answer)
Closed 7 years ago.
I'm new to programming and seem to be running into issues with when a variable, class, etc can and can't be referenced. Below is an example, hoping one of you can fix the specific issue but also help me understand it more broadly so I don't run into it again and again.
to try and avoid posting a bunch of code please note that a Question class is defined as well as a setText, setAnswer, checkAnswer, and display method are all defined elsewhere (all public).
The relevant code is below and I have two questions:
Why is the variable first not recognized in the method presentQuestion()?
At the very end there, why can't I just call the method checkAnswer() on first, i.e. why can't I just do first.checkAnswer(response);? Why do I have to define it in a new variable: boolean outcome = first.checkAnswer(response);?
Code:
/**
* This program shows a simple quiz with two questions.
*/
public class QuestionDemo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Question first = new Question();
first.setText("Who was the inventor of Java?");
first.setAnswer("James Gosling");
Question second = new Question();
second.setText("Who was the founder of Udacity?");
second.setAnswer("Sebastian Thrun");
int score = 0;
score = score + presentQuestion(first, in);
// Present the second question
score = score + presentQuestion(second, in);
System.out.println("Your score: " + score);
}
/**
* Presents a question to the user and obtains a response.
* #param q the question to present
* #param in the scanner from which to read the user input
* #return the score (1 if correct, 0 if incorrect);
*/
public static int presentQuestion(Question q, Scanner in) {
// Display the first question
first.display();
System.out.println("Your answer:");
String response = in.nextLine();
// Check whether the response was correct
// If so, print "true" and return 1
// Otherwise, print "false" and return 0
boolean outcome = first.checkAnswer(response);
System.out.println(outcome);
if (outcome) {
return 1;
}
else {
return 0;
}
}
}
The reason you can't use the variable first inside presentQuestion is because it's defined in main, and therefore not visible outside of main. Isn't this precisely why you gave presentQuestion its Question q parameter, however?
It seems to me that this is what you want to do:
public static int presentQuestion(Question q, Scanner in)
{
// Display the first question
q.display();
System.out.println("Your answer:");
String response = in.nextLine();
// Check whether the response was correct
// If so, print "true" and return 1
// Otherwise, print "false" and return 0
boolean outcome = q.checkAnswer(response);
System.out.println(outcome);
if (outcome) {
return 1;
} else {
return 0;
}
}
Note that references to first have been replaced by references to q.
To try and clear up what I imagine your confusion may consist in, imagine if presentQuestion were called from another method than main, in which case no first variable would be declared at all. What would then happen to the references to first inside of presentQuestion, now not referring to anything at all? This is why you need to explicitly pass the data you want as parameters. Different methods are independent blocks of code, and you can't intermingle variable references between them even if they happen to call each other.
As for question 2, there should indeed be no problem with checking if(q.checkAnswer(response)) directly, without using the outcome variable. I'm guessing you were simply confused by the error emitted by the compiler when first wasn't recognized again.
first is a local variable, that means it can only be accessed inside the method in which it is defined.
You don't have to put the result of checkAnswer() into a boolean before using it. Actually, if (checkAnswer(response)) { ... } is valid.
presentQuestion takes a question as a parameter. In main, you're calling it on the first question, and then on the second question; it looks like the intent is that you use presentQuestion on the first question, and then on the second question. So far, so good.
The problem is that in presentQuestion, you're referring to the question (which could be the first or the second question) as q in the parameter list. All you need to do is use q instead of first in the rest of the method.
When I was new to programming, I had this problem as well! Then I found out it is very simple.
For your first question, first is declared in the main method and you want to use it in presentQuestion method. But presentQuestion and main are different methods! So you can't get to first in presentQuestion. As you can see, there is a Question-typed parameter in the presentQuestion method. This is like you telling first, "Come here, man! And then change your name to q." When you do pass the argument first to presentQuestion,
presentQuestion (first, in);
first comes to the pressentQuestion method with its name being as q. So you should use q instead of first in the presentQuestion method.
Now the second question, using a variable in this context is not needed. But to increase efficiency, use a boolean variable to store the result of checkAnswer. Let's imagine what happens if you don't use a boolean variable.
System.out.println(q.checkAnswer(response));
if (q.checkAnswer(response)) {
return 1;
} else {
return 0;
}
See? you called q.checkAnswer twice! This would slow down your program so you should use a boolean variable.

How did I get the result of '6.03' and '23.24'? - Java Parameter Return [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 wonder how did I get the result of '6.03' and '23.24'? System.out.println(a+b+c) does not add up to those 2 numbers?
Why is there a return c + "" + a? There is no output result show c + a?
The full code as follows:
MyProgram:
public class MyProgram
{
public void start()
{
String result;
result = lots(2+1, 3, "3");
result = lots(22, 1.2, "4");
}
private String lots(int a, double b, String c)
{
System.out.println(a+b+c);
return c + "" + a;
}
}
MyApplication:
public class MyApplication
{
public static void main (String[] args)
{
MyProgram p = new MyProgram();
p.start();
}
}
It makes sense because you're concatenating some string at the end of all of that math.
For the first run, you pass in 3 and 3.0 as your first two numerical parameters. That adds to 6.0 (it's been since upcast to double). You now then do string concatenation on 3 to arrive at 6.03 for your answer.
Trace through the second execution of the method to arrive at a similar answer. Remember: + is overloaded in Java to mean either numeric addition or string concatenation.
You overwrite result after you get it the first time, but even then, you don't do anything with it. I'd argue that you don't really need the return statement. If it were there, then you'd actually return the string 422*, since again, it's all string concatenation at that level.
*: This is from the last standing run if you printed it out after both were executed. If it were printed out each time, you'd see 22 first.
a+b+c is (a+b)+c
The first addition adds the two numbers.
The second addition converts the result of the addition into a string, then concatenates it with the final string.
So ((2+1) + 3) = 6.0
and 6.0 + "3" = "6.0" + "3" = "6.03"

Categories

Resources