I recently completed an assignment that asked us to sort names out of a text file alphabetically, I used three different classes to get it to work properly.
class Person {
String firstName;
String lastName;
}
I then created this to sort in to alphabetical order by last name and then by first name
class SortNames {
void sortNames(Person[] arr, int type) {
if (type == 1) {
int j;
boolean flag = true; // will determine when the sort is finished
Person temp;
while (flag) {
flag = false;
for (j = 0; j < arr.length - 1; j++) {
if (arr[j].lastName.compareToIgnoreCase(arr[j + 1].lastName) > 0) { // ascending
// sort
temp = arr[j];
arr[j] = arr[j + 1]; // swapping
arr[j + 1] = temp;
flag = true;
}
}
}
for (int k = 0; k < arr.length; k++)
System.out.println(arr[k].firstName +" "+arr[k].lastName);
} else if (type == 2) {
int j;
boolean flag = true; // will determine when the sort is finished
Person temp;
while (flag) {
flag = false;
for (j = 0; j < arr.length - 1; j++) {
if (arr[j].firstName.compareToIgnoreCase(arr[j + 1].firstName) > 0) { // ascending
// sort
temp = arr[j];
arr[j] = arr[j + 1]; // swapping
arr[j + 1] = temp;
flag = true;
}
}
}
for (int k = 0; k < arr.length; k++)
System.out.println(arr[k].firstName +" "+arr[k].lastName);
}
}
}
Then I used a simple program to print all of the names, first in the order that they were given, then in order by last name and then in order by first name.
import java.io.*;
import java.util.*;
public class SortNameApp {
public static void main(String[] args) throws IOException {
Scanner scanner=new Scanner(new File(args[0]));
try {
int namesCount = Integer.parseInt(scanner.nextLine());
Person[] arr = new Person[namesCount];
String line = null;
int i = 0;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
Person person = new Person();
person.firstName = line.split(" ")[0];
person.lastName = line.substring(person.firstName.length(),
line.length()).trim();
arr[i] = person;
System.out.println(arr[i].firstName +" "+arr[i].lastName);
i++;
}
System.out.println("---------SORT BY LAST NAME---------");
new SortNames().sortNames(arr, 1);// sort by last name
System.out.println("---------SORT BY FIRST NAME---------");
new SortNames().sortNames(arr, 2);// sort by first name
} catch (IndexOutOfBoundsException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I wanted to create a GUI that does all three things with different buttons printing in different relative JtextFields, however when i go to print it out, only one name is printed out on to the jtextfield, even though the the text file has about 30 names in it. this is what i am calling under the "load file" button
public void Read() {
try {
String file = filename.getText();
int filesize = file.length();
Scanner input = new Scanner(getClass().getResourceAsStream(file));
int namesCount = Integer.parseInt(input.nextLine());
Person[] arr = new Person[namesCount];
String line = null;
int i = 0;
while (input.hasNextLine()) {
line = input.nextLine();
Person person = new Person();
person.firstName = line.split(" ")[0];
person.lastName = line.substring(person.firstName.length(),
line.length()).trim();
arr[i] = person;
display.setText(arr[i].firstName +" "+arr[i].lastName);
i++;
For the sorting i tried to do this, but it still does not work properly:
display2.setText(new SortNames().sortNames(arr, 2));
here
What is the proper way to do something like this?
This is my GUI so far
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import java.util.*;
public class SortNamesGUI extends JFrame {
private final LayoutManager layout;
private final LayoutManager layout2;
private JButton loadButton;
private JTextField filename;
private JTextArea display;
private JTextArea display2;
private JTextArea display3;
public SortNamesGUI()
{
super("Sorting Names");
setLayout(new BorderLayout());
JPanel buttonPanel = new JPanel();
layout = new FlowLayout();
buttonPanel.setLayout(layout);
JButton LoadFile = new JButton("Load File");
JButton FirstName = new JButton("Sort First Name");
JButton LastName = new JButton("Sort Last Name");
filename = new JTextField("Data file", 15);
buttonPanel.add(filename);
buttonPanel.add(LoadFile);
buttonPanel.add(FirstName);
buttonPanel.add(LastName);
JPanel DisplayPanel = new JPanel();
layout2 = new GridLayout(1,3);
DisplayPanel.setLayout(layout2);
display = new JTextArea("Unsorted list");
display2 = new JTextArea("Sorted based on first name");
display3 = new JTextArea("Sorted based on last name");
DisplayPanel.add(display);
DisplayPanel.add(display2);
DisplayPanel.add(display3);
DisplayPanel.add(new JScrollPane(display));
DisplayPanel.add(new JScrollPane(display2));
DisplayPanel.add(new JScrollPane(display3));
add(buttonPanel,BorderLayout.NORTH);
add(DisplayPanel,BorderLayout.CENTER);
LoadFile.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
Read(); }
}
);
}
/*public void actionPerformed(ActionEvent event) {
Read();
}*/
public void Read() {
try {
String file = filename.getText();
int filesize = file.length();
Scanner input = new Scanner(getClass().getResourceAsStream(file));
int namesCount = Integer.parseInt(input.nextLine());
Person[] arr = new Person[namesCount];
String line = null;
int i = 0;
while (input.hasNextLine()) {
line = input.nextLine();
Person person = new Person();
person.firstName = line.split(" ")[0];
person.lastName = line.substring(person.firstName.length(),
line.length()).trim();
arr[i] = person;
display.setText(arr[i].firstName +" "+arr[i].lastName);
i++;
person.toString();
}
} catch (IndexOutOfBoundsException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void SoftFirstName() {
String file = filename.getText();
int filesize = file.length();
Scanner input = new Scanner(getClass().getResourceAsStream(file));
int namesCount = Integer.parseInt(input.nextLine());
Person[] arr = new Person[namesCount];
new SortNames().sortNames(arr, 2);// sort by first name
display2.setText(new SortNames().sortNames(arr, 2));
}
public static void main(String[] args) {
SortNamesGUI testing= new SortNamesGUI();
testing.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
testing.setSize(620, 180);
testing.setVisible(true);
}
}
display2.setText(new SortNames().sortNames(arr, 2));
If you have tried this, you most likely get a compiler error. This is because the sortNames() method returns void but the setText() method requires a String argument. You need to modify sortNames() to return the sorted array rather than printing it out directly. In your original code, main() should get the sorted array and then print it. This is an example of what we call the Single Responsibility Principle. Each method should be responsible for a single task. In this case, your sortNames() does two things: 1. Sort the array and 2. Print the sorted array. If you separate these two tasks into separate methods, it will make your job a lot easier when you convert it to a GUI.
Once you have separated these two tasks, you will then need to decide how you want the names to appear in the JTextAray. I can think of at least two solutions:
Convert the entire array to a String and display the result in the JTextArea. This should be very easy to implement, but the output will have a list of names separated by commas inside square brackets.
Add each name one at a time to the JTextArea. Note that setText() will completely replace the entire contents of the JTextArea with the given text. I suggest look at the documentation for JTextArea to find another method that will be useful for your purposes.
Related
My program Runs and prints the first few system.out statements, then stops printing them. There is no exception thrown, and the program continues to run until manually terminated.
I've tried System.out.flush(); but am not even sure where to put that
import java.io.*;
import java.util.ArrayList;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) throws
FileNotFoundException {
String inputFileStr = args[0];//"input.txt";
String outputFileStr = args[1];//"output.txt";
String deleteFileStr = args[2];//"CS401Project5Delete_Varner_Sav58.txt";//
String replaceFileStr = args[3]; //"CS401Project5Replace_VARNER_SAV58.txt";
// create files w/ corresponding file names
try{
File inputFile = new File(inputFileStr);
File outputFile = new File(outputFileStr);
File deleteFile = new File(deleteFileStr);
File replaceFile = new File(replaceFileStr);
// create arrayLists
ArrayList<StringBuilder> deleteArray;
ArrayList<StringBuilder> replaceArray;
ArrayList<StringBuilder> inputArray;
ArrayList<String> inputStringArray = new ArrayList<>();
ArrayList<String> tokensArray = new ArrayList<>();
ArrayList<Integer> frequenciesArray = new ArrayList<>();
// turn Files into arrayLists of StringBuilders
deleteArray = fileToArray(deleteFile);
replaceArray = fileToArray(replaceFile);
inputArray = fileToArray(inputFile);
System.out.println("# words in original file: " + wordCount(inputArray));
// create a deleteList object
DeleteList delete = new DeleteList();
delete.compareArray(inputArray, deleteArray);
System.out.println("Word Count After Deleteing noise: " + delete.wordCount(inputArray));
System.out.flush();
// create a replacelist object
ReplaceList replace = new ReplaceList();
replace.compareArray(inputArray, replaceArray);
System.out.println("Word count after replacing words: " + replace.wordCount(inputArray));
System.out.println("New input printed to 'output.txt'");
}
catch (FileNotFoundException e){
System.out.println("File not found");
}
}
// turns a file into an arraylist of string builders
public static ArrayList<StringBuilder> fileToArray(File fileName) throws FileNotFoundException {
ArrayList<String> array = new ArrayList<>();
ArrayList<StringBuilder> sbArray = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null)
{
if (!line.isEmpty()) {
Stream.of(line.split("\\s+")).forEachOrdered(word -> array.add(word));
}
}
} catch (Exception e) {
System.out.printf("Caught Exception: %s%n", e.getMessage());
e.printStackTrace();
}
for(int i = 0; i < array.size(); i++) {
StringBuilder sb = new StringBuilder();
sb.append(array.get(i));
sbArray.add(sb);
}
for(int i = 0; i < sbArray.size(); i ++) {
if
(sbArray.get(i).toString().endsWith(",") ||
sbArray.get(i).toString().endsWith(".") ||
sbArray.get(i).toString().endsWith(" ")
||sbArray.get(i).toString().endsWith(":")) {
sbArray.get(i).deleteCharAt(array.get(i).length() - 1);
}
}
return sbArray;
}
public static int wordCount(ArrayList<StringBuilder> array) {
int count = 0;
for (int i = 0; i < array.size(); i++) {
count++;
}
return count;
}
}
import java.util.ArrayList;
public class DeleteList extends ArrayList<Object> implements MyInterface {
/**
*
*/
private static final long serialVersionUID = 1L;
//constructor
#Override
public ArrayList<StringBuilder>
compareArray(ArrayList<StringBuilder> inputArray, ArrayList<StringBuilder> deleteArray) {
for (int i = 0; i < deleteArray.size(); i++) {
for (int j = 0; j < inputArray.size(); j++) {
if (deleteArray.get(i).toString().equals(inputArray.get(j).toString())){
inputArray.remove(j);
}
}
}
return inputArray;
}
#Override
public int wordCount(ArrayList<StringBuilder> inputArray) {
int count = 0;
for (int i = 0; i < inputArray.size(); i++) {
count++;
}
return count;
}
}
import java.util.ArrayList;
public class ReplaceList extends ArrayList<Object> implements MyInterface {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public ArrayList<StringBuilder>
compareArray(ArrayList<StringBuilder> inputArray, ArrayList<StringBuilder> replaceArray) {
String wordToReplace, wordReplacingWith = null;
for (int i = 0; i < replaceArray.size(); i++) {
wordToReplace = replaceArray.get(i).toString();
wordReplacingWith = replaceArray.get(i +1).toString();
for (int j = 0; j < inputArray.size(); j++) {
if (inputArray.get(j).toString().equalsIgnoreCase((wordToReplace))) {
StringBuilder strB = new StringBuilder();
strB.append(wordReplacingWith);
inputArray.set(j, strB);
}
}
}
return inputArray;
}
#Override
public int wordCount(ArrayList<StringBuilder> inputArray) {
int count = 0;
for (int i = 0; i < inputArray.size(); i++) {
count++;
}
return count;
}
}
It should be printing to the console:
words in the original file :
words after deleting noise:
words after replacing words:
New Input printed to "output.txt" <--- (i haven't coded this part yet)
Note:
I have to use string builders, implement an interface, and have the
delteList and replaceList extend ArrayList & handle all exceptions in
main
You're problem is this:
ReplaceList#compareArray
while (i < replaceArray.size()) {
wordReplacingWith = replaceArray.get(i + 1).toString();
}
You probably want to increment i at some point or more likely you need a different counter here.
And those System.exit() commands that prevent compilation ;)
The only thing I am seeing in the updated version is a potential ArrayIndexOutOfBoundsException for
for (int i = 0; i < replaceArray.size(); i++) {
...
wordReplacingWith = replaceArray.get(i +1).toString();
...
}
Unrelated to any endless loop problem you might still have:
DeleteList#compareArray is likely to skip elements after a remove operation,
as the new element on position j (the former j+1) element is not covered by your loop.
So I'm writing a basic MasterMind game that is... mostly functional. However, its exhibiting odd behavior and I'm unsure why.
The idea is that what defines a Code and its behavior is one file, the gameplay is another, and the Main just creates a new game and starts playing. When I initialize the game, the computer creates a new random string of 4 (the "secret code"), as expected; but then once I get input for the User guess, it seems to rewrite the secret code into whatever I've input. Further, my methods for evaluating matches don't work at all, but considering that the secret code keeps changing means that it's not being set to begin with, and I'm unsure why.
All three classes below. Why is my class variable in Game not setting properly and accessible to the other methods?
Main.java
class Main {
public static void main(String[] args) {
Game newGame = new Game();
newGame.play();
}
}
Code.java
import java.util.Random;
import java.util.HashMap;
import java.util.Collection;
import java.util.ArrayList;
import java.util.Set;
import java.lang.Math;
import java.lang.StringBuilder;
class Code {
private static HashMap<String,String> PEGS;
private static ArrayList<String> pegStrings;
protected static String secretCodeString;
public static void main(String[] args) {
}
public Code(String input){
this.secretCodeString = input;
}
public Code(){
randomize();
}
//literally just creates the peghash
public static void setPegs(){
PEGS = new HashMap<String,String>();
PEGS.put("C","c");
PEGS.put("Y","y");
PEGS.put("R","r");
PEGS.put("P","p");
PEGS.put("O","o");
PEGS.put("G","g");
}
//turns the pegs ito something randomize can use
public static ArrayList<String> makePegArray(){
setPegs();
pegStrings = new ArrayList<String>();
Collection<String> pegValues = PEGS.values();
Object[] pegObjects = pegValues.toArray();
for (int i = 0; i < pegObjects.length; i++){
pegStrings.add(pegObjects[i].toString());
}
return pegStrings;
}
// sets Class Variable secretCode to a four letter combination
public static Code randomize(){
secretCodeString = new String();
Random rand = new Random();
int randIndex = rand.nextInt(makePegArray().size());
for (int i = 0; i < 4; i++){
randIndex = rand.nextInt(makePegArray().size());
secretCodeString = secretCodeString.concat(makePegArray().get(randIndex));
}
Code secretCode = parse(secretCodeString);
return secretCode;
}
public static Code parse(String input) {
setPegs();
makePegArray();
String[] letters = input.split("");
StringBuilder sb = new StringBuilder();
for (String letter : letters) {
if (pegStrings.contains(letter)) {
sb.append(letter);
} else {
System.out.println(letter);
throw new RuntimeException();
}
}
String pegListString = sb.toString();
Code parsedCode = new Code(pegListString);
//System.out.println(parsedCode);
return parsedCode;
}
public int countExactMatches(Code guess){
String guessString = guess.secretCodeString;
int exactMatches = 0;
String[] guessArray = guessString.split("");
String[] winningCodeArray = (this.secretCodeString).split("");
for(int i = 0; i < 4; i++){
if(guessArray[i] == winningCodeArray[i]){
exactMatches++;
}
}
return exactMatches;
}
public int countNearMatches(Code guess) {
String guessString= guess.secretCodeString;
HashMap<String,Integer> guessCount = new HashMap<String,Integer>();
HashMap<String,Integer> secretCodeCount = new HashMap<String,Integer>();
Set<String> codeKeys = guessCount.keySet();
int matches = 0;
int keys = guessCount.keySet().size();
String[] keyArray = new String[keys];
for(int i = 0; i < guessString.length(); i++) {
//removes character from string
String codeCharacter = String.valueOf(guessString.charAt(i));
String guessShort = guessString.replace(codeCharacter,"");
//counts instances of said character
int count = guessString.length() - guessShort.length();
guessCount.put(codeCharacter, count);
}
for(int i = 0; i < secretCodeString.length(); i++) {
//removes character from string
String winningString = this.secretCodeString;
String winningCodeCharacter = String.valueOf(winningString.charAt(i));
String winningCodeShort = guessString.replace(winningCodeCharacter,"");
//counts instances of said character
int count = winningString.length() - winningCodeShort.length();
secretCodeCount.put(winningCodeCharacter, count);
}
for (int i = 0; i < keys; i++) {
codeKeys.toArray(keyArray);
String keyString = keyArray[i];
if (secretCodeCount.containsKey(keyString)) {
matches += Math.min(secretCodeCount.get(keyString), guessCount.get(keyString));
}
}
int nearMatches = matches - countExactMatches(guess);
return nearMatches;
}
}
Game.java
import java.util.Scanner;
class Game {
protected static Code winningCode;
public static void main(String[] args){
}
public Game(){
winningCode = new Code();
}
protected static Code getGuess() {
Scanner userInput = new Scanner(System.in);
int count = 0;
int maxTries = 5;
while(true){
try {
String codeToParse = userInput.next();
Code guess = Code.parse(codeToParse);
return guess;
} catch(RuntimeException notACode) {
System.out.println("That's not a valid peg. You have " + (maxTries - count) + " tries left.");
if (++count == maxTries) throw notACode;
}
}
}
protected static void displayMatches(Code guess){
int nearMatches = winningCode.countNearMatches(guess);
int exactMatches = winningCode.countExactMatches(guess);
System.out.println("You have " + exactMatches + " exact matches and " + nearMatches + " near matches.");
}
protected static void play(){
int turnCount = 0;
int maxTurns = 10;
System.out.println("Greetings. Pick your code of four from Y,O,G,P,C,R.");
while(true){
Code guess = getGuess();
displayMatches(guess);
if (guess == winningCode) {
System.out.print("You win!!");
break;
} else if (++turnCount == maxTurns) {
System.out.print("You lose!!");
break;
}
}
}
}
On every guess, you call Code.parse, Code.parse creates a new Code (new Code(pegListString);) and that constructor sets the secretCodeString and because that's static, all instances of Code share the same variable. You need to avoid mutable static members.
Another tip is to either have a method return a value, or mutate state (of either its input, or its own instance, this), but avoid doing both.
"Why is my class variable rewriting itself after an unrelated method runs?"
Because, actually, it is not unrelated. The "mess" that you have created by declaring variables and methods as static has lead to unwanted coupling between different parts of your code.
It is difficult to say what the correct solution is here because your code has gotten so confused by the rewrites that it is hard to discern the original "design intent".
My advice would be to start again. You now should have a clearer idea of what functionality is required. What you need to do is to redo the object design so that each class has a clear purpose. (The Main and Game classes make sense, but Code seems to be a mashup of functionality and state that has no coherent purpose.)
I am attempting to sort the values in my program using the Bubble Sort method. I believe that my code in the organisedRoom method is correct. However when I run the code, add some customers and then attempt to sort them, the program crashes. If anyone can please point me in the right direction I would greatly appreciate it.
package test;
import java.io.IOException;
import java.util.Scanner;
public class Test {
private class Customer implements Comparable<Customer>{
private String name;
public Customer(String name) {
this.name = name;
}
//Override to stop the program returning memory address as string
#Override
public String toString() {
return name;
}
#Override
public int compareTo(Customer c) {
return name.compareTo(c.name);
}
}
//Array to store customers
public Customer[] customers;
public Scanner input = new Scanner(System.in);
public Test(int nRooms) throws IOException {
customers = new Test.Customer[nRooms];
System.out.println("Welcome to the Summer Tropic Hotel\n");
chooseOption();
}
final JFileChooser fc = new JFileChooser();
// Call new Hotel with int value to allocate array spaces
public static void main(String[] args) throws IOException {
Test t = new Test(11);
}
// New procedure to return User input and point to next correct method
private String chooseOption() throws IOException {
// Set to null, this will take user input
String choice;
//Menu options
System.out.println("This is the Hotel Menu. Please choose from the following options:\n");
System.out.println("A: " + "This will add a new entry\n");
System.out.println("O: " + "View booked rooms, in order of customers name.\n");
System.out.println("X: " + "Exit the program\n");
// Take user input and assign it to choice
choice = input.next();
// Switch case used to return appropriate method
switch (choice.toUpperCase()) {
case "A" :
System.out.println("");
addCustomer();
return this.chooseOption();
case "O" :
System.out.println("");
organisedRoom();
return this.chooseOption();
case "X":
System.exit(0);
}
return choice;
}
// Add a new customer to the Array
public void addCustomer() throws IOException {
// New variable roomNum
int roomNum = 1;
// Loop
do {
// Take user input as room number matching to array index - 1
System.out.println("Please choose a room from 1 to 10");
roomNum = input.nextInt() - 1;
// If room is already booked print this
if (customers[roomNum] != null) {
System.out.println("Room " + roomNum + 1 + " is not free, choose a different one.\n");
this.addCustomer();
}
// Do until array index does not equal to null
} while (customers[roomNum]!= null);
System.out.println("");
// User input added to array as name replacing null (non case-sensetive)
System.out.println("Now enter a name");
customers[roomNum] = new Customer(input.next().toLowerCase());
// Customer (name) added to room (number)
System.out.println(String.format("Customer %s added to room %d\n", customers[roomNum], roomNum + 1));
}
private void organisedRoom() {
boolean flag = true;
Customer temp;
int j;
while (flag) {
flag = false;
for (j = 0; j < customers.length - 1; j++) {
if (customers[j].compareTo(customers[j+1]) < 0) {
temp = customers[j];
customers[j] = customers[j + 1];
customers[j + 1] = temp;
flag = true;
}
}
}
}
}
I think this is because the initialisation of the array adds null to all the array index places.
The stack trace is as follows:
Exception in thread "main" java.lang.NullPointerException
at test.Test$Customer.compareTo(Test.java:34)
at test.Test.organisedRoom(Test.java:133)
at test.Test.chooseOption(Test.java:83)
at test.Test.chooseOption(Test.java:79)
at test.Test.chooseOption(Test.java:79)
at test.Test.<init>(Test.java:46)
at test.Test.main(Test.java:55)
Java Result: 1
It fails because you create Customer[] which will be initialized with11 null references. If you want to order them all elements in the array will be compared. Which lead into the java.lang.NullPointerException.
Store the Customer in an ArrayList. Then you should be able to prevent this error.
edit
If you really need to stick as close as possible to your current code. The following would fix your sorting. (don't use this solution for a real life project)
private void organisedRoom() {
for (int i = customers.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (customers[j + 1] == null) {
continue;
}
if (customers[j] == null ||customers[j + 1].compareTo(customers[j]) < 0) {
Customer temp = customers[j + 1];
customers[j + 1] = customers[j];
customers[j] = temp;
}
}
}
System.out.println("show rooms: " + Arrays.toString(customers));
}
edit 2
To keep most of your current code, you might store the room in the Customer instance (which I personally would not prefer).
// change the constructor of Customer
public Customer(String name, int room) {
this.name = name;
this.room = room;
}
// change the toString() of Customer
public String toString() {
return String.format("customer: %s room: %d", name, room);
}
// store the Customer like
customers[roomNum] = new Customer(input.next().toLowerCase(), roomNum);
Your implementation of Bubble Sort is incorrect. It uses nested for loops.
for(int i = 0; i < customers.length; i++)
{
for(int j = 1; j < (customers.length - i); j++)
{
if (customers[j-1] > customers[j])
{
temp = customers[j-1];
customers[j-1] = customers[j];
customers[j] = temp;
}
}
}
I have an assignment to code a graph matrix that takes numbers labels them and spits out the connections. Right now have the basic problem of this non-static/static stuff. I don't understand the problem even though I thought I understood the difference between a class and an instance of that class. When i run this there is a problem at first for loop. Won't pause for input of the labels. I appreciate any help and/or criticisms.
public class GraphMatrix {
class Matrix {
private int matrix[][];
private int size;
private String labels[];
private void createMatrix() {
Scanner in = new Scanner(System.in);
System.out.println("How many points will be represented in this graph?");
size = in.nextInt();
matrix = new int[size][size];
labels = new String[size];
System.out.println("Please label each point.");
for (int i = 1; i <= size; i++) {
System.out.println("Enter label for point #" + (i));
String key = in.nextLine();
labels[i] = key;
}
System.out.println("Please define edges between points or enter -1 when finished:");
int finish = 1;
while (finish == 1) {
int jkey = 0;
int kkey = 0;
int count = 0;
boolean pass = false;
System.out.println("Point labeled:");
String j = in.nextLine();
while (pass = false) {
if (labels[count].equals(j)) {
jkey = count;
count = 0;
pass = true;
}
}
System.out.println("to point labeled:");
String k = in.nextLine();
while (pass = true) {
if (labels[count].equals(j)) {
kkey = count;
pass = false;
}
}
matrix[jkey][kkey] = 1;
System.out.println("Finished enter -1, to define more connections enter 1");
finish = in.nextInt();
}
}
private void listEdges() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (matrix[i][j] == 1) {
System.out.println("There is an edge between" + labels[i] + " and" + labels[j]);
}
}
}
}
}
public static void main(String[] args) {
Matrix neo = new Matrix();
neo.createMatrix();
neo.listEdges();
}
}
You need to make change in main method as follows to remove compiler error.
From
Matrix neo = new Matrix();
to
GraphMatrix graphMatrix = new GraphMatrix();
Matrix neo = graphMatrix.new Matrix();
Note: To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
I see one significant problem in your code.
This while (pass = false) { should be while (!pass) {
and while (pass = true) { should be while (pass) {
Also: Why are you nesting the Matrix class inside of the GraphMatrix class? That doesn't make sense to me. If I were you, I wouldn't do this unless it is an explicit requirement of your assignment.
import java.io.*;
import java.util.*;
class StepfordHouses {
private ArrayList<Integer> houses; // A list containing houses
private TreeSet<Integer> ordered; // An ordered treeset of houses
private TreeSet<Integer> processed; // Elements already processed
private String inpline[]; // An array of String holing houses heights in physical order
private int disorientedindex; // The index for the Street
private int size; // Number of houses in the Street
public StepfordHouses() // Constructor for init
{
houses = new ArrayList<Integer>();
ordered = new TreeSet<Integer>();
processed = new TreeSet<Integer>();
// Basic Input from Text-File (Codechef Requirment)
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
size = Integer.parseInt(br.readLine());
inpline = br.readLine().split(" ");
} catch (IOException e) {
System.out.println("BAAAAAAAAAM!!");
}
for (int c = 0; c < size; c++) // Populating Houses
{
Integer tmp = Integer.parseInt(inpline[c]);
houses.add(tmp);
ordered.add(tmp);
}
}
public int calcIndex()
{
int c = 0;
while (c < size) {
Iterator<Integer> it = ordered.iterator();
Integer h1 = houses.get(c); // Get an element from the raw ArrayList of Houses
Integer h = it.next(); // Get an element from the Iterator
while (h1.equals(h) != true) {
if (processed.contains(h1) == false) { // The element is not already processed
System.out.println(h1 + " " + h);
disorientedindex++;
}
h = it.next(); // Get an element from the Iterator
}
processed.add(h1);
c++;
it = null;
}
return disorientedindex;
}
}
public class Work {
public static void main(String args[]) {
StepfordHouses sh = new StepfordHouses();
System.out.println(sh.calcIndex());
}
}
The contains() method doesn't work the way I expect it to, i.e compare Integers!
The output is 15 , which should be 9 when
if(processed.contains(h1)==false) works correctly and returns true when an element is already present!
Where could the code be wrong?
The logic is flawed. processed.add(h1); is called N times but processed.contains(h1) is called N*N times. So depending on the input you can have disorientedindex <> N.