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.
Related
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);
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 = "";
...
I have an array it has (id,name,salary)
I want to search specific ID using Employee search method, my code is:
Employee SearchID(int i_d) {
for (int i = 0; i < staff.length; i++) {
boolean check = true;
if (staff[i].id == i_d) {
System.out.println("Id: " + staff[i].id + ", name: " + staff[i].name + " and salary: " + staff[i].salary);
} else {
System.out.println("Sorry, no record exists with record id = " + i_d);
}
}
return staff[i].id;
}
Your SearchID method returns an Employee object but you return a primitive type. (staff[i].id) You must change return type of your method.
You can fix your method like this:
Employee SearchID(int i_d) {
for (int i = 0; i < staff.length; i++) {
if (staff[i].id == i_d) {
System.out.println("Id: " + staff[i].id + ", name: " + staff[i].name + " and salary: " + staff[i].salary);
return staff[i];
}
}
System.out.println("Sorry, no record exists with record id = " + i_d);
return null;
}
And, of course, you need to handle the null result after calling SearchID properly.
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.
I am having trouble looping through all of my questions that have been assigned to each oracle's queue. All of the questions are being added successfully, but I cannot for the life of me have each oracle answer each questions that it has been assigned 1 by 1. Meaning that oracle 1 answers its first question, oracle 2 answers its first questions and so on, until all queues are empty and all questions have been answered.
/*
* Name: James Combs
* Course: 3345 Data Structures and Algorithms
* Description:
* This program assigns array queues to a number of oracles and loops through them in a
* round robin fashion, answering each question the oracle as in its queue.
*/
package OracleQueues;
import java.util.Iterator;
import java.util.Random;
public class Executor
{
public static void addQuestions (String[] questions, ArrayQueue[] oracles, int numOracles)
{
// Put the questions into a random oracles queue
for (int i = 0; i < questions.length; i++)
{
try
{
int rand = Utility.random(numOracles);
if (oracles[rand] == null)
{
System.out.println("Oracle " + (rand + 1) + " does not have a queue");
ArrayQueue queue = new ArrayQueue();
oracles[rand] = queue;
oracles[rand].enqueue(questions[i]);
System.out.println("Oracle " + (rand + 1) + " has added question ----(" + (i + 1) + ")" + questions[i] + "---- to its queue");
}
else
{
oracles[rand].enqueue(questions[i]);
System.out.println("Oracle " + (rand + 1) + " has added question ---- (" + (i + 1) + ")" + questions[i] + "---- to its queue");
}
}
catch (IllegalStateException e)
{
// advance to next oracle if this oracles queue is full, until questions have all been assigned.
System.out.println("This oracles queue is full, advancing to the next one...");
continue;
}
}
}
public static void main(String[] args)
{
Utility.init(); // initializes file readers
String[] questions = Utility.readQuestions(); // reads question.txt file into questions array
String[] answers = Utility.readAnswers(); // reads answers.txt file into answers array
int oCount = 0, qCount = 0;
int numOracles = answers.length; // finds the number of oracles
ArrayQueue[] oracles = new ArrayQueue[numOracles]; // initialize the number of oracles based on number of answers in the file
// 10 oracles
addQuestions(questions, oracles, numOracles);
System.out.println("\n\n");
// Loop through the oracles, having each one remove a question from its queue (if empty do nothing) and answer it with its unique answer (oracle[k] uses answers[k]). Do this repeatedly till all queues become empty.
// Create a list to hold the oracles
for(String q : questions)
{
if (oCount == 10)
{
oCount = 0;
}
if (oracles[oCount] == null || oracles[oCount].isEmpty())
{
continue;
}
String output = oracles[oCount].dequeue();
System.out.println("Oracle # " + (oCount + 1) + " ---- " + output + " ----> " + answers[oCount]);
oCount++;
}
/*for (int i = 0; i < questions.length; i++)
{
System.out.println("Answering question " + (i + 1) + "...");
for (int j = 0; j < numOracles; j++)
{
// if queue is empty or doesnt have one, then continue
if (oracles[j] == null || oracles[j].isEmpty())
{
continue;
}
// otherwise, dequeue and display question and corresponding answer
String output = oracles[j].dequeue();
System.out.println("Oracle # (" + (j + 1) + ") --- " + output + " ----> " + answers[j] + "\n");
}*/
}
}
Questions has ben solved after lots of thought. Something was slightly wrong with my ArrayQueue class