I am making a homework planner GUI program in Java. One GUI takes in data from the user about the assignment, determines priority for the order the homework should be done in, then allows the user to view their schedule as another GUI that displays all their assignments in the appropriate days of the week that they will work on them.
My problem is that I can't get the Strings to format correctly in the JLists. See here:
I'm filling the JLists with String representations of Homework Objects from a PriorityQueue, like this:
while(!sun.isEmpty())
sundayListItems.add(sunday.poll().toString());
.
.
.
sundayList = new JList(sundayListItems.toArray());
My toString method in my Homework class looks like this, which works as it's supposed to in the console when I put in System.out.prints to see how it's working:
String string = nameOfAssignment + " for " + hoursPerDay +" hours";
if (string.length()>17) {//17 characters per line in this JList
String[] words = string.split(" ");
string = "";
int count = words.length;
int i = 0;
while(count>0) {
do{
string += words[i] + " "; //adding words to a line until 17 characters
i++;
count--;
} while(string.length() <= 17);
string += "\n";//skips line when 17 characters
do{
string += words[i] + " ";
count--;
i++;
} while(i < words.length);
string += "\n\n";//separates assignments w/ 2 lines
}
}
return string;
But, in the GUI JLists, the Strings are not formatting the way I want. I want the String to wrap around to the next line after 17 characters. Anyone have any ideas?
Related
I am currently programming java and have been asked to develop a program that analyses a sentence that contains several words without punctuation. when a word in that sentence is input, the program identifies all of the positions where that word occurs in that string..
String example:
ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU, ASK WHAT YOU CAN DO FOR YOUR COUNTRY.
Code:
String Scan_word;
Scan_word = JOptionPane.showInputDialog("Word to be scanned for");
String Full_Scan;
Full_Scan = "You have entered " + Scan_word + " "; // the input dialog box will display this when a word is inputted
String sentence = "Ask not what your country should do for you but what you should do for you country"; //The sentence
JOptionPane.showMessageDialog(null, Full_Scan);
if (sentence.contains(Scan_word)); {
String[] sentenceWords = sentence.split(" ");
for (int i = 0; i < sentenceWords.length; i++) {
if (sentenceWords[i].equals(Scan_word)); {
} System.out.println(Scan_word + " is located in the: " + i + "th position");
}
ALL code is in Static void section as should be.
SORRY IT HAS CODING COMMENTS.
PLS ignore the CAQ1STOPBLOCKINGTHEM title as my netbeans projects were being locked for no reason or another.
Your bug seems to be related to your if that is not properly written, indeed you put a semicolon just after it meaning that there no instruction to launch, moreover you print your message outside the curly brackets and finally you should print the value of i + 1 not i since it starts from 0, so your code should rather be:
if (sentenceWords[i].equals(Scan_word)) {
System.out.println(Scan_word + " is located in the: " + (i + 1) + "th position");
}
Consider reading some articles about the naming conventions in java like this one for example. In a nutshell, a varaiable name should start with a lower case.
System.out.println("How many teams are in this tournament?");
no_of_teams=kb.nextInt();
for(int x=1; x<=no_of_teams; x+=1)
{
System.out.println("Please enter the name of team " + x);
team=kb.next();
}
I would like to have team contain all the user inputs, so I can then use String.split later on in the program to output the team names once again.
I asked my original question on Reddit but to no avail, it went like this:
We have been asked to create a program which runs to collect data
based on a round robin soccer tournament for 'n' no. of teams. My
issue is when I must ask for all the team names at the beginning
(which I must) based on what no. of teams the user inputs of course, I
can do this with a for loop and the output is perfect:
input the code from up above here
However, as I am sure you are aware, this
basically means that team will now just be stored as whichever team
name was entered last as the for loop caused it to be overwritten.
This is a problem because later down in the program you are meant to
then output all the different team names for when they are playing
against each other but team is only storing one team name. Using
team1, team2, team3, etc. is impractical because the user can enter an
infinite amount for the number of teams. We are not allowed to use
arrays because we have not covered them yet, and by all accounts the
way I am to get around this is to use String concatenation and while
loops, but I am unsure how this would apply. Any help would be
gratefully appreciated! Thanks.
You can just append names to a String with an attached delimiter:
StringBuilder team = new StringBuilder();
for(int x=1; x<=no_of_teams; x+=1)
{
System.out.println("Please enter the name of team " + x);
//this will add a - after each name, and then you could split on the - character
team.append(kb.next()).append("-");
}
However, this is really not the best options. I would use an array to store names. The answer I gave t would return one big string, that you would have to split on the '-'.
After you got your string, you could split it by doing:
team.toString().split("-");
If you wanted to output all the team names you would do something like:
for(String aTeam : team.toString().split("-")){
System.out.println("Team Name: " + aTeam);
}
Actually, it is possible! You do not have to use arrays or lists provided by java for your convenience, even implicitly like the split method BlackHatSamurai provided in his answer. It's simple - you implement your own ArrayList! Well, ArrayList-like thing anyway.
class MyStringStringList {
private static final char delimeter = '%'; //just a character not in the input
private String internalMemory = "";
public void add(String s) {
internalMemory += s + delimeter;
}
public String getAll() {
return internalMemory;
}
public String get(int index) {
int delimeterCount = 0;
StringBuilder currentWord = new StringBuilder();
for (int j = 0; j < internalMemory.length(); j++) {
if (internalMemory.charAt(j) == delimeter) {
if (delimeterCount == index) {
return currentWord.toString();
} else {
delimeterCount++;
currentWord = new StringBuilder();
}
} else {
currentWord.append(internalMemory.charAt(j));
}
}
throw new ArrayIndexOutOfBoundsException(index);
}
}
I moved this code to a new class for clarity, but you could just paste the insides into your main class and use it from there.
Some usage:
MyStringStringList list = new MyStringStringList();
for (int x = 1; x <= no_of_teams; x += 1) {
System.out.println("Please enter the name of team " + x);
list.add(kb.next());
}
for (int i = 0; i < no_of_teams; i++) {
System.out.println("Team number " + i+1 + ": " + list.get(i));
}
Do note, that only a crazy person would do that. Inefficient, probably buggy, incomplete feature-wise... But if you are not mistaken, and you were in fact prohibited from using the built-in array or collections that could be the "Your rules are stupid" solution your teacher deserves.
The problem requires to input different values for each attribute.Ex:
Color Black White
Water Cool Hot Medium
Wind Strong Weak
I made ArrayList of ArrayList of String to store such thing as no. of values of each attribute is not fixed.The user inputs Black White and on hitting new line the program has to start taking values of NEXT attribute( Cool Hot Medium).The no. of attributes has been already specified.I followed some (almost related) answers here and wrote the following code:
ArrayList<ArrayList<String>> attributes = new ArrayList<ArrayList<String>>();
String input;
for(i=0; i<num_of_Attributes ;i++)
{ System.out.print(" Enter attribute no." + i+1 + " : ");
ArrayList<String> list = new ArrayList<String>();
while(! input.equals("\n"))
{
list.add(input);
input = sc.nextLine();
}
attributes.add(list);
}
The program prints "Enter Attribute 1 : " but even after new line it doesn't print "Enter attribute 2 : ".It goes into infinite loop. How can I achieve what the program requires to do? sc is my Scanner object.
You should read:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine%28%29
specifically the part that states:
This method returns the rest of the current line, excluding any line separator at the end
So, if the user inputs an empty line with only the line separator \n, you will read an empty line without such line separator.
Check while (!input.isEmpty()) or, even better, while (!input.trim().isEmpty())
As a more general rule, you can debug your program (or even just print input) to try to find out yourself what is the actual value you are checking.
As a quick-Hack you can do sth. like
for (i = 0; i < num_of_Attributes; i++) {
input = " ";
System.out.print(" Enter attribute no." + (i + 1) + " : ");
ArrayList<String> list = new ArrayList<String>();
while (!input.isEmpty()) {
list.add(input);
input = sc.readLine();
}
attributes.add(list);
}
not nice but it works. Please also watch out for calculating in String concaternation. In you code it will print 01, 11, 21 and so on. With brackets it will work.
How do I go about getting the result of all the string inputs to print as a list with out the use of arrays? For example, I'd like the list to print vertically, like below, rather than all on one line:
kidsname
bookname
kidsname
bookname
I appreciate any help which can steer me in the right direction!
package part3;
import java.util.Scanner;
public class listnames {
private static Scanner kb;
public static void main(String args[]) {
String finished;
String kidsname;
String storage = " ";
String bookname;
String storageb = " ";
String storagec = " ";
int noofchild;
kb = new Scanner(System.in);
System.out.print("How many Children do you have?");
noofchild = kb.nextInt();
for (int k = 1; k <= noofchild; k++) {
System.out.print("What is the kids name?");
kidsname = kb.next();
storage += (String.valueOf(kidsname) + "\t");
do {
System.out.print("What book did they buy?");
bookname = kb.next();
storageb += (String.valueOf(bookname) + "\t");
System.out.print("Do you want to finish? y/n ");
finished = kb.next();
storagec = (storage + ("\n-----------------------\n") + storageb);
} while (finished.equalsIgnoreCase("n"));
System.out.println();
System.out.print(storagec);
}
}
}
storageb +=(String.valueOf(bookname)+"\t"); --> storageb +=(String.valueOf(bookname)+"\n");
It's almost like you're doing too much here. You have kidsname and bookname already declared as variables, yet you're storing them with tabs appended to the end, which is overly verbose, and a bit confusing.
Furthermore, your do...while loop seems misplaced; you're always going to be overwriting the value of bookname if someone decides to continue (even by entering "&" they'll continue).
Lastly, since you know you're dealing with Strings, String#valueOf is unnecessary. In actuality, since you're going to be placing a new line after the tab character, the tab character is also unnecessary.
So, a few things:
Remove storagea, storageb, and storagec - they serve no real purpose.
Move your printing statement inside of the do...while. This way, you can print one child name per with multiple book names per iteration.
Change System.out.print to System.out.println. Everywhere.
Your printing statement would ultimately read like this:
System.out.println(kidsname + "\n-----------------------\n" + bookname);
EDIT: If you want bookname to hold more than one element, keep appending to it. Initialize it to the empty string, then when you read the line, append to it and append a newline as well.
bookname = kb.next() + "\n";
You keep outputting the string using System.out.print(). Try using System.out.println instead.
I am working on an assignment which is confusing to me. It requires me to write a method called processName() that accepts a Scanner for the console as a parameter and prompts the user to enter a full name, then prints the last name first and then the first name last. For instance, if I enter "Sammy Jankins", it would return "Jankins, Sammy".
My plan is to go through the string with a for loop, find an empty space, and create two new strings out of it—one for the first and last name each. However, I am not sure if this is the right path and how to exactly do this. Any tips would be appreciated, thanks.
Here is what I have so far:
import java.util.*;
public class Exercise15 {
public static void main(String[] args) {
Scanner inputScanner = new Scanner(System.in);
processName(inputScanner);
}
public static void processName(Scanner inputScanner) {
System.out.print("Please enter your full name: ");
String name = inputScanner.next();
System.out.println();
int n = name.length();
String tempFirst;
for (int i = 0; i <= name.length()-1; i++) {
// Something that checks the indiviual characters of each string to see of " "exists
// Somethow split that String into two others.
}
}
}
Why don't you simply use String#split?
I won't solve this for you, but here what you should do:
split according to spaces.
Check if the size of the array is 2.
If so, print the second element then the first.
Tip: Viewing the API can save a lot of efforts and time.
Why not just to say:
String[] parts = name.split("\\s+");
String formattedName = parts[1] + ", " + parts[0];
I am leaving it for you as an exercise to support names that contain more than 2 words, for example "Juan Antonio Samaranch" that should be formatted as "Samaranch, Juan Antonio".
Using StringTokenizer will be more easier. Refer http://www.mkyong.com/java/java-stringtokenizer-example/ for example.
You can replace for loop with the following code:
int spaceIdx = name.indexOf(' '); // or .lastIndexOf(' ')
if (spaceIdx != -1) {
int nameLength = name.length();
System.out.println(name.substring(spaceIdx + 1) + ", " + name.substring(0, spaceIdx));
} else {
// handle incorrect input
}
I think you should also consider such inputs - Homer J Simpson
1.Use the StringTokenizer to split the string .This will be very helpful when you are trying to split the string.
String arr[]=new String[2]; int i=0; StringTokenizer str=new StringTokenizer(StringToBeSplited,"");
while(str.hasMoreTokens()){
arr[i++]=new String(str.nextToken());
}
System.out.println(arr[1]+" "+arr[0]);
That's all