Użytkownik podaje plik ( jeden wiersz :Imie_Nazwisko_ocena(int)), napisz program który oblicza ile osób otrzymało ocene 2.
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.io.IOException; import java.io.RandomAccessFile;
public class kopa {
public static void main(String[] args) throws IOException { boolean trwanie= true; do{ kopa qq = new kopa(); Scanner s = new Scanner(System.in); System.out.println("MENU:"); System.out.println("1.Zapis osób:"); System.out.println("2.Liczenie dop.."); System.out.println("3.Koniec"); int c = s.nextInt(); switch(c){ case 1: System.out.println("Podaj nazwe Pliku"); s = new Scanner(System.in); String np = s.nextLine(); qq.zapis(np);break;
case 2: System.out.println("Podaj nazwe Pliku"); s = new Scanner(System.in); String nk = s.nextLine(); System.out.println("Liczba dop to: "+qq.czytanie(nk)); break;
case 3:trwanie = false;break;
default:System.out.println("Zły wybór...");break; } }while(trwanie); }
void zapis(String nazwaplk) throws FileNotFoundException, IOException{ File f = new File(nazwaplk); if(f.exists())f.delete(); f.createNewFile(); RandomAccessFile r = new RandomAccessFile( nazwaplk,"rw"); Scanner s = new Scanner(System.in); String wiersz ; System.out.println("Podaj ile osób chcesz wprowadzić..."); int iloosb = s.nextInt(); for(int i =0 ; i<iloosb;i++){ wiersz = null; System.out.println("Podaj imię osoby "); s = new Scanner(System.in); String imie = s.nextLine(); System.out.println("Podaj nazwisko osoby"); s = new Scanner(System.in); String nazwisko = s.nextLine(); System.out.println("Podaj ocene osoby"); s = new Scanner(System.in); Integer ocena = s.nextInt(); wiersz = imie; String concat = wiersz.concat("_").concat(nazwisko).concat("_").concat(ocena.toString()); r.writeUTF(concat); }} int czytanie(String nazwaplk) throws IOException ,FileNotFoundException { RandomAccessFile r = null; r = new RandomAccessFile( nazwaplk,"rw"); int liczbadop = 0; long poz = 0; long dł =r.length(); r.seek(0); while(poz<dł){ String wiersz = r.readUTF(); int mom = wiersz.lastIndexOf('_'); String teks = wiersz.substring(mom+1, wiersz.length()); int licztym = Integer.parseInt(teks); if(licztym == 2 ) liczbadop++; poz = r.getFilePointer(); } return liczbadop; } }
|