Im storing names in a array list logcall and printing them out accordingly. But when there are duplicates how do I only print them once rather than however many times they're in the array list?
public static void displayHistory()
{
for(Call allCalls : logCall)
{
if(logCall!=null)
{
String name = allCalls.getName();
Long phone = allCalls.getPhoneNumber();
String type = allCalls.getType();
String time = allCalls.getTime();
String date = allCalls.getDate();
String phoneStr = Long.toString(phone);
if(name.equals("N/A"))
{
System.out.println( PhoneBook.formatNum(phoneStr) + " (" + type + ") " +date + " " + time);
}
else if(search(name) > 1)
{
System.out.println( name + " (" +search(name)+ ") " );
}
else
{
System.out.println( name + " (" + type + ") " + date + " " + time);
}
}
}
A quick thought I had would be to store your output in a string and use the string's .contains method to search for duplicates before adding a new entry. Then you would just print the output string at the very end.
Use a HashSet. This is far more efficient than checking it in a string as Logan Kulinski says, as checking in a string takes N operations, and the complexity will be N^2.
For example,
Collection<String> seen = new HashSet<String>();
for (.....) { //process the items here
//format the stuff and what not
if (!seen.contains(currentString)) {
seen.add(currentString);
print(currentString);
}
Related
I know that I can just use printf to format it but printf is used to print. I want to use the formatting to store the data then call the data to print it outside the do while loop.
#Override
public String toString() {
Scanner input = new Scanner(System.in);
String enter = "", data = "";
double totalCommission = 0.0;
DecimalFormat df = new DecimalFormat();
do {
setTransaction();
setSalesNum();
setName();
setAmount();
setCommission();
setRate();
do {
//prompt user to enter another
System.out.println("Would you like to enter another? [Y/N]");
boolean error = false;
//error prompt if y or n is not entered
enter = input.next();
if (!(enter.equals("n") || enter.equals("N") || enter.equals("y") || enter.equals("Y"))) {
error = true;
System.out.println("Invalid input! Please enter again.\n Would you like to enter another student's mark? [Y/N]");
} else {
error = false;
}
} while (false);
//setting the decimal places
df.setMaximumFractionDigits(2);
df.setMinimumFractionDigits(2);
//transaction details saved here
data += getTransaction() + "\t" + getSalesNum() + "\t\t" + getName() + "\t\t" + (df.format(getAmount())) + "\t" + " " + getRate() + "%" + "\t\t" + (df.format(getCompute())) + "\n";
totalCommission = totalCommission + getCompute();
} while (enter.equalsIgnoreCase("Y"));
System.out.println("Sales\tCommission");
System.out.println("TNO#\tSALESNO#\tNAME\t\tAMOUNT\t\t" + " " + "COMM RATE\tCOMMISSION");
return String.format(data + "\t\t\t\t\t\t" + " " + "TOTAL COMMISSION\t" + (df.format(totalCommission)));
}
So what I wanted to do is for this part data += getTransaction() + "\t" + getSalesNum() + "\t\t" + getName() + "\t\t" + (df.format(getAmount())) + "\t" + " " + getRate() + "%" + "\t\t" + (df.format(getCompute())) + "\n"; to be formatted inside while (enter.equalsIgnoreCase("Y")); then send data here: return String.format(data + "\t\t\t\t\t\t" + " " + "TOTAL COMMISSION\t" + (df.format(totalCommission)));
I'm sorry but I don't understand what you want to achieve. You may add an input and desired output example.
First of all:
if (!(enter.equals("n") || enter.equals("N") || enter.equals("y") || enter.equals("Y"))) {
if (!(enter.equalsIgnoreCase("n")|| enter.equalsIgnoreCase("y"))) {
You talked about print so you may want to take a look into: https://www.javatpoint.com/java-string-format
Because you mentioned String.format already I guess I misunderstood your question. If you reply back to me I will try to help you.
You wrote that you want to store your data inside that while loop and return it later. In this case, I would add every data to a list and return this list.
I am trying to get data from a result set into my java application so that I can display it to the user. Something I'd like to implement is a partial search function that displays multiple rows of data based on an input string. If that string appears in any serial number in the database, it pulls that entire row and adds it to a string.
res is the ResultSet
public String searchToString() {
String temp = "";
try {
while(res.next()) {
temp = res.getString("ProductCode") + " " + res.getString("SerialNum") + " "
+ res.getString("DateSold") + " " + res.getString("SoldTo") + " " + res.getString("Notes") + "\n";
}
} catch (SQLException se) {
System.out.println(se);
}
return temp;
}
I have tried changing the queries I use and figured out that the LIKE query was the best one. However, if I try outputting the string to a text area I only see one output where many more are supposed to be. I am definitely missing something from my code to tell it to continue adding the rest of the rows to the string, but I haven't come across anything on the Internet that can tell me what it is.
You are overwriting temp
//try +=
temp += res.getString("ProductCode") + " " + res.getString("SerialNum") + " "
+ res.getString("DateSold") + " " + res.getString("SoldTo") + " " + res.getString("Notes") + "\n";
}
//or temp = temp +
temp = temp + res.getString("ProductCode") + " " + res.getString("SerialNum") + " "
+ res.getString("DateSold") + " " + res.getString("SoldTo") + " " + res.getString("Notes") + "\n";
}
This question already has answers here:
How do I break out of nested loops in Java?
(37 answers)
Closed 4 years ago.
I've been working on a program that will take the user's input of the name or symbol of an element in the periodic table and then output some facts about that element. After quite a few questions on here I've gotten to the point the program stores all the data correctly, outputs it in the way I want and can accept an input of both the name or symbol. The problem I'm having now is that the breaks I have inserted into a loop are not actually breaking from the loop, and I'm really not sure why. The program will just keep on asking for an input even if it received a correct input. In addition, if the user inputs a symbol rather than a name the program will repeatedly tell the user that their input was invalid before finally outputting correctly (and then restarting the loop rather than breaking as it should). I'm new to Java, so if anyone could help me fix either of these issues and explain why the problem occurred and how they fixed it fairly simply I would greatly appreciate it.
import java.util.Scanner;
public class PeriodicTable {
public enum Element {
Hydrogen("H", "Nonmetal", "1.008"),
Helium("He", "Noble Gas", "4.003"),
Lithium("Li", "Alkali Metal", "6.941"),
Beryllium("Be", "Alkaline Earth", "9.012"),
Boron("B", "Semimetal", "10.811"),
Carbon("C", "Nonmetal", "12.011"),
//The rest of the periodic table is here, I just removed it for the sake of this post.
private String symbol;
private String group;
private String weight;
private Element(String symbol, String group, String weight) {
this.symbol = symbol;
this.group = group;
this.weight = weight;
}
}
static Element cName = null;
public static void main(String[] args) {
System.out.println("Enter the name or symbol of an element in the periodic table. ");
do {
Scanner reader = new Scanner(System.in);
String input = reader.nextLine().trim();
for (Element sy : Element.values()) {
if (sy.symbol.equalsIgnoreCase(input)) {
System.out.println("Element: " + sy + " (" + sy.symbol + ")" + "\nGroup: " + sy.group + "\nAtomic Mass: " + sy.weight);
reader.close();
break;
} else {
try {
cName = Element.valueOf(input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase());
System.out.println("Element: " + cName + " (" + cName.symbol + ")" + "\nGroup: " + cName.group + "\nAtomic Mass: " + cName.weight);
reader.close();
break;
} catch(IllegalArgumentException e) {
System.out.println("That name or symbol is not valid. Please try again. ");
continue;
}
}
}
} while (true);
}
}
The problem is that the break's are within the for loop, so it only breaks to for loop. If you want to break the do-while loop you can use a label:
outer:
do {
Scanner reader = new Scanner(System.in);
String input = reader.nextLine().trim();
for (Element sy : Element.values()) {
if (sy.symbol.equalsIgnoreCase(input)) {
System.out.println("Element: " + sy + " (" + sy.symbol + ")" + "\nGroup: " + sy.group + "\nAtomic Mass: " + sy.weight);
reader.close();
break outer;
} else {
try {
cName = Element.valueOf(input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase());
System.out.println("Element: " + cName + " (" + cName.symbol + ")" + "\nGroup: " + cName.group + "\nAtomic Mass: " + cName.weight);
reader.close();
break outer;
} catch(IllegalArgumentException e) {
System.out.println("That name or symbol is not valid. Please try again. ");
continue;
}
}
}
} while (true);
I am trying to get rid of multiple specific strings. For instance, I have a string that prints:
1.jedi
2.sith
3.sith
4.sith
5.bounty hunter
6.jedi
7.sith
8.robot
My goal is to remove duplicates so that it prints:
jedi
sith
bounty hunter
robot
If I change one of the jedi to "something jedi.", it will not print "something jedi."
Output should be:
1.jedi
2.sith
3.bounty hunter
4.robot
5.something jedi
Right now I am using this code to achieve the task of removing duplicates.
if (department.contains(departmentList.get(empName))){
}
else{
department += j + ": " + departmentList.get(empName) + "\n";
j++;
}
I understand where the mistake is. Since I am using .contains(VARIABLE), when it checks "something jedi" it will find that the word JEDI is already there. therefore it returns true and it won't add it to the department.
Create a set to contain the full names of the departments already output. Each time you want to output a department, check if the set contains it already. If not, then output the department name and add it to the set.
For example:
Set<String> usedDepartments = new HashSet<String>();
Then in your loop:
if(!usedDepartments.contains(departmentList.get(empName))) {
department += j + ": " + departmentList.get(empName) + "\n";
j++;
usedDepartments.add(departmentList.get(empName));
}
As your department's value:
department += j + ": " + departmentList.get(empName) + "\n";
You may change your IF statement:
if (department.contains(": " + departmentList.get(empName) + "\n"))
SUPPOSE:
department = "1: something jedi.\n";
departmentList.get(empName) = "jedi.";
department.contains(": " + departmentList.get(empName) + "\n"); // will return false
Firstly, split your String into Link.
Secondly, make a Set from it, so it will delete all the repetitions.
department should be a Set<String>, not a String:
Set<String> departments = new HashSet<String>();
then every loop:
departments.add(departmentList.get(empName));
and after the loop:
int i = 0;
String output = "";
for (String s : departments)
output += i + ": " + s + "\n";
I have 2 list List<String> existingGuesses which contains characters and List<String> word = new ArrayList<String>(words) which contains words which is a copy of list words as shown in my code below. What I am trying to do is to iterate through all the words of List word and iterate through the characters of list existingGuesses. Then I want to compare the first character of List existingGuesses with all the words of List word one by one and if a match is found then I want to remove the word from the list. Then the same for next character and continue until there are no more words left to compare. Until now, I could only declare a iterator, it's not necessary to use iterator but I don't know any other ways. My code is as follows:
public List<String> getWordOptions(List<String> existingGuesses, String newGuess)
{
List<String> word = new ArrayList<String>(words);
String c = existingGuesses.get(0); //trying to get the first character
ListIterator<String> iterator = word.listIterator(); //iterator to iterate thorugh word list
while(iterator.hasNext())
{
if(word.contains(c)) //trying to compare
{
word.remove(c);
}
}
return null;
}
Can anybody help me out? The original List words is:
private List<String> words = new ArrayList<String>() {
{
// DO NOT CHANGE THESE WORDS!
String w =
"sentence\n"
+ "together\n"
+ "children\n"
+ "mountain\n"
+ "chipmunk\n"
+ "crashing\n"
+ "drinking\n"
+ "insisted\n"
+ "insulted\n"
+ "invented\n"
+ "squinted\n"
+ "standing\n"
+ "swishing\n"
+ "talented\n"
+ "whiplash\n"
+ "complain\n"
+ "granddad\n"
+ "sprinkle\n"
+ "surprise\n"
+ "umbrella\n"
+ "anything\n"
+ "anywhere\n"
+ "baseball\n"
+ "birthday\n"
+ "bluebird\n"
+ "cheerful\n"
+ "colorful\n"
+ "daylight\n"
+ "doghouse\n"
+ "driveway\n"
+ "everyone\n"
+ "faithful\n"
+ "flagpole\n"
+ "graceful\n"
+ "grateful\n"
+ "homemade\n"
+ "homework\n"
+ "housefly\n"
+ "kickball\n"
+ "kingfish\n"
+ "knockout\n"
+ "knothole\n"
+ "lipstick\n"
+ "lunchbox\n"
+ "newscast\n"
+ "nickname\n"
+ "peaceful\n"
+ "sailboat\n"
+ "saturday\n"
+ "shameful\n"
+ "sidewalk\n"
+ "snowball\n"
+ "splendid\n"
+ "suitcase\n"
+ "sunblock\n"
+ "sunshine\n"
+ "swimming\n"
+ "thankful\n"
+ "thinnest\n"
+ "thursday\n"
+ "whatever\n"
+ "whenever\n"
+ "windmill\n"
+ "american\n"
+ "possible\n"
+ "suddenly\n"
+ "airplane\n"
+ "alphabet\n"
+ "bathroom\n"
+ "favorite\n"
+ "medicine\n"
+ "december\n"
+ "dinosaur\n"
+ "elephant\n"
+ "February\n"
+ "football\n"
+ "forehead\n"
+ "headache\n"
+ "hospital\n"
+ "lollipop\n"
+ "november\n"
+ "outdoors\n"
+ "question\n"
+ "railroad\n"
+ "remember\n"
+ "sandwich\n"
+ "scissors\n"
+ "shoulder\n"
+ "softball\n"
+ "tomorrow\n"
+ "upstairs\n"
+ "vacation\n"
+ "restroom";
addAll(Arrays.asList(w.split("\\s+")));
}
};
Some points to consider:
String c = existingGuesses.get(0); //trying to get the first character
gets the first word in a list of words, not the first character.
To get the first character in a String you can do this:
char c = newguess.getCharAt(0);
Then you can search through the list for words starting with that character. Next you do not want to remove words that contain the character, you want to remove words that start with the character.
Also, you want to get each item from the iterator one at a time:
while(iterator.hasNext()){
String w = iterator.next(); //get the next word in the iterator here
//process w here
}
You seem to want to find if the characters correspond. That is, if the guess is "foo" then you want to remove all words that start with f, and all words that has the second character o and all words that have the third character o. That seem a little strange so you may want to check your logic.
Your method seem to be referring to some global variables and that could be causing you some confusion.