Итак, сначала давайте сосредоточимся на вашем классе страны. Корневая проблема заключается в том, что вы хотите создать объекты Страны, каждая из которых представляет одну страну. Для этого, вы хотели бы конструктор в классе Страна, которая принимает строку в качестве параметра, так что в вашей основной программе вы можете сделать:
Country ger = new Country("Germany");
Country usa = new Country("USA");
Но чтобы сделать это, в первую очередь необходимо обеспечить класс Страна имеет переменная экземпляра, которая может хранить страну для каждого объекта. Таким образом, класс Country должен иметь по крайней мере следующее:
public class Country {
//Each object holds a variable called country, which is the name of the country
private String country;
//This constructor takes the name you enter in brackets and sets country to this name
public Country(String name) {
country = name;
}
}
Теперь мы готовы сделать объекты страны, представляющие разные страны. Поскольку вы хотите ввести страны из текстового файла (.txt), вам нужно будет сделать некоторые инструменты для работы с данным файлом. Я буду предполагать, что для простоты текстовый файл имеет только названия стран, разделенных новой строкой. Вы можете расширить свой класс Страну, чтобы включать в себя основные методы, а также некоторый соответствующий импорт:
import java.io.*;
import java.util.Scanner;
public class Country {
//Each object holds a variable called country, which is the name of the country
private String country;
//This constructor takes the name you enter in brackets and sets country to this name
public Country(String name) {
country = name;
}
public static void main(String[] args) {
//This represents the file you want to access
File countryFile = new File("path-of-text-file-goes-here");
Scanner input = null; //this tool will allow you to read from the file
try {
//we must initialize the file read tool in a try block
input = new Scanner(new FileInputStream(countryFile));
}
catch (FileNotFoundException e) {
System.out.println("Error accessing the file. Exiting...");
System.exit(0);
}
//initialize an empty String and we will put all the countries in the file
//into our program by first putting it in a String separated by spaces
String inputText = "";
while (input.hasNext()) //tests to see whether input has a word left
inputText += input.next() + " "; //if so, add it to the String and add a space
//Here we are creating an array of Strings, where each indice is one word from inputText
// the split(" ") method returns an array of characters separated by spaces
String[] inputTextArray = inputText.split(" ");
//initialize a Country array to the length of words in inputText
Country[] countryObject = new Country[inputTextArray.length];
//for each word in inputTextArray, initialize each indice in countryObject
//with a new Country("each-indice-of-inputTextArray-will-be-placed-here-one-by-one")
for (int i = 0; i < countryObject.length; i++)
countryObject[i] = new Country(inputTextArray[i]);
}
}
countryObject массив должен теперь быть заполнены объектами страны, где каждые из них является страна, введенной в текстовом файле. Надеюсь, что это поможет, дайте мне знать, если что-то неясно вам или если я неправильно понял вопрос. Благодаря!
Похоже, вы, вероятно, хотите «Карта' - вам действительно нужны они как отдельные переменные *? (Обратите внимание, что это переменная, которая имеет имя, а не экземпляр.) –
Почему бы не использовать карту? –