public void compareTo(String lname1, String lname2) {
/* Note to self: Using this method is case sensitive, because
it only prints if names are found in the array. And those names
are case sensitive inside the array, even though I'm using the
CompareTo method from java's String
class which is NOT inherently case sensitive. ???????? */
boolean foundContact = false;
for(int i = 0; i < arrayOfPersons.size(); i++){
if(arrayOfPersons.get(i).getFname().equals(lname1) && (arrayOfPersons.get(i).getFname().equals(lname2))) {
lname1.compareTo(lname2);
foundContact = true;
}
}
if (foundContact == false)
System.out.println("This option is case sensitive. Check your spelling and try again. Otherwise these contacts do not exist.");
if(lname1.compareTo(lname2) < 0)
System.out.println(lname1 + " comes after " + lname2 + " .");
if(lname1.compareTo(lname2) == 0)
System.out.println(lname1 + " are equal " + lname2 + ".");
if(lname1.compareTo(lname2) > 0)
System.out.println(lname1 + " comes before " + lname2 + " .");
}
case 6:
System.out.println("Enter last name #1:");
String lname3 = scnr.next();
System.out.println("Enter last name #2:");
String lname4 = scnr.next();
Necronomicon.compareTo(lname3, lname4);
break;
// This case is from my main and shows how I use the compareTo method. Just one of many options to my address book.
I created an address book. One of the requirements for my address book is to compare two people by last name. This is the method I wrote to accomplish that goal. However, it's case sensitive when used, so I tried writing a warning to the user.
But the warning prints regardless of whether the contacts are found in the arrayOfPersons. So I think that my boolean is not updating correctly or the way I'm checking to see if the two names exist in the persons array is wrong? Is that right?
Have you tried doing like this ?
boolean foundlname1 = false,foundlname2 = false;
for(int i = 0; i < arrayOfPersons.size(); i++)
{
if(arrayOfPersons.get(i).getFname().equals(lname1) && !foundlname1)
foundlanme1 = true;
if(arrayOfPersons.get(i).getFname().equals(lname2) && !foundlname2)
foundlanme2 = true;
if(foundlanme1 && foundlanme2)
{
foundContact = true;
break;
}
}
if (foundContact == false)
System.out.println("This option is case sensitive. Check your spelling and try again. Otherwise these contacts do not exist.");
else if(lname1.compareToIgnoreCase(lname2) > 0)
System.out.println(lname1 + " comes after " + lname2 + " .");
else if(lname1.compareToIgnoreCase(lname2) == 0)
System.out.println(lname1 + " are equal " + lname2 + ".");
else
System.out.println(lname1 + " comes before " + lname2 + " .");
}
Your if statement in the for loop will never be true unless lname1 and lname2 are equals. I don't know if what you did is what you wanted to do. You can do like this which is similar to your code you already have:
In the compareTo method check if the arrayOfPersons contains those two Persons
if(arrayOfPersons.contains(Person1) && arrayOfPersons.contains(Person2)
and then compare lname1 and lname2 like you did with your last three if statements
Note that to use the contains method you need to ovverride in your Person class the equals method
public void compareTo(String lname1, String lname2) {
boolean foundContact1 = false;
boolean foundContact2 = false;
for(int i = 0; i < arrayOfPersons.size(); i++){
if(arrayOfPersons.get(i).getLname().equals(lname1)) {
foundContact1 = true;
}
}
for(int i = 0; i < arrayOfPersons.size(); i++){
if(arrayOfPersons.get(i).getLname().equals(lname2)) {
foundContact2 = true;
}
}
if (foundContact1 && foundContact2 == false)
System.out.println("This option is case sensitive. Check your spelling and try again. Otherwise these contacts do not exist.");
if(foundContact1 && foundContact2 == true) {
if(lname1.compareTo(lname2) < 0)
System.out.println(lname1 + " comes after " + lname2 + " .");
else if(lname1.compareTo(lname2) == 0)
System.out.println(lname1 + " are equal " + lname2 + ".");
else if(lname1.compareTo(lname2) > 0)
System.out.println(lname1 + " comes before " + lname2 + " .");
}
}
I figured it out. This is what I was looking for. Thanks for the pointers everybody. Similar to solution to what Shreshta proposed, just had to modify his logic a little bit.
Related
For this assignment I have to count the number of operations that my program does. I have put an OpCount counter in my loops etc., but am stumped on how to do so for an if statement. Heres my code for the ifs for some context (Printing details of a specific dam from an array of objects of type dam):
public void printDam(String damName) {
boolean find = false;
for (int i = 0; i<211; i++) {
ObjDam dam = data[i];
if (dam.getDamName().equals(damName)) {
System.out.println("Dam Name: " + dam.getDamName() +
", FSC: " + dam.getFsc() +
", Dam Level: " + dam.getDamLevel());
find = true;
}
}
if (find == false) {
System.out.println("The dam " + damName + " you entered cannot be found in the file");
}
}
Any help would be greatly appreciated.
How do I not store values from the program when it loops back again. For example, if I plan to enter two families, first I will ask for the details of the first family and display their names, and then I want to use the same variables to collect the next family and display their names without having stored information from the previous family.
public static void main(String[] args) {
// TODO code application logic here
String ans;
String res;
double cont;
int cot;
String name;
String order = "";
do {
ans = JOptionPane.showInputDialog(null,"What is the name of the "
+ "family?" );
res = JOptionPane.showInputDialog(null, "How many member in the " + ans +
" family?");
cot = Integer.parseInt(res); // Converts res String to a number
for (int count = 1; count < cot; count ++) {
name = JOptionPane.showInputDialog(null, " Enter first name: " + count);
order += name + " " + ans + "\n";
}
JOptionPane.showMessageDialog(null, "Members of the " + ans
+ " Family" + "\n" + order);
cont = JOptionPane.showConfirmDialog(null, "Do you want to add another "
+ "family", "Membership", JOptionPane.YES_NO_OPTION);
}while (cont == JOptionPane.YES_OPTION);
if (cont == JOptionPane.NO_OPTION){
JOptionPane.showMessageDialog(null," Come Back Again");
}
}
}
Your order variable is a String that you are adding the names to. Just reset it at the beginning of the loop:
...
do {
order = "";
...
Maybe I'm just stupid (probably) but I have been struggling with this for LITERALLY the past five hours and I really can't figure it out. Nothing on this site / google seems to help me; everyone wants to know how to call a method that's defined in the main method in another method, but I am trying to do it the other way around. I am new to java, but I am aware that you can't directly call a variable from a method into another method. However, I have tried so many different iterations of trying to get the values and NOTHING is compiling and I get the same errors over and over again: "error: cannot find symbol" for all of my variables.
All I am trying to do is read a text file and print out what percentage of the words are of x length up to 13 and say how many of those words are in the document so like "Proportion of 1- letter words: .7% (2 words)" is printed out all the way to "Proportion of 13- letter words: 80.7% (7000 words)" (this is how the output is supposed to look, I know it's not pretty).
Anyway please help me because I am stuck and tearing my hair out.
import java.util.*;
import java.io.*;
public class FileReader
{
public static void main (String [] args)throws FileNotFoundException
{
WordCount();
WordLengthCount();
File file = new File("RomeoAndJuliet.txt");
Scanner keyboard = new Scanner(new FileInputStream(file));
System.out.println("Proportion of 1-letter words: " + count1/count + "% (" + count1 + " words)");
System.out.println("Proportion of 2-letter words: " + count2/count + "% (" + count2 + " words)");
System.out.println("Proportion of 3-letter words: " + count3/count + "% (" + count3 + " words)");
System.out.println("Proportion of 4-letter words: " + count4/count + "% (" + count4 + " words)");
System.out.println("Proportion of 5-letter words: " + count5/count + "% (" + count5 + " words)");
System.out.println("Proportion of 6-letter words: " + count6/count + "% (" + count6 + " words)");
System.out.println("Proportion of 7-letter words: " + count7/count + "% (" + count7 + " words)");
System.out.println("Proportion of 8-letter words: " + count8/count + "% (" + count8 + " words)");
System.out.println("Proportion of 9-letter words: " + count9/count + "% (" + count9 + " words)");
System.out.println("Proportion of 10-letter words: " + count10/count + "% (" + count10 + " words)");
System.out.println("Proportion of 11-letter words: " + count11/count + "% (" + count11 + " words)");
System.out.println("Proportion of 12-letter words: " + count12/count + "% (" + count12 + " words)");
System.out.println("Proportion of 13-letter words: " + count13/count + "% (" + count13 + " words)");
}
public static int WordCount(int n)throws FileNotFoundException
{
File file = new File("RomeoAndJuliet.txt");
Scanner keyboard = new Scanner(new FileInputStream(file));
int countABC=0;
while(keyboard.hasNext())
{
keyboard.next();
countABC++;
}
return countABC;
}
public static int WordLengthCount(int n) throws FileNotFoundException
{
File file = new File("RomeoAndJuliet.txt");
Scanner keyboard = new Scanner(new FileInputStream(file));
int count1 = 0;
int count2 = 0;
int count3 = 0;
int count4 = 0;
int count5 = 0;
int count6 = 0;
int count7 = 0;
int count8 = 0;
int count9 = 0;
int count10 = 0;
int count11 = 0;
int count12 = 0;
int count13 = 0;
int blob = 0; // so that if statement runs
while(keyboard.hasNext())
{
if (keyboard.next().length() == 1)
{
count1++;
keyboard.next();
return count1;
}
else if (keyboard.next().length() == 2)
{
count2++;
keyboard.next();
return count2;
}
else if (keyboard.next().length() == 3)
{
count3++;
keyboard.next();
return count3;
}
else if (keyboard.next().length() == 4)
{
count4++;
keyboard.next();
return count4;
}
else if (keyboard.next().length() == 5)
{
count5++;
keyboard.next();
return count5;
}
else if (keyboard.next().length() == 6)
{
count6++;
keyboard.next();
return count6;
}
else if (keyboard.next().length() == 7)
{
count7++;
keyboard.next();
return count7;
}
else if (keyboard.next().length() == 8)
{
count8++;
keyboard.next();
return count8;
}
else if (keyboard.next().length() == 9)
{
count9++;
keyboard.next();
return count9;
}
else if (keyboard.next().length() == 10)
{
count10++;
keyboard.next();
return count10;
}
else if (keyboard.next().length() == 11)
{
count11++;
keyboard.next();
return count11;
}
else if (keyboard.next().length() == 12)
{
count12++;
keyboard.next();
return count12;
}
else if (keyboard.next().length() == 13)
{
count13++;
keyboard.next();
return count13;
}
} return blob;
}
}
thanks!
Make the variable static and call it from the main method
There are a couple of things wrong in your code, but the biggest one is that you are returning the count when you find a word that has a specific Length.
You may want to create a class (say Document) that has the attributes you listed as variables in WordLengthCount (int count1, int count2, etc). Since attributes should most often be private, I would suggest doing an increment count method.
Finally, your WordLengthCount, can call the increment count method for the right word type, and return the object that you have created.
Moreover, instead of creating 13 variables, I would recommend using an array instead
int[] wordCount= new int[13];
You're trying to access local variables of one function in some other function. This is not possible. As the name suggests, local variables are local to the block or function in which they are declared. If you want to globally access these variables, make them class-level variables, i.e. declare them inside the class body but outside of any other function. Also, if you want to access them from static methods without creating object of the class, make these variables static.
I have a problem where i'm using a joptionpane to get the postal code of a user. I'm trying to check if the format is in L#L#L#L where L is a letter and # is a number. I'm trying to provide error checks to see if the postal code is in that format. I keep getting out of bounds errors if i look for a string that doesn't exist i.e. string.charAt(5) but I don't know how to fix it.
this is the current code that i'm erroring at
String postalCode = JOptionPane.showInputDialog("Enter customer(s) " + (count + 1) + " postal code");
if (Character.isLetter(postalCode.charAt(0)) &&
Character.isDigit(postalCode.charAt(1)) &&
Character.isLetter(postalCode.charAt(2)) &&
Character.isDigit(postalCode.charAt(3)) &&
Character.isLetter(postalCode.charAt(4)) &&
Character.isDigit(postalCode.charAt(5))) {
}
else {
}
There are a couple solutions. One would be to first validate the size of the input:
String postalCode = JOptionPane.showInputDialog("Enter customer(s) " + (count + 1) + " postal code");
if ((postalCode.length() == 7) && Character.isLetter(postalCode.charAt(0)) && Character.isDigit(postalCode.charAt(1)) && Character.isLetter(postalCode.charAt(2)) && Character.isDigit(postalCode.charAt(3)) && Character.isLetter(postalCode.charAt(4)) && Character.isDigit(postalCode.charAt(5))) {
} else {
}
Another would be to use a regular expression:
import java.util.regex.Pattern;
...
String postalCode = JOptionPane.showInputDialog("Enter customer(s) " + (count + 1) + " postal code");
if (Pattern.matches("^[a-zA-Z]\\d[a-zA-Z]\\d[a-zA-Z]\\d[a-zA-Z]$", postalCode)) {
} else {
}
Edit: See deanosaur's comment below for a more concise regex.
I'm wondering how I can use the StringBuilder properly because my current method (http://pastebin.com/VHjM0KeQ) is way too long, I'm sure I can do a loop or a string builder I'm just not sure how to, thanks.
As everything but the case for 0 arguments and for more then 20 arguments is pretty much the same you can easily use a StringBuilder along with a loop to add your words to the text.
Like this:
if (args.length == 0) {
player.sendMessage(ChatColor.DARK_RED + "Usage: /pm <Target> <Message>");
} else if (args.length > 20) {
player.sendMessage(ChatColor.DARK_RED + "Error: Maximum of 20 words.");
} else {
StringBuilder sb = new StringBuilder();
sb.append(ChatColor.DARK_AQUA).append("[PM] ");
sb.append(player.getName() + " > " + targetPlayer.getName());
sb.append(ChatColor.WHITE);
for (final String word : args) {
sb.append(word).append(' ');
}
sb.setLength(sb.length - 1);
targetPlayer.sendMessage(sb.toString());
}
I used a array loop because it just works nicely here. Instead of
for (final String word : args) {
sb.append(word).append(' ');
}
you could also write
for (int i = 0; i < args.length; i++) {
sb.append(args[i]).append(' ');
}
You might understand the second solution a little better.
Your code would slightly improve from using StringBuilders, that's true:
targetPlayer.sendMessage(ChatColor.DARK_AQUA + "[PM] "
+ player.getName() + " > " + targetPlayer.getName()
+ ChatColor.WHITE + " " + args[0])
should be changed to:
targetPlayer.sendMessage(
new StringBuilder()
.append(ChatColor.DARK_AQUA).append("[PM] ")
.append(player.getName()).append(" > ")
.append(targetPlayer.getName()).append(ChatColor.WHITE)
.append(' ').append(args[0]).build());
Note: the compiler does that for you internally, so there won't be much performance gain. However your code will be easier to debug, because the compiled code will be consistent with the source code. Otherwise, when you debug, you will keep jumping inside StringBuilder.append() calls you don't have in your source code.
but the main problem I see with your code is that you should change your many if() clauses to a switch statement:
switch(args.length){
case 0: dosomething(); break;
case 1: doSomethingElse();break;
default: doSomethingEntirelyDifferent();break;
}
Try something like this
if(args.length == 0) {
player.sendMessage(ChatColor.DARK_RED + "Usage: /pm <Target> <Message>");
} else if(args.length > 20 && player.getServer().getPlayer(args[0]) != null){
player.sendMessage(ChatColor.DARK_RED + "Error: Maximum of 20 words.");
} else {
StringBuilder argsConcat= new StringBuilder();
for(int i;i<args.length;i++) {
argsConcat.append(" "+args[i]);
}## Heading ##
targetPlayer.sendMessage(ChatColor.DARK_AQUA + "[PM] " + player.getName() + " > " + targetPlayer.getName() + ChatColor.WHITE + argsConcat.toString());
}