Премини към съдържанието
Форумът в приложение

По-лесно сърфиране. Научи повече.

Kaldata.com - Форуми

Приложение на форума на цял екран с push известия, значки и други.

За да инсталирате това приложение на iOS и iPadOS
  1. Докоснете Иконата за споделяне в Safari
  2. Превъртете менюто и докоснете Добавяне към началния екран.
  3. Докоснете Добавяне в горния десен ъгъл.
За да инсталирате това приложение на Android
  1. Докоснете менюто с 3 точки (⋮) в горния десен ъгъл на браузъра.
  2. Докоснете Добавяне към началния екран или Инсталиране на приложение.
  3. Потвърдете, като докоснете Инсталиране.

Добре дошли!

Добре дошли в нашите форуми, пълни с полезна информация. Имате проблем с компютъра или телефона си? Публикувайте нова тема и ще намерите решение на всичките си проблеми. Общувайте свободно и открийте безброй нови приятели.

Моля, регистрирайте се за да публикувате тема и да получите пълен достъп до всички функции.

 

Въпрос по Java

Featured Replies

Здравейте, от скоро започнах да изучавам Java и не съм много наясно с нещата. Ако може някой да ми помогне с тази задача ще съм му много благодарен.

 

17425938_1373806159346026_1363049192335378983_n.jpg

преди 2 часа, mitko9670 написа:

Здравейте, от скоро започнах да изучавам Java и не съм много наясно с нещата. Ако може някой да ми помогне с тази задача ще съм му много благодарен.

Здравейте !

Моля, използвайте следната картинка за структуриране на проекта си (използван е Eclipse):

projectStructure.png.c4fbadbd4fb9ec38f2311d1f15915d43.png

Задача 1 (FileReader.java):

Spoiler

package edu.project.firm;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class FileReader {

	private File file;
	private String content = "";

	public FileReader(String fileName) {
		this(new File(fileName));
	}

	public FileReader(File file) {
		if (file.isFile()) {
			this.file = file;
			try {
				Scanner sc = new Scanner(this.file);
				StringBuilder sb = new StringBuilder();
				while (sc.hasNextLine()) {
					sb.append(sc.nextLine() + '\n');
				}
				sc.close();
				this.content = sb.toString();
			} catch (FileNotFoundException e) {
				System.err.println(e.getMessage());
			}
		} else {
			throw new RuntimeException("File " + file.getName() + " is not proper file");
		}
	}

	public void readFile() {
		System.out.println(this.content);
	}
	
	public String getContent() {
		return this.content;
	}

	public void writeFile() {
		try {
			FileWriter fw = new FileWriter(file);
			fw.write(this.content);
			fw.close();
		} catch (IOException e) {
			System.err.println(e.getMessage());
		}
	}

	public void editContent(String newContent) {
		this.content = newContent;
	}

	public static void main(String[] args) {
		String testFileName = "test/file.txt";
		FileReader fr = new FileReader(testFileName);
		fr.readFile();
		fr.editContent(fr.getContent() + Math.random());
		fr.writeFile();
		// Check if write is OK
		FileReader frCheck = new FileReader(testFileName);
		frCheck.readFile();
	}

}

 

Помощен файл за задача 1 (file.txt):

Spoiler

NewContent
0.47405448876492506
0.663004609237197

 

Задача 2 (Employee.java):

Spoiler

package edu.project.firm;

public class Employee implements Comparable<Employee>{
	
	public enum GENDER {
		MALE, FEMALE;
		
		static GENDER get(String gender) {
			for (GENDER e: values()) {
				if (e.name().equals(gender)) {
					return e;
				}
			}
			return MALE;
		}
	}
	
	public enum EDUCATION {
		PrePrimary, Elementary, 
		Secondary, Bachelor,
		Master, Doctoral;
		
		static EDUCATION get(String education) {
			for (EDUCATION e: values()) {
				if (e.name().equals(education)) {
					return e;
				}
			}
			return PrePrimary;
		}
	}
	
