Input Object into an array as a List in Java - java

I am a beginner in Java. I want to get input from the user to a 2D array, and convert into a list of objects.
When I hardcoded the data, it could be done as this way
class Job // Job Class
{
public int taskID, deadline, profit;
public Job(int taskID, int deadline, int profit) {
this.taskID = taskID;
this.deadline = deadline;
this.profit = profit;
}
}
public class JobSequencing{
public static void main(String[] args) {
// List of given jobs. Each job has an identifier, a deadline and profit associated with it
List<Job> jobs = Arrays.asList(
new Job(1, 9, 15), new Job(2, 2, 2),
new Job(3, 5, 18), new Job(4, 7, 1),
new Job(5, 4, 25), new Job(6, 2, 20),
new Job(7, 5, 8), new Job(8, 7, 10),
new Job(9, 4, 12), new Job(10, 3, 5)
);
}
but, I want to get this object arrays from the user input. When I am going to do this way, it was giving me an error.
Code :
Scanner scan = new Scanner(System.in);
int count = scan.nextInt();
int[][] arr = new int[count][3];
for(int i =0; i<count;i++){
String[] arrNums = scan.nextLine().split(" ");
arr[i][0] = Integer.parseInt(arrNums[0]);
arr[i][1] = Integer.parseInt(arrNums[1]);
arr[i][2] = Integer.parseInt(arrNums[2]);
}
List<Job> jobs = Arrays.asList(
for(int i=0 ; i< count ; i++){
new Job(arr[i][0], arr[i][1], arr[i][2]);
}
);
Error :
Syntax error, insert ")" to complete MethodInvocationJava(1610612976)
Syntax error, insert ";" to complete LocalVariableDeclarationStatementJava(1610612976)
Can you give me a solution for adding objects as a list from the 2D array that user inputs?

First, create List then in for-loop add to the List
List<Job> jobs = new ArrayList<>();
for (int i = 0; i < count; i++) {
jobs.add(new Job(arr[i][0], arr[i][1], arr[i][2]));
}

Instead of
List<Job> jobs = Arrays.asList(
for(int i=0 ; i< count ; i++){
new Job(arr[i][0], arr[i][1], arr[i][2]);
}
);
try using lambda
List<Job> jobs = Arrays.stream(arr)
.map(arrElement -> new Job(arrElement[0],arrElement[1],arrElement[2]))
.collect(Collectors.toList());

You can try this way also using bufferedReader,
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader bufferedReader = new BufferedReader(isr);
List<Job> jobs = new ArrayList<>();
String x = bufferedReader.readLine();
String[] y;
int count = Integer.parseInt(x);
for (int i = 0; i < count; i++) {
y = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");
jobs.add(new Job(
Integer.parseInt(y[0]),
Integer.parseInt(y[1]),
Integer.parseInt(y[2])));
}

Related

how to read data from text file and pass them to junit test as parameterized test in java?

So Im doing JUnit Tests. While Im getting the parameters for my test method in a text document I counter an issue that is after the parameter object is not working well. All my parameter pass to the test method at once but I want them to pass separately.
Image below is what I want(Red line means the second set of parameters). The image is a sample run of my test method.
https://ibb.co/nFLhOc
This is my code:
String fileName = "ChargeData.txt";
try
{
scan = new Scanner(new File(fileName));
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
ArrayList<Object[]> Params = new ArrayList<Object[]>();
List listOfLists = new ArrayList();
ArrayList <Integer> quantityList;
ArrayList <Boolean> highQualityList;
ArrayList <Boolean> designEffectList;
ArrayList <Double> expectedResultList;
while(scan.hasNext())
{
quantityList = new ArrayList<Integer>();
highQualityList = new ArrayList<Boolean>();
designEffectList = new ArrayList<Boolean>();
expectedResultList = new ArrayList<Double>();
while(scan.hasNextInt())
{
quantityList.add(new Integer(scan.next()));
}
for(int i=0;i<quantityList.size();i++)
{
highQualityList.add(new Boolean(scan.next()));
}
for(int i=0;i<quantityList.size();i++)
{
designEffectList.add(new Boolean(scan.next()));
}
expectedResultList.add(new Double(scan.next()));
int[] quantity = new int[quantityList.size()];
boolean[] highQuality = new boolean[quantityList.size()];
boolean[] designEffect = new boolean[quantityList.size()];
double[] expectedResult = new double[1];
for (int i=0; i < quantity.length; i++)
{
quantity[i] = quantityList.get(i).intValue();
highQuality[i] = highQualityList.get(i).booleanValue();
designEffect[i] = designEffectList.get(i).booleanValue();
}
expectedResult[0] = expectedResultList.get(0).doubleValue();
listOfLists.add(quantity);
listOfLists.add(highQuality);
listOfLists.add(designEffect);
listOfLists.add(expectedResult);
}
Params.add(listOfLists.toArray());
scan.close();
return Params.toArray();
}
Code Logic problem, just move the Params.add(listOfLists.toArray()); inside while loop fixed it.
while(scan.hasNext())
{
quantityList = new ArrayList<Integer>();
highQualityList = new ArrayList<Boolean>();
designEffectList = new ArrayList<Boolean>();
expectedResultList = new ArrayList<Double>();
while(scan.hasNextInt())
{
quantityList.add(new Integer(scan.next()));
}
for(int i=0;i<quantityList.size();i++)
{
highQualityList.add(new Boolean(scan.next()));
}
for(int i=0;i<quantityList.size();i++)
{
designEffectList.add(new Boolean(scan.next()));
}
expectedResultList.add(new Double(scan.next()));
int[] quantity = new int[quantityList.size()];
boolean[] highQuality = new boolean[quantityList.size()];
boolean[] designEffect = new boolean[quantityList.size()];
double[] expectedResult = new double[1];
for (int i=0; i < quantity.length; i++)
{
quantity[i] = quantityList.get(i).intValue();
highQuality[i] = highQualityList.get(i).booleanValue();
designEffect[i] = designEffectList.get(i).booleanValue();
}
expectedResult[0] = expectedResultList.get(0).doubleValue();
listOfLists.add(quantity);
listOfLists.add(highQuality);
listOfLists.add(designEffect);
listOfLists.add(expectedResult);
Params.add(listOfLists.toArray());
}

How do i find the mean and median through a csv using an array on a Jframe?

I'm just a tad bit confused, I need to find the median and mode through this code through an array and I want to input it into a textfield since i'm using Jframes.
This is the code i'm using for the actual CSV document, it already reads the files from the CSV, but the mean and median bit is a bit confusing...
public void theSearch() {
try {
BufferedReader br = new BufferedReader(new FileReader(new File("C:\\Users\\Joshua\\Desktop\\Data Set.csv")));
//BufferedReader br = new BufferedReader(new FileReader(new File("H:\\2nd Year\\Programming Group Project\\Data Set.csv")));
List<String[]> elements = new ArrayList<String[]>();
String line = null;
while((line = br.readLine())!=null) {
String[] splitted = line.split(",");
elements.add(splitted);
}
br.close();
setMinimumSize(new Dimension(640, 480));
String[] columnNames = new String[] {
"Reporting period", "Period of coverage", "Breakdown", "ONS code", "Level", "Level description", "Gender", "Indicator value", "CI lower", "CI upper", "Denominator", "Numerator"
};
Object[][] content = new Object[elements.size()][13];{
for(int i=1; i<elements.size(); i++) {
content[i][0] = elements.get(i)[0];
content[i][1] = elements.get(i)[1];
content[i][2] = elements.get(i)[2];
content[i][3] = elements.get(i)[3];
content[i][4] = elements.get(i)[4];
content[i][5] = elements.get(i)[5];
content[i][6] = elements.get(i)[6];
content[i][7] = elements.get(i)[7];
content[i][8] = elements.get(i)[8];
content[i][9] = elements.get(i)[9];
content[i][10] = elements.get(i)[10];
content[i][11] = elements.get(i)[11];
content[i][12] = elements.get(i)[12];
}
};
jTable.setModel(new DefaultTableModel(content,columnNames));
jScrollPane2.setMinimumSize(new Dimension(600, 23));
jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
add(jScrollPane2);
//TableModel model = new DefaultTableModel (content, columnNames);
//JTable jTable = new JTable(model);
//jTable.setPreferredScrollableViewportSize(new Dimension(1200, 400));
// TableRowSorter<TableModel> sorted = new TableRowSorter <TableModel>(model);
// jTable.setRowSorter(sorted);
// jTable.setEnabled(false);
// JScrollPane pane = new JScrollPane(jTable);
System.out.println(jTable.getModel().getValueAt(1, 1));
} catch (Exception ex) {
ex.printStackTrace();
}
}
To calculate statistics such as mean and median you need to have numbers rather than strings. So the first thing you need to do is to convert the strings you are reading from the file into the appropriate data type. By far the best way to do this in Java is to create a class to represent objects in each row and then turn your rows into a collection of those objects.
I'm not sure what your rows represent so I'll just call the class Row here:
class Row {
private final int reportingPeriod;
private final int level;
...
public Row(String[] values) {
this.reportingPeriod = Integer.valueOf(values[0]);
this.level = Integer.valueOf(values[1]);
...
}
public int getLevel() {
return level;
}
}
List<Row> rows = new ArrayList<>();
while((line = br.readLine())!=null) {
rows.add(new Row(line.split(","));
}
Or in Java 8:
List<Row> rows = br.lines().map(l -> new Row(l.split(","))).collect(toList());
To find the median and mean:
int[] levels = new int[rows.size()];
int sum = 0;
for (int i = 0; i < rows.size(); i++) {
levels[i] = rows.get(i).getLevel();
sum += levels[i];
}
Arrays.sort(levels);
int median = levels[rows.size() / 2];
double mean = (double)sum / rows.size();
In Java 8 this would be:
int median = rows.stream().mapToInt(Row::getLevel).sorted().skip(rows.size() / 2).findFirst().get();
double mean = rows.stream().mapToInt(Row::getLevel).average().getAsDouble();

How to print out a line in a textfile into 2 different lines on console Java

public static FAQ_Alisa_QnA[] oipReadQuestion(){
String questionA1,thisUser;
int indexQuestion;
String [] entryDetails;
FAQ_Alisa_QnA [] entries = new FAQ_Alisa_QnA[100];
//Read file = "activities.txt".
File file = new File ("ReadOIP.txt");
int count = 0;
try{
Scanner sc = new Scanner(file);
//do this while there is a next line in file.
while(sc.hasNextLine()){
String line = sc.nextLine();
entryDetails = line.split(";");
// index = entryDetails[0];
indexQuestion = Integer.parseInt(entryDetails[0]);
thisUser = entryDetails[1];
questionA1 = entryDetails[2];
//Object to store values of entry.
FAQ_Alisa_QnA a = new FAQ_Alisa_QnA();
// a.index = Integer.parseInt(index);
a.indexQuestion = indexQuestion;
a.thisUsername = thisUser;
a.questionA1 = questionA1;
entries [count] = a;
count++;
}
}catch(FileNotFoundException fnfe){
System.out.println(fnfe.getMessage());
}
FAQ_Alisa_QnA [] allQuestions = new FAQ_Alisa_QnA [count];
for(int i = 0; i < count; i++){
allQuestions[i] = entries[i];
}
return allQuestions;
}
public static FAQ_Alisa_QnA[] oipReadAnswers(){
String indexAnswer, answer11, thisUser;
String [] answerDetails;
FAQ_Alisa_QnA [] answers = new FAQ_Alisa_QnA[100];
//Read file = "activities.txt".
File thisFile = new File ("AnsReadOIP.txt");
int count1 = 0;
try{
Scanner sc1 = new Scanner(thisFile);
//do this while there is a next line in file.
while(sc1.hasNextLine()){
String line = sc1.nextLine();
answerDetails = line.split(";");
// index = entryDetails[0];
indexAnswer = answerDetails[0];
thisUser = answerDetails[1];
answer11 = answerDetails[2];
//Object to store values of entry.
FAQ_Alisa_QnA a = new FAQ_Alisa_QnA();
// a.index = Integer.parseInt(index);
a.indexAnswer = Integer.parseInt(indexAnswer);
a.thisUsername = thisUser;
a.answer11 = answer11;
answers [count1] = a;
count1++;
}
}catch(FileNotFoundException fnfe){
System.out.println(fnfe.getMessage());
}
FAQ_Alisa_QnA[] allAnswers = new FAQ_Alisa_QnA[count1];
for(int i = 0; i < count1; i++){
allAnswers[i] = answers[i];
}
return allAnswers;
}
public static void oipPrintQnA(){
FAQ_Alisa_QnA [] allQuestions = oipReadQuestion();
FAQ_Alisa_QnA [] allAnswers = oipReadAnswers();
System.out.println("Organization in project work");
System.out.println("=============================");
for(int i = 0; i < allQuestions.length; i++){
System.out.println( allQuestions[i].indexQuestion + "-" + "Question" + ":");
System.out.println(allQuestions[i].thisUsername + ":" +allQuestions[i].questionA1);
System.out.println(" ");
for(int j = 0; j < allAnswers.length; j++){
if(allQuestions[i].indexQuestion == allAnswers[j].indexAnswer){
System.out.println("Answer for question "+ + allAnswers[j].indexAnswer+ ":" );
System.out.println(allAnswers[j].thisUsername+ ":" +allAnswers[j].answer11);
System.out.println(" ");
}
}
}
}
//So I have read answers and questions and I saved my qns and answers in 2 different text files. This is because I have add functions to it but i never put it here cuz my qn is not related to that. I just wanna know how to print out the qn and answer in 2 lines so that if the qn is so long then it can print out in two lines//
So these are how my text files look like:
ReadOIP.txt
1;Shafiq;How to organize your time well when you're juggling with so many project work and assignments on the same day? Best answer:The best solution to this is to early planning or schedule your time wisely. Write in a calendar beforehand the work you are going to do for an assignment.
2;Rohannah;Does having a timetable works to finish your project on time?
3;lymeoww;Is task allocation really important to be organized in project work?
AnsReadOIP.txt
1;Andy23;The best solution to this is to early planning or schedule your time wisely. Write in a calendar beforehand the work you are going to do for an assignment .2; Does having a timetable to do your project works? //For example this line, it will print out very long on the console//
2;Betty23;of course it does!
1;Ying Qian;just organize lorh
3;lymeoww;Yes, it is important!
//Refer to this picture//

Reading from file/array. No values. No errors

Any ideas what I am missing here? I am reading from a file array. The values in the text file don't get stored and there is no output. All I get is "names and totals" but no values.
I don't know.
private int[] totals;
private String[] names;
private String[] list;
private int count;
public void readData() throws IOException {
BufferedReader input = new BufferedReader(new FileReader("cookies.txt"));
//create the arrays
totals = new int[count];
names = new String[count];
list = new String[count];
//read in each pair of values
String quantityString = input.readLine();
for (int i = 0; i < count; i++) {
names[i] = input.readLine();
list[i] = input.readLine();
quantityString = input.readLine();
totals[i] = Integer.parseInt(quantityString);
}
}
public void display() {
System.out.println("names totals")
for (int i = 0; i < count; i++)
System.out.println(list[i] + " \t " + names[i] + " \t" + totals[i]);
}
//called to compute and print the result
public void printResults() {
//find the best teacher
int maxIndex = 0;
int maxValue = 0;
//for each record stores
for (int i = 0; i < count; i++) {
//if we have a new MAX value so far, update variables
if (maxValue < totals[i]) {
maxValue = totals[i];
maxIndex = i;
}
}
}
You never give the variable count a value, so it initialized to 0 by Java. This means that your arrays are of size 0 also.
So since count is zero, you never read anything from the file, which is why nothing is stored in your arrays and also why nothing is printed out.
Example: Reading a File line-by-line
// create temporary variable to hold what is being read from the file
String line = "";
// when you don't know how many things you have to read in use a List
// which will dynamically grow in size for you
List<String> names = new ArrayList<String>();
List<Integer> values = new ArrayList<Integer>();
// create a Reader, to read from a file
BufferedReader input = new BufferedReader(new FileReader("cookies.txt"));
// read a full line, this means if you line is 'Smith 36'
// you read both of these values together
while((line = input.readLine()) != null)
{
// break 'Smith 36' into an array ['Smith', '36']
String[] nameAndValue = line.split("\\s+");
names.add(nameAndValue[0]); // names.add('Smith')
values.add(Integer.parseInt(nameAndValue[1]); // values.add(36);
}

How do I get both of my arrays to be read in?

I have two arrays the store the values of two lines that are read in from a file. After some processing in my GUI class it should show to rectangles side by side in the middle of the frame. However only one ever shows up. I have tried every way I know how to get the other one to show up but no dice. Here is my code:
public class PortraitFileReader
public static ArrayList<Drawable> readFile(File a) {
File myFile;
ArrayList<Integer> values = new ArrayList<Integer>();
ArrayList<Drawable> couple = new ArrayList<Drawable>();
Man aMan;
Woman aWoman;
Point aPoint;
String input;
String [] array = null;
String [] array2 = null;
try {
myFile = a;
Scanner inFile = new Scanner(myFile);
input = inFile.nextLine();
array = input.split(", ");
while(inFile.hasNext()) {
input = inFile.nextLine();
array2 = input.split(", ");
System.out.println(Arrays.toString(array2));
}
if(array[0].equals("man")) {
for(int i=1; i<array.length-1; i++) {
int current = Integer.parseInt(array[i]);
values.add(current);
System.out.println(values);
}
aPoint = new Point(values.get(0), values.get(1));
aMan = new Man(aPoint, values.get(2), values.get(3), array[5]);
couple.add(aMan);
values.clear();
}
if(array[0].equals("woman")) {
for(int i=1; i<array.length-1; i++) {
int current = Integer.parseInt(array[i]);
values.add(current);
System.out.println(values);
}
aPoint = new Point(values.get(0), values.get(1));
aWoman = new Woman(aPoint, values.get(2), values.get(3), array[5]);
couple.add(aWoman);
values.clear();
}
if(array2[0].equals("man")) {
for(int i=1; i<array2.length-1; i++) {
int current = Integer.parseInt(array[i]);
values.add(current);
System.out.println(values);
}
aPoint = new Point(values.get(0), values.get(1));
aMan = new Man(aPoint, values.get(2), values.get(3), array2[5]);
couple.add(aMan);
values.clear();
}
if(array2[0].equals("woman")) {
for(int i=1; i<array2.length-1; i++) {
int current = Integer.parseInt(array[i]);
values.add(current);
System.out.println(values);
}
aPoint = new Point(values.get(0), values.get(1));
aWoman = new Woman(aPoint, values.get(2), values.get(3), array2[5]);
couple.add(aWoman);
values.clear();
}
}
catch (FileNotFoundException e) {
System.out.println("The file was not found.");
}
return couple;
}
}
This is the data that I'm reading in from the file:
man, 260, 100, 40, 80, Tom
woman, 300, 100, 40, 80, Sally
Any help would be greatly appreciated.
NOTE: the system.out.println's are just there to test if each array had the right values in it.
When you are going through array2 checking if it is a woman, you are actually going through the variable array.
for(int i=1; i<***array2***.length-1; i++) {
int current = Integer.parseInt(****array***[i]);
The same goes for when you are checking if array2 is a man
The effect of this is that you are processing the contents of the first line twice.
Um, I can barely read it, so I rewrote it:
public class PortraitFileReader {
public static ArrayList<Drawable> readFile(File file) {
ArrayList<Drawable> couple = new ArrayList<Drawable>();
try {
Scanner scanner = new Scanner(file);
while(scanner.hasNext()) {
couple.add(parseLine(scanner.nextLine()));
}
}
catch (FileNotFoundException e) {
System.out.println("The file was not found.");
}
return couple;
}
public static Drawable parseLine(String line) {
String [] array = line.split(", ");
String gender = array[0];
int pointX = Integer.parseInt(array[1]);
int pointY = Integer.parseInt(array[2]);
int width = Integer.parseInt(array[3]);
int height = Integer.parseInt(array[4]);
String name = array[5];
if(gender.equals("man")) {
return new Man(new Point(pointX, pointY), width, height, name);
} else {
return new Woman(new Point(pointX, pointY), width, height, name);
}
}
}
Anyway, it looks like either you're not drawing your drawable right, or the input in the file isn't exactly formatted as you expect. The parsing itself seems to make sense....
except that you're always parsing array, and not switching it to parseInt(array2[i]) in the 3rd and 4th block. Which just demonstrates why collapsing these cut and pasted blocks into one method is the sensible way to go.
Inlining everything would look like the above with these edits:
....
Scanner scanner = new Scanner(file);
while(scanner.hasNext()) {
String line = scanner.nextLine();
Drawable person = null;
// everything from parseLine, change return to assignment to person
couple.add(person);
}
....

Categories