Way To Organize Incoming Strings
Oct 8, 2014
If I wanted to take strings in from the user through a GUI say day, month, year. I am looking for a way to organize those incoming strings. I am going to add this information to a queue. However, I want the people who put in the earliest day, month, and year to be put into the queue first followed by the next earliest so on and so forth.I was thinking what I would need to make a method that would compare the information.
View Replies
ADVERTISEMENT
Dec 3, 2014
What is the difference between instansiating a ServerSocket and .accept(); and a ServerSocketChannel .accept();
They both listen on a port for incoming connections so what is the benifit or dissadvantage of ServerSocketChannel?
View Replies
View Related
Feb 16, 2015
When I run this (entering 12 for both questions) I get this error:
java.lang.ArrayIndexOutOfBoundsException: 12
at MathTablesTwo.main(MathTablesTwo.java:22)
Also, what would be the proper way to organize my code into blocks?
import java.util.Scanner;
public class MathTablesTwo {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
[code]....
View Replies
View Related
Apr 13, 2014
I am trying to write a program that read from a csv file called matches.csv.
A single football match can end with a win or a draw: in first case the winner team get 3 points and the loser none, in the second case of draw each of the two teams get 1 point.
For example, the first line of the file matches.txt is as follow:
In the file it contains the following data.
17/08/2013ArsenalAston Villa13
24/08/2013Aston VillaLiverpool01
This means that a match has been played on the 17/08/2013 where Arsenal scored 1 goal while Aston Villa 3 goals: thus Arsenal got 0 points while Aston Villa 3 points.
How can I structure my output to make it make it read
Position Team Played Points
1 Aston Villa 2 3
2 Liverpool 1 3
3 Arsenal 1 0
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Teams {
public static void main(String[] args) {
String fileName = "matches.csv";
File file = new File(fileName);
[code]....
View Replies
View Related
Oct 7, 2014
Lately I've been working with JDBC and writing queries in some Java programs. I've noticed that I keep experimenting with where I place my blocks of querying code. I've tried creating a private method in the class where the query is used, I've created utility classes where I can call the query when needed, and sometimes I've just put it in a localized block of code where I need to. Also, most often these queries are one-shot queries where I need to pull the data to populate a JTable.
In short, this has made me realize that I don't have a solid practice for organizing my queries in Java. So my question is "Is there a practice for organizing query code?".
View Replies
View Related
Aug 15, 2014
I have a couple of objects, which I will call height and width. The latter may depend on the former and I access them through an interface:
interface Height
{
double getHeight();
}
interface Width
{
double getWidth( Height height );
}
I then have something I will call a RectangleMaker, which represents some set of rectangles that can be made. It takes a list of heights and widths and keeps track of which ones have been selected and which ones can still be made. For example, the possible heights might be 2 or 3 and the possible widths 3 or 4. It needs to determine if it can make a rectangle with a specific area and if selected to make that rectangle, disallow any other heights. So if I said, you are in charge of 2 x 3 rectangles, it could still potentially also make 2 x 4 rectangles, but 3 x 3 rectangles would no longer be an option. For the most part I think these details are irrelevant to my question, which is really about organization and assignment of responsibilities.
interface RectangleMaker
{
void setHeights( ArrayList<Height> );
void setWidths( ArrayList<Width> );
boolean isAreaAvailable( double Area );
void selectDimension( Height height, Width width );
Height listAllowedHeight();
ArrayList<Width> listAllowedWidths();
}
Now I have a new requirement. The lists of heights now need to be associated with a source, as do the widths. I should keep track of a list of RectangleMakers and pick the 'most appropriate' one for a particular area. The rule is to sort first on the height source and then on the width source and the first one able to handle the area, gets the job. So I created two enums heightSource and widthSource and had RectangleMaker implement Comparable, so I can make an ArrayList<RectangleMaker> and sort it based on the rules. Then I traverse the list and the first one that returns isAreaAvailable() true gets the job.
The final bit is that these sources also imply a specific set of Heights or Widths. How I get that set varies, it may be a fixed value or values, or might be read from a file. So in principle I could have:
ArrayList<Height> buildHeights( RectangleMaker.SOURCE source )
{
switch ( source )
{
}
}
and have a lot of specific code that builds each list by whatever method is appropriate. I still need to deal with the fact I might need additional information to build the lists. For example, one source might require a min, max and increment and another might require a file name. So I started working in the direction of more interfaces.
interface HeightList
{
ArrayList<Height> getHeights();
RectangleMaker.Source getSource();
}
I am not totally comfortable with my enum lists. They solve the sorting problem, but I am not exactly sure which class should define them. Right now they are defined by the RectangleMaker. I would need to update this class every time I added an implementation of HeightList or WidthList.
I was also thinking that since the list is built from a specific source, that source should be associated with the list. That would lead me to make this change:
interface RectangleMaker
{
void setHeights( HeightList heightList );
void setWidths( WidthList widthList );
boolean isAreaAvailable( double Area );
void selectDimension( Height height, Width width );
Height listAllowedHeight();
ArrayList<Width> listAllowedWidths();
}
It seems maybe there should be a factory in here somewhere, but this is where I am having trouble sorting out exactly who has what responsibility. I can do this sort of thing with my HeightList interface:
class SpacedHeight implements HeightList
{
int start;
int end;
int step;
ArrayList<Height> heights;
RectangleMaker.SOURCE source;
[Code] ....
Should I be thinking of putting one more layer over all of this? What complicates my thinking are two things: multiple instances may have the same source and some of these instances are dynamic. For example, two SpacedHeight instances may have different ranges, but they are both SpacedHeight and it doesn't matter which gets picked first. Exactly what SpacedHeight instances get created is determined by prompting the user for the values. If the heights come from a file, every instance would be associated with a different source and the file names would be hard-coded.
I think I want to make a HeightFactory and I think then it would make sense to move my enum definitions there. I see how I would do that if I could hard-code a specific instance of a HeightList with a specific enum. I am less clear on how to handle the case where the factory needs different parameters for different HeightList implementations.
View Replies
View Related
Apr 13, 2014
I'm trying to program a tile-based map editor and most of it is going quite smoothly except trying to organize the layout. Originally I was going to use 2 frames, one for the map, and 1 for the tile set, but after reading about frames I learned that that is bad practice and is also inconvenient because there is no way to have both frames in focus at once (so you need to click an extra time to gain focus when switching windows). So what I'd like to do is create a single frame application that holds 3 panels. One for the map, one for the tile set, and one for tile settings. This is basically what it would look like:
Note that the tile settings panel uses GUI elements (a border, a JLabel (which starts out empty), a JComboBox, and a JTextField) while the other 2 panels are just drawing panels*
Now I have tried multiple things which either did not work visually (panels were inside panels) or did not compile. One thing I tried was using BoxLayout to put the 2 tile panels vertically within a temporary panel which I then tried to add into the frame after the map panel (with FlowLayout), but that made it look like this: I honestly don't know what else I did that I should write here because in retrospect many of the tings I tried were silly or I don't remember exactly what I did. What would be the best layout to doing what I want?
View Replies
View Related
Mar 20, 2014
I'm currently taking a computer program design class which has done a lot for my understanding of how to organize classes, but isn't giving me challenging enough assignments and I don't believe it's going to be covering interfaces and abstract classes, which is a shame. So I've been digging into these topics myself and decided to work on my own program (an Uno game program) that would utilize everything we've been learning and give me some practice with GUIs.
My current plan:
Have an abstract UnoCard class that determines the basic properties/methods common to all cards. Create a class for each card type extending from UnoCard, which would be - the generic card (number and color), action cards (skip, reverse, draw two), and special cards (wild, wild draw four, and blank).
Two enums, one for color, one for rank (which includes the numbers, as well as the action and special card ranks (reverse, wild, exc.) ).
A deck class would have an ArrayList <UnoCard> property and it's constructor would initialize a fresh deck.
A hand class that also has an ArrayList <UnoCards> where it gets said cards from the deck class.
A discard pile class, which contains the cards discarded and the current card in play.
A "board" class (haven't figured out a better name for it yet) which would determine/keep track of the number of players/hands, the turn order, the locations of the cards, and the winning condition.
Area of confusion and concern I'm having:
From what I've read, I want to avoid circular dependency. So if that's the case, when a card type effects the state of a "hand" or the turn order or really anything else, then in what class do I place the method(s) that effect that? If I place it in the specific card class, wouldn't that create a circular dependency? So would it be better then to have the hand class figure out what can be done with a specific card and what that specific card effects (which wouldn't that hinder the cohesion of the class?)?
I was also thinking a possible solution might be to have the non-generic card types contain methods that return values as apposed to manipulating higher level classes, such as a boolean drawCards which returns true if cards need to be drawn, false otherwise (same for skip, reverse, exc.).Then maybe the board class can determine what to do if those values are true or false (which actually seems more convoluted since only one value would be allowed to be true at any given time).
The other solution I was considering is to have a single UnoCardRules class, which serves the sole function of providing methods to determine the effects of each card, that way each card class can only worry about defining the card's state.
View Replies
View Related
Aug 25, 2014
I am having an array of strings and i want to find out whether these strings contained in the array contain a similar character or not.For example i am having following strings in the array of string:
aadafbd
dsfgdfbvc
sdfgyub
fhjgbjhjd
my program should provide following result: 3 because i have 3 characters which are similar in all the strings of the array(f,b,d).
View Replies
View Related
Mar 26, 2014
I can sort strings in a collection by uppercase and then lowercase though I was wondering if there is any way of doing it in reverse, sorting by lowercase then by uppercase.
View Replies
View Related
Mar 13, 2014
Its supposed to notify the user if they have a palindrome, but keeps returning true even when I type, "hello".
import java.util.Scanner;
public class PalinDrome {
public static void main(String[] args) {
String line;
Scanner input = new Scanner(System.in);
System.out.print("Please enter a word ");
[code]....
View Replies
View Related
Feb 12, 2014
I know that in c++ in order to read a string like
PHP Code:
. you need to use
getline(cin,string variable)
. In java, I have noticed that using
String name=keyboard.nextLine()
automatically reads the whole line...Suppose I wanted to read the first name only, how would I be able to accomplish that?
View Replies
View Related
Jul 3, 2014
example input (#federer #great #game )->
output : [federer] [great][game], [federer, game],[federer,great], [game,great], [federer, game,great]
View Replies
View Related
May 18, 2015
I need my code to print out the top three most common IP Addresses in the ArrayList. Right now I have it printing out the top IP Address. I am a little confused as to how to get it to print out three. Every time I change something, It doesn't give me the correct results
My Code:
public class Log_File_Analysis {
private static ArrayList<String> ipAddress = new ArrayList<>();
private static String temp , mostCommon;
static int max = 0;
static int num = 0;
[Code] .....
View Replies
View Related
Jul 19, 2014
Below is the snippet of code
public static void main(String[] args) throws Exception {
String s = "oldString";
reverse(s);
System.out.println(s); // oldString
}
public static void modifyString(String s) {
s = "newString";
System.out.println(s); // newString
}
I thought the first print statement would print "newString" as String is an object, and when we pass objects between methods, changing state of the object in any method reflects across the methods.
View Replies
View Related
May 12, 2015
I am asking the user a question and already have a correct answer. The answer is a string but is more than one word.
When the user types in the correct answer, it still comes up as wrong but I only have the input.next method.
Quote
Why are rabbits ears long?
United states of america
Incorrect!
View Replies
View Related
Jan 3, 2014
So the while loop I am trying to use is:
while( type != "EXIT" ) {
type = input.next();
}
The problem is that typing in EXIT doesn't end the loop like I want it to. I also tried input.nextLine(); but neither of them work. The loop is being used to fill an ArrayList so the number of elements can change based on how many they want. What am I doing wrong, or what alternatives do I have?
Seems I need to use !type.equals("EXIT")
View Replies
View Related
Sep 21, 2014
covers switch statements and if/else statements. Java doesn't like the Strings for some reason. My instructor does her strings just like this and it works for her. I can figure out the rest of the program if I can only get around the: "java error35: sSymbol variable might not have been initialized.
import java.util.*;
public class RockPaperScissors
{
public static void main(String[] args) {
//generate outcome
int symbol = (int)(Math.random() * 4);
String sSymbol;
[code]....
View Replies
View Related
May 6, 2014
I have to write a java programm,where i have given string. Output should be like that:
1. print only once what characters are apearinng in string, and the last index of it
2. print how many characters are in the string
I have to do it only with loops,no special classes
So far:
public static void main( String[] args ) {
String besedilo = "Testiranje";
besedilo = besedilo.toLowerCase();
for (int i=0; i<besedilo.length();i++)
[code]...
View Replies
View Related
May 1, 2015
I am making a simple calculator. I want the user to input either string "add" or "subtract" and then it will take two numbers and either add or subtract them. I cannot get the if statement to work with a string!
import java.util.Scanner;
public class newcalc {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter add or subtract");
String line = input.nextLine();
if input = "add";
View Replies
View Related
Jun 12, 2014
Im trying to make a question game, much like a spin off from Trivial Pursuit. In this code, I call classes to get a random number. This number determines what category the question will be from. Coinciding with this number, the "if" statements go and pull the questions and answers from an alternate class. My problem is that when I try and output what should be the question and the 3 answers, its outputs "null" for each String?
This is my first class, which is just the class for the player.
Java Code: /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
[Code].....
View Replies
View Related
Sep 24, 2014
Output of the program given below:
class A123
{
public static void main(String args[])
{
String s1="hello123";
String s2="hello"+String.valueOf(123);
String s3="hello"+"123";
String s5=new String("hello123");
[Code] ....
why s1 is equal to s3 and not s2
View Replies
View Related
Apr 1, 2014
I have figured out, how to diplay basic datatypes of an entity / object in a dataTable, but I can't find a way to display a List<String>.
I also tried it with ui:repeat, but the space, where it should appear, stays empty. This is my code right now:
Product.java (the entity)
...
@ElementCollection
@CollectionTable(name="NeededRessources", joinColumns=@JoinColumn(name="product_id"))
@Column(name="resource")
private List<String> neededResources;
...
And the page: index.xhtml
<ui:repeat value="#{product.neededResources}" var="t">
#{t}
</ui:repeat>
View Replies
View Related
Apr 21, 2014
I'm trying to calculate the average of grades that a user puts in. Here is my code so far:
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("Please enter an array of grades seperated bt a comma.");
input.nextLine();
String arrayOfGrades = "100,50,100";
String[] grades = arrayOfGrades.split(",");
[Code] .....
I think I'm on the right track, the only big error I'm really getting is the line: sum += grades[i]. It's saying string can not be converted into a double.
View Replies
View Related
Apr 25, 2015
I am making a program i want String length and compare it that it will be null or not but it gives me error.
View Replies
View Related
Feb 10, 2014
I want get a specific document from data set if a given string matches in that document.
If given string is 'what is java' and,
doc1='... what is full form of java ...'
doc2='... is java what ...'
doc3='... what is java ...'
then the output should contains doc1, and doc3.
I'm trying like this.
for(String key_word: key.split("W+")) {
for (String _word : line1.split("W+")) {
if(word.toLowerCase().equals(key_word.toLowerCase())) {
key_final=key_final+" "+key_word;
}
}
}
I'm getting wrong output containing doc1, doc2 and doc3.But I want only the exact match. Here each document is containing some paragraphs.
View Replies
View Related