	private String name;
	private GENDER gender;
	private EDUCATION education;
	
	public Employee(String name, GENDER gender, EDUCATION education) {
		this.name = name;
		this.gender = gender;
		this.education = education;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public GENDER getGender() {
		return gender;
	}

	public void setGender(GENDER gender) {
		this.gender = gender;
	}

	public EDUCATION getEducation() {
		return education;
	}

	public void setEducation(EDUCATION education) {
		this.education = education;
	}
	
	@Override
	public String toString() {
		return new StringBuilder()
				.append("|Name: ").append(name)
				.append(", Gender: ").append(gender)
				.append(", Education: ").append(education)
				.append("|").toString();
	}

	@Override
	public int compareTo(Employee o) {
		return this.getEducation().compareTo(o.getEducation());
	}
	
	public static void main(String[] args) {
		Employee emp1 = new Employee("Ivan", GENDER.MALE, EDUCATION.Elementary);
		Employee emp2 = new Employee("Maria", GENDER.FEMALE, EDUCATION.Secondary);
		System.out.println(emp1);
		System.out.println(emp2);
		if (emp1.compareTo(emp2) < 0) {
			System.out.println(emp2.getName() + " has higher education than " + emp1.getName());;
		} else if (emp1.compareTo(emp2) > 0) {
			System.out.println(emp1.getName() + " has higher education than " + emp2.getName());;
		} else {
			System.out.println(emp1.getName() + " and " + emp2.getName() + " have same education");;
		}
	}

}

 

Задача 3 (Firm.java):

Spoiler

package edu.project.firm;

import java.util.Arrays;
import java.util.Random;

import edu.project.firm.Employee.EDUCATION;
import edu.project.firm.Employee.GENDER;

public class Firm {
	
	private Employee[] employees;
	
	public Firm(Employee[] employees) {
		this.employees = employees;
	}

	public Employee[] getEmployees() {
		return employees;
	}

	public void setEmployees(Employee[] employees) {
		this.employees = employees;
	}
	
	public Employee[] getMasters(GENDER genderFilter) {
		Employee[] result = new Employee[this.employees.length];
		int currentIndex = 0;
		for (Employee emp : this.employees) {
			if (emp.getEducation() == EDUCATION.Master && emp.getGender() == genderFilter) {
				result[currentIndex] = emp;
				currentIndex++;
			}
		}
		return Arrays.copyOfRange(result, 0, currentIndex);
	}
	
	public void sortEmployees() {
		Arrays.sort(this.employees);
	}
	
	@Override
	public String toString() {
		return Arrays.toString(this.employees);
	}
	
	public static void main(String[] args) {
		Employee[] employees = new Employee[10];
		Random r = new Random();
		for (int i = 0; i < employees.length; i++) {
			employees[i] = new Employee("Employee"+i, randomGender(r), randomEducation(r));
		}
		printEmployees(employees);
		
		Firm firm = new Firm(employees);
		
		System.out.println("Male Masters: ");
		printEmployees(firm.getMasters(GENDER.MALE));
		
		firm.sortEmployees();
		System.out.println("Print sorted employees: ");
		printEmployees(firm.getEmployees());
	}
	
	private static void printEmployees(Employee[] employees) {
		for (Employee e : employees) {
			System.out.println(e);
		}
	}
	
	private static EDUCATION randomEducation(Random random) {
		return Arrays.asList(EDUCATION.values()).get(random.nextInt(EDUCATION.values().length));
	}
	
	private static GENDER randomGender(Random random) {
		return Arrays.asList(GENDER.values()).get(random.nextInt(GENDER.values().length));
	}

}

 

Задача 4 (FirmFromFile.java):

Spoiler

package edu.project.firm;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import edu.project.firm.Employee.GENDER;
import edu.project.firm.Employee.EDUCATION;

public class FirmFromFile {
	
