What I'm wondering is, is there a way to read the file so that the strings 'vertex' and 'connected' can be cast as a reference to the Vertex objects outside the loop? The Strings will share the same name as the file is read, with it progressing from a-t, so that isn't a problem. If this isn't possible, is there any other way to work around this? Maybe by somehow creating a vertex object within the loop yet not overwriting it? I tried it but it would overwrite itself for each loop, as it would create a new Vertex with the same value each time. Thanks in advance.
public static void main(String[] args) throws FileNotFoundException {
File file = new File("ass3.txt");
Scanner scan = new Scanner(f);
if (file.exists() == false) {
System.out.println("File doesn't exist or could not be found.");
System.exit(0);
}
int nVertices = scan.nextInt();
int nEdges = scan.nextInt();
for (int i = 0; i < 21; i++) {
String s = scan.nextLine();
}
Queue selectedSet = new Queue();
Queue candidateSet = new Queue();
Vertex a = new Vertex("a");
Vertex b = new Vertex("b");
Vertex c = new Vertex("c");
Vertex d = new Vertex("d");
Vertex e = new Vertex("e");
Vertex f = new Vertex("f");
Vertex g = new Vertex("g");
Vertex h = new Vertex("h");
Vertex i = new Vertex("i");
Vertex j = new Vertex("j");
Vertex k = new Vertex("k");
Vertex l = new Vertex("l");
Vertex m = new Vertex("m");
Vertex n = new Vertex("n");
Vertex o = new Vertex("o");
Vertex p = new Vertex("p");
Vertex q = new Vertex("q");
Vertex r = new Vertex("r");
Vertex s = new Vertex("s");
Vertex t = new Vertex("t");
for (int z = 0; z < 99; z++) {
String vertex = scan.next();
String connected = scan.next();
int weight = scan.nextInt();
vertex.addNeighbour(new Edge(weight,vertex,connected));
}
You should be using a Map. This maps objects->objects, so in this case we would want it to be Strings->Vertex.
Some sample code:
HashMap<String, Vertex> vertices = new HashMap<String, Vertex>();
vertices.put("a", new Vertex("a"));
...
You can then reference the map in or outside your loop
Vertex v = vertices.get(vertex);
Related
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])));
}
I need some help, I've got a matrix 4x4 that shows a mountain, in the Mountain.txt there are the heights of mountain zones:
1 1 1 1
1 2 3 1
1 2 2 1
1 1 1 1
And the file Rocks.txt that has a type or rock for each zone:
stone stone stone stone
stone sand sand stone
stone sand sand sand
sand sand sand sand
Public class Mountain {
int height;
String typeRock;
public Mountain (int height, String typeRock) {
this.height = height;
this.typeRock = typeRock;
};
}
How do I read that data from 2 different files and to make objects with it, like
Mountain zone00 = new Mountain(1, stone);
Mountain zone01 = new Mountain(1, stone);
Mountain zone11 = new Mountain(2, sand);
And so on...
Loading a file from a directory could be done like so:
public String loadFile(String path) {
StringBuilder builder = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(path));
String line;
while((line = br.readLine()) != null) {
builder.append(line + "\n");
}
br.close();
} catch(IOException e ) {
e.printStackTrace();
}
return builder.toString();
}
You could know use this method to load both files into strings:
String mountainData = loadFile("Mountain.txt");
String rockData = loadFile("Rpcks.txt");
You could now split these Strings:
String[] mountainsTokens = mountainData.split("\\s+");
String[] rockTokens = rockData.split("\\s+");
After that you just need to create your mountains. Therefore you go through each element of your matrix (the size seems to be 4 here):
Mountain[][] zones = new Mountain[4][4];
for(int y = 0; y < 4; y++) {
for(int x = 0; x < 4; x++) {
mountains[y][x] = new Mountain(Integer.parseInt(mountainData[x + y * 4]), rockData[x + y * 4]);
}
}
For that you have to convert something one-dimensional into something two dimensional (x+y*4) Furthermore, you have to convert the String into an int using Integer.parseInt(). You might have to surround with try-catch too.
Btw, I would definetivly save the mountains in a two dimensional arry like above. This makes everything much easier (instead of zone00 you write zones[0][0]).
I hoped that helped.
You simply open and read two files at a time.
Btw you have a bit of a problem in that the size of your input is hard coded. Instead of assuming that the data is a 4 x 4 array of input, you should add the rows and columns to the input file and read those first. This allows your program to handle any sized data.
This code has not been tested, caveat emptor.
public Mountain[][] read( String mountains, String rocks ) throws IOException {
Reader br1 = Files.newBufferedReader( new File( mountains ).toPath() );
Reader br2 = Files.newBufferedReader( new File( rocks ).toPath() );
Scanner scan1 = new Scanner( br1 );
Scanner scan2 = new Scanner( br2 );
final int rows = 4; // shouldn't hard code these
final int columns = 4;
Mountain[][] mountainArr = new Mountain[rows][columns];
for( int i = 0; i < rows; i++ ) {
for( int j = 0; j < columns; j++ ) {
int mountainHeight = scan1.nextInt();
String rock = scan2.next();
mountainArr[i][j] = new Mountain( mountainHeight, rock );
}
}
scan1.close();
scan2.close();
return mountainArr;
}
public static class Mountain {
public Mountain( int height, String rockType ) {
}
}
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());
}
My array has an unfixed size as it depends on the user input for the number of modules entered so I really don't know what to do when I run this code and got this error: ArrayIndexOutOfBoundsException: 0
Module[] array = new Module[moduleno];
String[] a = new String[moduleno];
String[] b = new String[moduleno];
int[] c = new int[moduleno];
String[] Output = new String[moduleno];
String endoutput="";
//Method for input of number of modules
moduleno = Student.modno();
for (int i = 0; i < moduleno; i++) {
modulename = Student.MakingModName(i);
grade = Student.readGrade(i);
cu = Student.readCredits(i);
value = Student.GradeValue(grade);
score = Student.calculateScore(value, cu);
totalScore += score;
totalCu += cu;
GPA = Student.calculateGPA(totalCu, totalScore);
//Error occurs here.
**array[i] = new Module(modulename,grade,cu);**
a[i] = array[i].getModulename();
b[i] = array[i].getGrade();
c[i] = array[i].getCu();
Output[i] = a[i] + " " +b[i]+" " +c[i]+" ";
endoutput = endoutput + Output[i] + "\n";
}
This sequence of statements:
Module[] array = new Module[moduleno];
moduleno = Student.modno();
does not magically resize the array that has been allocated previously. You need to do it the other way round:
moduleno = Student.modno();
Module[] array = new Module[moduleno];
Move the statement
moduleno = Student.modno(); // this should be the value while you initialize the array
before you initialize your arrays.
//Add This line before initialize your array
**moduleno = Student.modno();**
Module[] array = new Module[moduleno];
String[] a = new String[moduleno];
String[] b = new String[moduleno];
int[] c = new int[moduleno];
String[] Output = new String[moduleno];
String endoutput="";
Reason :
By default your moduleno variable contains 0(Zero) size so your all arrays size is also 0(Zero).
And you try to add 1 element in array but size of array is zero so it gives ArrayIndexOutBoundsException.
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);
}
....