I will have display all the toppings the user selected and there can be more than one but my code only display one at a time. Please advise.
Here is my code for toppings part:
public String toppingsSelect()
{
String toppingsSelectString = "";
if(tomatoCheckBox.isSelected())
{
toppingsSelectString = "Tomato";
}
if(greenPeppersCheckBox.isSelected())
{
toppingsSelectString = "Green Peppers";
}
if(mushroomsCheckBox.isSelected())
{
toppingsSelectString = "Mushrooms";
}
if(blackOlivesCheckBox.isSelected())
{
toppingsSelectString = "Black Olives";
}
if(sausageCheckBox.isSelected())
{
toppingsSelectString = "Sausage";
}
if(extraCheeseCheckBox.isSelected())
{
toppingsSelectString = "Extra Cheese";
}
return toppingsSelectString;
}
displayString = "Pizza type : " + crustSelect() + "\n" +
"Pizza size : " + sizeSelect() + "\n" +
"Toppings : " + toppingsSelect() + "\n" +
"Amount Due : " + dollarDecimalFormat.format(totalPriceFloat);
outputTextArea.setText(displayString);
Each time you assign a value to toppingsSelectString it replace the precedent value. You should put for exemple toppingsSelectString += " " + "Tomato";
public String Cite()
{
String authorsList = "";
Collections.sort(authors);
for(Author a: authors)
{
authorsList += a.firstName.toUpperCase().charAt(0) + ". " + a.lastName + ", ";
}
String cite = authorsList + "\"" + title + "\", " + venue + "(" + getAcronym() + ")" + " , " +
publisher;
return cite;
}
How would I go about adding the word "and" to separate the last two names of the list?
Use a for loop with index.
for (int i = 0; i < authors.size(); ++i) {
if (i == authors.size() - 2) {
authorsList += a.firstName.toUpperCase().charAt(0) + ". " + a.lastName + "and ";
} else {
authorsList += a.firstName.toUpperCase().charAt(0) + ". " + a.lastName + ", ";
}
}
public static String Cite(ArrayList<Author> authors){
String authorsList = "";
Collections.sort(authors, new CustomComperator());
int size = authors.size();
int count = 0;
for(Author a: authors) {
if (size ==1) {
authorsList = a.firstName.toUpperCase().charAt(0) + ". " + a.lastName;
}
else if (count == size-2) {
authorsList += a.firstName.toUpperCase().charAt(0) + ". " + a.lastName ;
}
else if (count == size - 1) {
authorsList += " and " + a.firstName.toUpperCase().charAt(0) + ". " + a.lastName ;
}
else{
authorsList += a.firstName.toUpperCase().charAt(0) + ". " + a.lastName + ", ";
}
count ++;
}
return authorsList;
}
You should use a normal for loop, so you can detect that you're on the first and/or last element.
Other changes:
Remove the , after the last author.
Use StringBuilder to build a String.
List<Author> authors = new ArrayList<>(List.of(
new Author("Stephen", "King"),
new Author("John", "Grisham"),
new Author("William", "Shakespeare"),
new Author("Charles", "Dickens") ));
Collections.sort(authors);
StringBuilder buf = new StringBuilder();
for (int i = 0; i < authors.size(); i++) {
Author a = authors.get(i);
if (i != 0)
buf.append(i < authors.size() - 1 ? ", " : " and ");
buf.append(a.firstName.toUpperCase().charAt(0) + ". " + a.lastName);
}
String authorsList = buf.toString();
System.out.println(authorsList);
Output
C. Dickens, J. Grisham, S. King and W. Shakespeare
Oxford comma
Whether or not you want , comma before and (Oxford comma) is of course entirely up to you.
buf.append(i < authors.size() - 1 ? ", " : ", and ");
Output
C. Dickens, J. Grisham, S. King, and W. Shakespeare
UPDATE
Since all 4 other answers at this time gave bad result for a single Author, here is test result for various number of authors.
Full Test
List<Author> allAuthors = List.of(
new Author("Stephen", "King"),
new Author("John", "Grisham"),
new Author("William", "Shakespeare"),
new Author("Charles", "Dickens") );
for (int aCount = 0; aCount <= allAuthors.size(); aCount++) {
List<Author> authors = new ArrayList<>(allAuthors.subList(0, aCount));
Collections.sort(authors);
StringBuilder buf = new StringBuilder();
for (int i = 0; i < authors.size(); i++) {
Author a = authors.get(i);
if (i != 0)
buf.append(i < authors.size() - 1 ? ", " : " and ");
buf.append(a.firstName.toUpperCase().charAt(0) + ". " + a.lastName);
}
String authorsList = buf.toString();
System.out.println(aCount + ": \"" + authorsList + "\"");
}
Output
0: ""
1: "S. King"
2: "J. Grisham and S. King"
3: "J. Grisham, S. King and W. Shakespeare"
4: "C. Dickens, J. Grisham, S. King and W. Shakespeare"
If you want to do the same without loops you could:
Define a toString or similar method inside your Author class:
class Author{
String firstName;
String lastName;
Author(String firstName,String lastName){
this.firstName=firstName;
this.lastName=lastName;
}
#Override
public String toString(){
return String.format("%s. %s",this.firstName.toUpperCase().charAt(0), this.lastName);
}
}
And use the Collectors.joining to create the initial list (comma separated).
List<Author> authors = Arrays.asList(new Author("Jules", "Verne"),
new Author("Pablo", "Neruda"), new Author("JK", "Rowling"));
authors.sort(Comparator.comparing(a -> a.lastName));
StringBuffer result = new StringBuffer(
authors.stream().limit(authors.size() - 1).map(a -> a.toString()).collect(
Collectors.joining(" ,")));
And after that, add the last "and":
if (authors.size() > 1) {
result.append(String.format(" and %s", authors.get(authors.size() - 1).toString()));
} else {
result.append(authors.get(authors.size() - 1).toString());
}
System.out.println(result);
Output: P. Neruda ,J. Rowling and J. Verne
I have a segment of code that splits a string into tokens and prints them each out on a new line. I am having a hard time writing a code that determines if a word is a reserved word or not. I have to print "Reserved word is: " if the word is a java keyword, otherwise print "Current word is: ". Here is my code so far:
package projectweek3;
/**
*
* Name -
* Email Address -
* Date -
*
*/
public class Week3Project {
final static String program = "/*\n" +
" * To change this license header, choose License Headers in Project Properties.\n" +
" * To change this template file, choose Tools | Templates\n" +
" * and open the template in the editor.\n" +
" */\n" +
"package testapplication2;\n" +
"\n" +
"import java.util.Scanner;\n" +
"\n" +
"/**\n" +
" *\n" +
" * #author james\n" +
" */\n" +
"public class TestApplication2 {\n" +
"\n" +
" /**\n" +
" * #param args the command line arguments\n" +
" */\n" +
" public static void main(String[] args) {\n" +
" Scanner input = new Scanner(System.in);\n" +
" \n" +
" System.out.println(\"Enter integer #1\");\n" +
" int num1 = input.nextInt();\n" +
" \n" +
" System.out.println(\"Enter integer #2\");\n" +
" int num2 = input.nextInt();\n" +
" \n" +
" System.out.println(\"Enter integer #3\");\n" +
" int num3 = input.nextInt();\n" +
" \n" +
" System.out.println(\"Enter integer #4\");\n" +
" int num4 = input.nextInt();\n" +
" \n" +
" System.out.println(\"Enter integer #5\");\n" +
" int num5 = input.nextInt();\n" +
" \n" +
" //determine the sum\n" +
" int sum = num1 + num2 + num3 + num4 + num5;\n" +
" \n" +
" //this is helpful to make sure your sum is correct\n" +
" System.out.println(\"The sum is: \" + sum);\n" +
" \n" +
" //why doesn't this generate the sum correctly\n" +
" double average = sum / 5;\n" +
" \n" +
" //The average, lets hope its right...\n" +
" System.out.println(\"The average of your numbers is: \" + average);\n" +
" \n" +
" }\n" +
" \n" +
"}\n" +
"";
**public static void main(String[] args)
{
String str = program;
String s = "";
for (int i = 0; i < str.length(); i++) {
s += str.charAt(i) + "";
if (str.charAt(i) == ' ' || str.charAt(i) == '\t' || str.charAt(i) == '\n' || (str.charAt(i) == ' ' && str.charAt(i) == '\n')) {
String currentWord = s.toString();
String res = "int";
if (currentWord.equals(res)) {
System.out.println("Reserved word is: [" + currentWord + "]");
}
else {
System.out.println("Current word is: [" + currentWord + "]");
}
s = "";//Clear the string to get it ready to build next token.
}
}**
I would reconsider the way you're looping through the "program."
Instead of going through character by character, use the Java String.split() function.
String program = "int num1 = input.nextInt();\n";
String[] words = program.split("[\\n\\s\\t]");
for (String word : words) {
System.out.println(word);
}
Output:
int
num1
=
input.nextInt();
EDIT:
Since you can't use String.split(), your looping solution looks good. To check if the current word is reserved, try using Set.contains().
Set<String> reserved = new HashSet<>();
reserved.add("int");
// ...
if reserved.contains(word) {
System.out.println("Reserved word is: " + word);
} else {
System.out.println("Current word is: " + word);
}
That is, assuming you're allowed to use Set.
Please help my figure out why this keeps throwing an out of bounds error. i tried making a separate loop keep track of AdminDecisions
String returnProfile() {
String uniPicksString ="";
String studentInfo = null;
//for(int i = 0; i<ApplicantArray.size(); i++) {
studentInfo =FAMILYNAME+ ", " + "average = " + AVERAGE + " ";
for (int j = 0; j<CHOICES.size(); j++) {
if(j<CHOICES.size() - 1) {
uniPicksString = uniPicksString + CHOICES.get(j)+ ": " + " admin decision, " ;
}else {
uniPicksString = uniPicksString + CHOICES.get(j)+ ": " + " admin decision" + "\n";
}
}
//}
return studentInfo + uniPicksString + "\n";
}
the following code shows the desired out put but i cant return it as a string
String printProof() {
// System.out.println("from inside the student class");
String temp=null;
d = new ArrayList<String>();
for(int j = 0 ; j<1; j++) {
System.out.print("\n >>printProof<< " + FAMILYNAME+", " + "average = " + AVERAGE + " ");
for (int i = 0; i<AdminDecision.size(); i++) {
//System.out.println(AdminDecision.get(i));
//temp = CHOICES.get(i)+ ": " + AdminDecision.get(i) + ", ";
if(i<CHOICES.size() - 1) {
temp = CHOICES.get(i)+ ": " + AdminDecision.get(i) + ", ";
}else {
temp = CHOICES.get(i)+ ": " + AdminDecision.get(i) + "\n";
}
System.out.print(temp + " ");
d.add(AdminDecision.get(i));
}
}
return temp + "\n";
}
So I've tried pretty much everything to get rid of the last newline character in my code. Its supposed to print a new line after every recursive call except for the last one. Any ideas?
public static boolean solve(double target, ArrayList<Double> numbers)
{
String print = "";
String newPrint = "";
double compare = 0;
boolean done = false;
for (double num : numbers)
{
if (!done)
{
ArrayList<Double> remaining = new ArrayList<Double>(numbers);
remaining.remove(num);
if (target == num)
{
done = true;
}
else
{
done = solve(target + num, remaining);
if (done)
{
print += ((int) target + (int) num) + " " + "-" + " " + (int) num + " "
+ "="
+ " "
+ ((int) target + "\n");
}
else
{
done = solve(target - num, remaining);
if (done)
{
print += ((int) target - (int) num) + " " + "+" + " " + (int) num + " "
+ "=" + " "
+ ((int) target + "\n");
}
else
{
done = solve(target * num, remaining);
if (done)
{
print += ((int) target * (int) num) + " " + "/" + " " + (int) num
+ " " + "=" + " "
+ ((int) target + "\n");
}
else
{
done = solve(target / num, remaining);
if (done)
{
print += ((int) target / (int) num) + " " + "*" + " "
+ (int) num
+ " " + "="
+ " " + ((int) target + "\n");
}
}
}
}
}
}
}
System.out.print(print);
return done;
}
}
For instance:
void recursiveF(...) {
if ... {
recursiveF(...);
println();
}
...
}
The result is a string but you don't want the last character, so remove it:
print = print.substring(0, print.length()-1);
Use trim() method. It will remove white spaces, newline etc from beginning and end of string.
System.out.print(print.trim());
Short Print the new line character before.
The first thing the recursive function should do is print the new line character.
This way you shift the odd case from the last function call, to the first call, which should not prepend a new line character.
You could add a parameter String prepend = "" to the signature of the recursive method, it's empty on the first call, all further calls have it set to String prepend = "\n".
Then you can just print prepend without bothering with its content.