	public static void main(String[] args) {
		//If you come with better solution than 
		//the horrific LineNumberReader, use arrays. 
		//Otherwise, work around with List.
		List<Employee> employees = new LinkedList<Employee>();
		try {
			File f = new File("test/firm.txt");
			Scanner sc = new Scanner(f);
			String line;
			while (sc.hasNextLine()) {
				line = sc.nextLine();
				String[] infos = line.split(",");
				for (int i = 0; i < infos.length; i++) {
					infos[i] = infos[i].replace("|", "")
							.replace("Name: ", "")
							.replace("Gender: ", "")
							.replace("Education: ", "")
							.trim();
				}
				employees.add(new Employee(infos[0], GENDER.get(infos[1]), EDUCATION.get(infos[2])));
			}
			sc.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} 
		
		Firm firm = new Firm(employees.toArray(new Employee[employees.size()]));
		
		System.out.println("Male Masters: ");
		printEmployees(firm.getMasters(GENDER.MALE));
		
		firm.sortEmployees();
		System.out.println("Print sorted employees: ");
		printEmployees(firm.getEmployees());
		
	}
	
	private static void printEmployees(Employee[] employees) {
		for (Employee e : employees) {
			System.out.println(e);
		}
	}
}

 

Помощен файл за задача 4 (firm.txt):

Spoiler

|Name: Ivan, Gender: MALE, Education: Master|
|Name: Maria, Gender: FEMALE, Education: Doctoral|
|Name: Elena, Gender: FEMALE, Education: Bachelor|
|Name: Milena, Gender: FEMALE, Education: Elementary|
|Name: Veselina, Gender: FEMALE, Education: Master|
|Name: Georgi, Gender: MALE, Education: Elementary|
|Name: Yordan, Gender: MALE, Education: Master|
|Name: Radostina, Gender: FEMALE, Education: Master|
|Name: Stefan, Gender: MALE, Education: Bachelor|
|Name: Petar, Gender: MALE, Education: PrePrimary|

 

 

  • 8 месеца по-късно...

Здравейте, ще ви помоля за малко съдействие.. Благодаря предварително.

 

Иван тренира футбол. Иван е зает човек. Той тренира футбол само през уикенда. Понякога се прибира в Шумен. Когато е в Шумен той тренира футбол. Ако Иван не е в Шумен през уикенда се среща с други приятели и се напиват.

Имате променливите: int day, която може да е 1,2,3,4,5,6,7 - 1 е понеделник, 7 е неделя boolean inShumen, която ако е true значи Иван е в Шумен Напишете метод, която извежда дали Иван ще играе футбол.

Имаме число n. Върнете абсолютната стойност на разликата на n и 21. Освен ако х (резултатът от разликата им) е по-голямо от 21, тогава върнете абсолютната им разлика по две.

 

Примери:

(19) → 2

(10) → 11 (

21) → 0

Архивирана тема

Темата е твърде стара и е архивирана. Не можете да добавяте нови отговори в нея, но винаги можете да публикувате нова тема, в която да продължи дискусията. Регистрирайте се или влезте във вашия профил за да публикувате нова тема.

Разглеждащи това в момента 0

  • Няма регистрирани потребители разглеждащи тази страница.

Дарение

  • Подкрепи съществуването на форума - направи дарение
    25%
    Дарени 252.69 EUR от нужните 1,000.00 EUR

Бюлетин

Получавайте известие, когато има важна промяна или новина свързана с форума.

Профил

Навигация

Търсене

Търсене

Конфигуриране на push известия в браузъра

Chrome (Android)
  1. Докоснете иконата на катинар до адресната лента.
  2. Докоснете Разрешения → Известия.
  3. Променете предпочитанията си.
Chrome (Desktop)
  1. Кликнете върху иконата на катинар в адресната лента.
  2. Изберете Настройки на сайта.
  3. Намерете Известия и коригирайте предпочитанията си.