Creating a database of foods in Java [closed] - java

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.

Related

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.

What is the best data structure that represents the following data type? [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 6 years ago.
Improve this question
I have data type of the following format:
Popularity:xx
Name:xx
Author:xx
Sales:xx
Date Published: xx
I am free to choose whatever way I can store my data in.
I will need to perform some queries on the data, for example
What are the top 'N' Books for the year 'M'
What are the average sales of the top 'N' songs for author 'X'?
It should be kept in mind that further queries may be added.
What will be the different ways to represent the data to perform the queries (in Java)? What will be the merits?
Note: (Not looking for a DB solution)
JDK comes bundled with Java DB and seems perfectly fine for your use case.
Edit: Sorry I misread the question as a dB solution because it seems you need it. That said you should look for a DB solution where you just query your books from.
If you actually do want to perform queries on data-structures in memory you can use Apache Commons Collections which support filtering.
If you do want to use a data-structure like a Vector which seems like a solution, you need to build indexes to improve performance. Then lookup in the indices and get the book needed. If you know which searches are necessary you can group chosen indexes and create a block to easily search. Essentially creating your own cube data-structure. Could be a nice project.
Arraylist of a class. Create a class with those variables as, well, class variables, then instantiate an Arraylist of said object. Then you can perform searches based on the values of certain variables. For example:
//replace "ClassName" with the name of the class
ArrayList<"ClassName"> array = new ArrayList<"ClassName">();
ArrayList<"ClassName"> results = new ArrayList<"ClassName">();
for("ClassName" obj:array)
{
if(obj.getAuthor().equals("Author Name"))
{
results.add(obj);
}
}
There are many ways to sort the results, including using Collections.sort(); which seems to be the best way to go about it.
Sort ArrayList of custom Objects by property
EDIT: I went ahead and gave you an example based on the specific case you outlined in the comments. This should help you out a lot. As stated before, I had a similar issue for a lab in University, and this was a way I did it.
You could use a Bean to wrap your data:
public class Record {
int popularity;
String name;
String author;
int sales;
int yearPublished;
public Record(int popularity, String name, String author, int sales, int yearPublished) {
super();
this.popularity = popularity;
this.name = name;
this.author = author;
this.sales = sales;
this.yearPublished = yearPublished;
}
//getter and setter...
public String toString(){
return name;
}
And this is a typical usage querying with java8:
Record Record1 = new Record(10,"Record 1 Title","Author 1 Record",10,1990);
Record Record2 = new Record(100,"Record 2 Title","Author 2 Record",100,2010);
Record Record3 = new Record(140,"Record 3 Title","Author 3 Record",120,2000);
Record Record4 = new Record(310,"Record 4 Title","Author 1 Record",130,2010);
Record Record5 = new Record(110,"Record 5 Title","Author 5 Record",140,1987);
Record Record6 = new Record(160,"Record 6 Title","Author 1 Record",15,2010);
Record Record7 = new Record(107,"Record 7 Title","Author 1 Record",4,1980);
Record Record8 = new Record(1440,"Record 8 Title","Author 8 Record",1220,1970);
Record Record9 = new Record(1120,"Record 9 Title","Author 9 Record",1123,2010);
List<Record> Records = Arrays.asList(Record1,Record2,Record3,Record4,Record5,Record6,Record7,Record8,Record9);
//top 2 record of year 2010
int m = 2;
int year = 2010;
System.out.println(Arrays.toString(Records.stream().filter(s -> s.getYearPublished() == year).sorted((r1, r2) -> Integer.compare(r2.popularity, r1.popularity)).limit(m).toArray()));
//average top 2 record of Author 1 Record
String author= "Author 1 Record";
int n = 2;
System.out.println(Records.stream().filter(s -> author.equals(s.getAuthor())).sorted((r1, r2) -> Integer.compare(r2.popularity, r1.popularity)).limit(n).mapToInt(Record::getSales).average().getAsDouble());
This prints:
[Record 9 Title, Record 4 Title]
72.5
Having a collection of objects you can use stream api to collect/filter/reduce your results. There is not so much to it.
The main problem is to not load all of the objects to memory and to be able to retrieve them from whatever store efficiently by using indexes, reverse-indexes.
One of the frameworks which came to my mind is Apache spark

How to limit characters on a line and make the display go to the next line

I'd like some help with a Java assignment, if it's no problem. We've just been getting started, but my teacher wants us to do a bunch of research on our own and I can't figure out how to do the homework.
We have an assignment where he's given us the lines to 10 different speeches, and we have to use objective oriented coding to display the entire thing. I figured out so far how to set up variables to link to the first file and have things displayed on the screen, but he wants us to limit how many characters are on each line so he doesn't have to scroll sideways forever to read a speech on a single line. This leaves me in a position where I'd be making new variables for every sentence of every speech for the next few hours, and I figure there has to be a more efficient way. So, I asked my friend (who took the class last year) for advice, and he recommended using a for loop to scan for spaces after a certain amount of characters and jump to the next line to continue, but I have no idea how to do any of this. All I have so far is the base file that our teacher told us to use, and the beginning of the first of 10 speeches.
/**
* TextWriter is a program that uses objective coding to display 10 political speeches
* #author ()
* #version (10/12/16)
*/
public class TextWriter {
private String textToDisplay;//text to be displayed
public TextWriter() {
textToDisplay = "";
}
public TextWriter(String inputText) {
textToDisplay = inputText;
}
public void clearTextToDisplay() {
textToDisplay = "";
}
public void setTextToDisplay(String inputText) {
textToDisplay = inputText;
}
public String getTextToDisplay() {
return textToDisplay;
}
public void display() {
System.out.println(textToDisplay);
}
}
and the second one,
/**
* Displays Washington's Farewell speech using objective oriented coding.
* #author ()
* #version (10/12/16)
*/
public class WashingtonFarewellDriver {
public static void main(String[] args) {
TextWriter wf1;
wf1 = new TextWriter();
wf1.setTextToDisplay("Friends and Citizens: The period for a new election of a citizen to administer the executive government of the United States being not far distant, and the time actually arrived when your thoughts must be employed in designating the person who is to be clothed with that important trust, it appears to me proper, especially as it may conduce to a more distinct expression of the public voice, that I should now apprise you of the resolution I have formed, to decline being considered among the number of those out of whom a choice is to be made.");
wf1.display();
TextWriter wf2;
wf2 = new TextWriter("I beg you, at the same time, to do me the justice to be assured that this resolution has not been taken without a strict regard to all the considerations appertaining to the relation which binds a dutiful citizen to his country; and that in withdrawing the tender of service, which silence in my situation might imply, I am influenced by no diminution of zeal for your future interest, no deficiency of grateful respect for your past kindness, but am supported by a full conviction that the step is compatible with both.");
wf2.display();
TextWriter wf3;
wf3 = new TextWriter("The acceptance of, and continuance hitherto in, the office to which your suffrages have twice called me have been a uniform sacrifice of inclination to the opinion of duty and to a deference for what appeared to be your desire. I constantly hoped that it would have been much earlier in my power, consistently with motives which I was not at liberty to disregard, to return to that retirement from which I had been reluctantly drawn.");
wf3.display();
}
}
(hopefully that's formatted right)
I hope that it's ok that I'm asking for homework help, because it does seem to be kind of looked down upon, but I'm pretty confused and hopefully someone can explain what's going on a little more than my teacher.
Thank you! If there's any questions, I might be able to answer them too.
Loop thru the string character by character using String.charAt(). Keep track of how many characters you've put out. After say 25 characters the next time you see a space spit out a newline character, reset your counter to 0, and start printing it out again.
String in = "This is a run on sentence that is too long for a single line and should be broken up into multiple lines because I said so. This is a run on sentence that is too long for a single line and should be broken up into multiple lines because I said so.";
int counter=0;
for(int i=0;i<in.length();i++){
Char c=in.charAt(i);
counter++;
System.out.print(c+"");
if((counter>25)&&(c=' ')){
System.out.println();
counter=0;
}
}
There are many ways to approach this.
You can add this function in your TextWriter class for adding lines something like this:
public void addLines(int maxChars){
int lines = 1;
String[] lineStrings;
if(maxChars <= textToDisplay.length()){
if(textToDisplay.length() % maxChars > 0) lines = textToDisplay.length()/maxChars + 1;
else lines = textToDisplay.length()/maxChars;
lineStrings = new String[lines];
for(int i = 0; i < lines; i++){
if(i == (lines - 1)) lineStrings[i] = textToDisplay.substring(i*maxChars, i*maxChars + (textToDisplay.length() % maxChars)) + "\r\n";
else lineStrings[i] = textToDisplay.substring(i*maxChars, i*maxChars + maxChars) + "\r\n";
}
textToDisplay = "";
for(int i=0; i < lines; i++){
textToDisplay += lineStrings[i];
}
}
}
and in your Main function, maybe:
public class WashingtonFarewellDriver {
public static void main(String[] args) {
TextWriter wf1;
wf1 = new TextWriter();
wf1.setTextToDisplay("Friends and Citizens: The period for a new election of a citizen to administer the executive government of the United States being not far distant, and the time actually arrived when your thoughts must be employed in designating the person who is to be clothed with that important trust, it appears to me proper, especially as it may conduce to a more distinct expression of the public voice, that I should now apprise you of the resolution I have formed, to decline being considered among the number of those out of whom a choice is to be made.");
wf1.addLines(50);
wf1.display();
TextWriter wf2;
wf2 = new TextWriter("I beg you, at the same time, to do me the justice to be assured that this resolution has not been taken without a strict regard to all the considerations appertaining to the relation which binds a dutiful citizen to his country; and that in withdrawing the tender of service, which silence in my situation might imply, I am influenced by no diminution of zeal for your future interest, no deficiency of grateful respect for your past kindness, but am supported by a full conviction that the step is compatible with both.");
wf2.addLines(50);
wf2.display();
TextWriter wf3;
wf3 = new TextWriter("The acceptance of, and continuance hitherto in, the office to which your suffrages have twice called me have been a uniform sacrifice of inclination to the opinion of duty and to a deference for what appeared to be your desire. I constantly hoped that it would have been much earlier in my power, consistently with motives which I was not at liberty to disregard, to return to that retirement from which I had been reluctantly drawn.");
wf3.addLines(50);
wf3.display();
}
}
This should work, but some words will be cut off, because this just roughly separates lines by a maximum characters in a line.
thanks for all the feedback, it helped me, but ultimately there was another pretty easy way my that friend walked me through using the main.org.apache.commons.lang3.text.WordUtils package that he downloaded!
import java.io.IOException;
import org.apache.commons.lang3.text.WordUtils;
public class WashingtonFarewellDriver {
public static void main(String[] args) throws IOException {
int wwl = 110;
TextWriter wf1;
wf1 = new TextWriter(WordUtils.wrap("long sentences",wwl));
wf1.display();
}
}

Application layer protocol header fields in Java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 7 years ago.
Improve this question
I hope the question is suitable for here. I've designed an application layer protocol, say similar to HTTP. How can I define, and set the header fields in Java? Overall, I just want to write a simple client-server program that transfers "Hello World" string, but using my own protocol.
Assume header fields are similar to the following. So the "Hello World!" data comes after this header.
When you write to a socket, you're writing an stream of bytes. It's common, as in the table you included in your question, to start that stream with a standard series of bytes that gives the information needed to make sense of the remaining stream.
For example, of you simply want to send a string the minimum you'd need to add would be the string length like this:
|message length|data|
Which could be written like this:
String data = "Hello, world!";
ByteBuffer buffer = ByteBuffer.allocate(data.length + Integer.BYTES);
buffer.putInt(data.length);
buffer.put(data.getBytes("UTF-8"));
buffer.flip();
channel.write(buffer);
Adding in additional header information is no different, you just need to define a format for it in the stream.
You might for example use a format like this
|message length|header count|header size|header type|header data|data|
Which could be written like this:
Map<Integer, String> headers = ...
String data = "Hello, world - look at my headers!";
int headerBuffersLength = 0;
List<ByteBuffer> headerBuffers = new ArrayList<>();
for(Integer headerType : headers.keySet())
{
String headerData = headers.get(headerType);
ByteBuffer headerBuffer = ByteBuffer.allocation(headerData.size + Integer.BYTES + Integer.BYTES);
headerBuffer.putInt(headerData.length);
headerBuffer.putInt(headerType);
headerBuffer.put(headerData.getBytes("UTF-8"));
headerBuffer.flip();
headerBuffers.add(headerBuffer);
headerBuffersLength += headerBuffer.limit();
}
ByteBuffer buffer = ByteBuffer.allocate(data.length + headerBuffersLength + Integer.BYTES + Integer.BYTES);
buffer.putInt(data.length + headerBuffersLength);
buffer.putInt(headerBuffers.size());
for (ByteBuffer headerBuffer : headerBuffers)
{
buffer.put(headerBuffer);
}
buffer.put(data.getBytes("UTF-8"));
buffer.flip();
channel.write(buffer);
That's the basics, the code is very simple to write, but you might want to look at Google Protocol Buffers if you're doing anything more complicated.
There are many ways. It is quite common that this kind of specification comes with an xsd. If that is the case, you can use JAXB2 to parse it and create a set of Java Classes.
If that is not the case, may be you have the specification in such way you can do text processing and extract attributes and types to automate Java Class construction, using grep, sed, and so on.
If finally you have to build the Java Classes on your own, I will do something like following:
package my.package.ams;
public class ASMHeader {
private Integer version = null;
private Integer msgType = null;
private Integer priority = null;
...
public String getVersionString (){
return String.format("%02d", (version != null)?version:0);
}
public Integer getVersion(){
return version;
}
public void setVersion(Integer version){
if(version >= 0 and version < 100){
this.version = version;
}
}
public Integer getMsgType(){
return msgType;
}
public void setMsgType(Integer MsgType){
if(msgType >= 0 and msgType < 5){
this.msgType = msgType;
}
}
//And so on
....
}
Finally processing rules are not shown in yournpic, but you will have to understand and implements.
Take into account the possibility to thrown exception where version, msgType and other variables, doesn't meet the rules expressed in the document.
Hope it helps!

Best way to store temporary QuestionID-AnswerID data

I'm developing a quiz app and I want to find an efficient way to save user's answers.
Each quiz has 30 questions and all I need to save is:
questionNumber, questionId and answerId and either the answer is correct or not.
I thought an array will be a good solution. Example:
Each row represents a question (questionNumber). The first column represents the questionId and the second answerId. The third column will contain either 0 (incorrect) or 1 (correct).
The third column (correct) is needed to sum the number of correct answers (it's faster to sum the third column instead of checking each answer any time).
This isn't a SQL table - this info is temporary and will be destroyed as soon as the user finishes the quiz.
I want to know if you have any other solutions, maybe better.
Thank you!
Why not a class?
class Answer
{
private int questionID;
private int answerID;
private boolean correct;
public Answer(int questionID, int answerID, boolean correct)
{
this.questionID = questionID;
this.answerID = answerID;
this.correct = correct;
}
}
And an ArrayList
List<Answer> answers = new ArrayList<Answer>();
Then use
Answer answer = new Answer(1, 2, true);
answers.add(answer);
With an Array you will need to fix the array size every time you add a question with an ArrayList you can add as much questions as you want without care about the array size.
Anyway, if you questions will be always 30 you can create an Array too without problems.
About performances, well i don't see problems about speed/memory.

Categories

Resources