Jump to content

Need help with java

crask
hey guys, i was assigned with a java program that consists in a menu counter for a restaurant.

in that counter, i have so separate the different dishes, an create an average and then display it.

the program as to read a .txt file and import the data, in that file the layout its something like this <beef> : <nº of orders>. the only problem is that could be repeated dishes so how do i identify each one of a time, and join the repeated ones in the program?

i know that i can import all the data into an array but how can i import it separately or separate the data after?

 

thanks 

Link to comment
Share on other sites

Link to post
Share on other sites

Had a hard time understanding what you need to do, but could you do the following?

 

  1. Read the text file one line at a time
  2. With each line, split the text on the colon, giving you the dish name and the number of orders
  3. Use a dictionary to store the data.
  4. If the dish isn't in the dictionary, add it along with it's value (the number of orders, converted to int if needed). If the dish has previously been added to the dictionary, just update it's value by adding the number of dishes to it's current value.

Does that help?

Link to comment
Share on other sites

Link to post
Share on other sites

Had a hard time understanding what you need to do, but could you do the following?

 

  1. Read the text file one line at a time
  2. With each line, split the text on the colon, giving you the dish name and the number of orders
  3. Use a dictionary to store the data.
  4. If the dish isn't in the dictionary, add it along with it's value (the number of orders, converted to int if needed). If the dish has previously been added to the dictionary, just update it's value by adding the number of dishes to it's current value.

Does that help?

Thanks, i'm doing this project with crask.

 

Are you talking about HashMap's?

Link to comment
Share on other sites

Link to post
Share on other sites

Thanks, i'm doing this project with crask.

 

Are you talking about HashMap's?

 

Yes, HashMap's are what it's called in Java. Sorry, haven't programmed Java in a while lol.

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

so...

//--------------------------------------------------------------------------String fileName = "pedidos.txt";    Scanner pedidos = new Scanner (fileName);//--------------------------------------------------------------------------HashMap <String, Integer> lista = new HashMap<String, Integer>();   int a = 0;   int i = 0;   while (pedidos.hasNextLine()){      String linha = pedidos.nextLine();      String [] splits = linha.split (" : ");     // if (linha==ArrayList){     // x == nextLineInt;     //     else add.Unknownproducts      i++;    }
we need to separate the string from the integer that are in the "pedidos.txt" file and put them in the HashMap.

linha (portuguese) == line (english)

we know what to do.. but we dont know the code for it. can someone help us?

Link to comment
Share on other sites

Link to post
Share on other sites

Projectos a esta hora?! (Assumindo que estão em Portugal)

 

First of all, at least with Java 7 in linux, I can't read the contents of the file with the Scanner, so I recommend (and always use) BufferedReader.

BufferedReader pedidos = new BufferedReader(new FileReader(fileName))

 

If you are having trouble with the names or arguments of any method in any java class you can always check out Oracle's online documentation.

http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html is what you need in this case, specifically containsKey(key), get(key), and put(key, value).

 

Since you have already split the line into array splits you will need something like
if(lista.containsKey(splits[0]))

    lista.put(splits[0], lista.get(splits[0]) + splits[1]);

else

    lista.put(splits[0], splits[1]); 

Link to comment
Share on other sites

Link to post
Share on other sites

[sim, Portugal. Tem mesmo de ser noite e dia dentro. Amanha (hoje) a noite.]

Our while isnt going further than 1, and my .txt file has more than 2 lines... me and my collegue are kinda paniking lol

Link to comment
Share on other sites

Link to post
Share on other sites

[sim, Portugal. Tem mesmo de ser noite e dia dentro. Amanha (hoje) a noite.]

Our while isnt going further than 1, and my .txt file has more than 2 lines... me and my collegue are kinda paniking lol

[bem sei. Também já tive de estar de pé 30+ horas na altura de entregas de projectos. Mas agora devia ser época de exames, não? Eu estou a (tentar) estudar para 2 para a semana.]

 

With the Scanner? When I was using the scanner the only thing I could print was the name of the file, which was weird since I was printing the content of the first read line. That's why I switched to the BufferedReader.

 

Here is what I have (again, I am using Java 7):

import java.io.*;import java.util.*;public class MenuCounter {  public static void main(String[] args) {    String filename = "pedidos.txt";    HashMap<String, Integer> lista = new HashMap<String, Integer>();        try(BufferedReader pedidos = new BufferedReader(new FileReader(filename))) {      String linha;      while((linha = pedidos.readLine()) != null) {        String[] splits = linha.split(" : ");        System.out.println(splits[0] + " " + splits[1]);      }    } catch(IOException ioe) {      ioe.printStackTrace();    }      }}
Link to comment
Share on other sites

Link to post
Share on other sites

É epoca de exames mas ainda estamos a acabar uns trabalhos antes, ve la o que achas disto, assim conseguimos ler o ficheiro

 

check this code

       String filename = "pedidos.txt";        File origem = new File (filename);        ArrayList <String> nomes;        nomes = new ArrayList <String> ();        Scanner leitor;        int contador = 0;        int c = 0;                           try{                             leitor = new Scanner (origem);                               while (leitor.hasNextLine()){                      String linha = leitor.nextLine();                      contador ++;                      System.out.println (linha);                      nomes.add (linha);                       }                 leitor.close();             }           catch (FileNotFoundException e) {                System.out.println ("Produto desconhecido");    }
Link to comment
Share on other sites

Link to post
Share on other sites

That's why I switched to the BufferedReader.

I know we must use Scanner, our teacher told us. And we saw scanner read multiple lines and split them into an HashMap of <String, Integer>.. We just cant get the code to work. (and we dont know the commands)

Link to comment
Share on other sites

Link to post
Share on other sites

I know we must use Scanner, our teacher told us. And we saw scanner read multiple lines and split them into an HashMap of <String, Integer>.. We just cant get the code to work. (and we dont know the commands)

 

Since the FileReader class accepts a string and automatically opens the file I was trying to pass the string filename to the scanner...  <_<  Anyways...

 

As far as I know there is no immediate way of getting a HashMap from a Scanner.

But I did manage to do this:

public static void main(String[] args) {    String filename = "pedidos.txt";    Scanner leitor = null;    HashMap<String, Integer> lista = new HashMap<String, Integer>();            try {      leitor = new Scanner (new File (filename)).useDelimiter(" : |\n");                    while (leitor.hasNext()){        String nome = leitor.next();        Integer contagem = leitor.nextInt();        System.out.println (nome + " -> " + contagem);        if(lista.containsKey(nome))          lista.put(nome, lista.get(nome) + contagem);        else          lista.put(nome, contagem);      }     } catch (FileNotFoundException e) {      System.out.println ("Ficheiro desconhecido");    } finally {      if(leitor != null) leitor.close();    }        System.out.println("---");    for(Map.Entry<String, Integer> m : lista.entrySet())      System.out.println(m.getKey() + " -> " + m.getValue());    System.out.println("---");  }
Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×