I am going to help you with a part of your problem, which is not another one of separate what you receive per console in String
and in an integer 'int'
, and thus be able to work with those variables. I also help you when ordering alphabetically 'with an update that I've done' .
For this we are going to work with the split()
method which divides a string of the matches of a regular expression passed as a parameter 'a blank space in this case'.
1) First I create an array of type Object[]
to be able to store what comes to us through the console ..
2) Now we separate in 2 variables and store on the one hand the fruit of type String
, and on the other hand the number of pieces in an integer int
.
String fruta = (String) renglon[0];
int numero = Integer.parseInt((String)renglon[1]);
3) And now we print by console what each of these variables returns to us ..
System.out.println("Fruta: "+ fruta + " y he vendido "+numero+" piezas");
Result:
The complete example:
public static void main(String[] args) {
File f = new File("C:\Development\ficheros\ventas.txt");
try {
Scanner sc = new Scanner(f);
Object[] renglon;
while (sc.hasNext()) {
renglon = sc.nextLine().split(" ");
String fruta = (String) renglon[0];
int numero = Integer.parseInt((String) renglon[1]);
System.out.println("Fruta: " + fruta + " y he vendido " + numero + " piezas");
}
} catch (IOException e) {
System.out.println("Fichero no encontrado.");
}
}
Edit or Update ..
To make an order and compare values and others, I would create a POJO class apart ..
class MiFruta {
String fruta;
int pieza;
public MiFruta(String fruta, int pieza){
this.fruta = fruta;
this.pieza = pieza;
}
public String getFruta() {
return fruta;
}
public void setFruta(String fruta) {
this.fruta = fruta;
}
public int getPieza() {
return pieza;
}
public void setPieza(int pieza) {
this.pieza = pieza;
}
}
In the class where we extract from the file it would create a list to keep the fruits with the respective pieces.
List<MiFruta> lasFrutas = new ArrayList<>();
Inside the while we initialize each of the objects of the MyFruit class
MiFruta frutasVarias = new MiFruta(fruta, numero);
And we add them to our list
lasFrutas.add(frutasVarias);
And out of the while we could make the comparisons and print them in alphabetical order for example ..
System.out.println("----------Despues de ordenar nuestras frutas---------");
Collections.sort(lasFrutas, Comparator.comparing(MiFruta::getFruta));
for (MiFruta mf : lasFrutas){
System.out.print("MiFruta "+ mf.getFruta());
System.out.println("..Piezas "+ mf.getPieza());
}
And it would throw us as a result ..