Comparing String with equals - java

String site_inclusion = "0;100";
for (String inc: site_inclusion.split(";")) {
if(!inc.equals(String.valueOf(record.getAttrs().get(new PdsxAttrKey("SiteId")).getValue()))) {
continue;
}
}
And record.getAttrs().get(new PdsxAttrKey("SiteId")).getValue() returns 77
So from my code it should be going to continue block right? But it is not going to continue?
Any suggestions?

I suggest you simplify your code to test what's going on. You might have made a mistake trying to build an example.
String site_inclusion = "0;100";
for (String inc: site_inclusion.split(";")) {
String temp = String.valueOf(record.getAttrs().get(new PdsxAttrKey("SiteId")).getValue());
if(!inc.equals(temp)) {
System.out.println(inc + " != " + temp);
continue;
}
System.out.println(inc + " == " + temp);
}

It would be better for you to check what are the variables (System.out.println/debugging).
The reason why it's not going in that way you think is for sure that condition in if statement.
Try splitting your code into smaller pieces.
String site_inclusion = "0;100";
for(String inc : site_inclusion.split(";")) {
int value = record.getAttrs().get(new PdsxAttrKey("SiteId")).getValue();
System.out.println("Inc = " + inc + " and value = " + value);
if(!inc.equals(String.valueOf(value))) {
System.out.println("continue");
continue;
}
System.out.println(inc + " equals " + value);
}

Related

How to break out of a loop after an input has been checked against every item in an enum Java?

I'm trying to make a program that will allow the user to input either a name or symbol of an element from the periodic table, and will then output some data about that element. So far I've managed to get the user to be able to input either a name or a symbol and have it output correctly, but if the user inputs something wrong then the code doesn't output anything, and will stop accepting an input of a symbol and only accept an input of a name. I would like to know how I would be able to break out of the loop and tell a user that their input is invalid only after the input has been checked against every item in the enum, since my current solution doesn't work. I'm new to Java, so a simple explanation as to how and why would be greatly appreciated.
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) {
int counter = 0;
System.out.println("Enter the name or symbol of an element in the periodic table. ");
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) {
if(counter > Element.values().length) {
System.out.println("That name or symbol is not valid. Please try again. ");
continue outer;
} else {
counter++;
continue;
}
}
}
}
} while (true);
}
}
I would avoid using the valueOf method in a loop. Instead, you can iterate over the elements and for each element check both its name (use the name method) and its symbol.
Scanner reader = new Scanner(System.in);
outer: while (true) {
System.out.println("Enter the name or symbol of an element in the periodic table. ");
String input = reader.nextLine().trim();
for (Element sy : Element.values()) {
if (sy.symbol.equalsIgnoreCase(input) || sy.name().equalsIgnoreCase(input)) {
System.out.println("Element: " + sy + " (" + sy.symbol + ")" + "\nGroup: " + sy.group + "\nAtomic Mass: " + sy.weight);
break outer;
}
}
System.out.println("No such element found. ");
}
reader.close(); // this might be a bad idea
I would also avoid closing the reader, as this will also close System.in and you will be unable to read any more input.
Assuming I understand your question, I would add the logic for parsing Element(s) to Element. You can create Map(s), one to symbol and one of name to corresponding Element instances and then invoke them in whichever order you choose. Like,
private static Map<String, Element> symbolMap = new HashMap<>();
private static Map<String, Element> nameMap = new HashMap<>();
static {
for (Element e : Element.values()) {
symbolMap.put(e.symbol.toUpperCase(), e);
nameMap.put(e.name().toUpperCase(), e);
}
}
public static Element fromString(String token) {
if (symbolMap.containsKey(token.toUpperCase())) {
return symbolMap.get(token.toUpperCase());
}
return nameMap.get(token.toUpperCase());
}
Then in main
Element e = Element.fromString("H");
Element e2 = Element.fromString("Hydrogen");
System.out.println(e == e2); // <-- true
And if e were null then it isn't a valid symbol (or name).
If I have understood correctly, you want to go through the enums and see if any of the symbols match the user input. If not, print a message and try again. You had the right approach, but in the catch block you don't need to make a counter. Instead if we think through the design, you have break outer; if the input ever matches. So the end of the do-while loop will only be reached if there is no matching element. So if we just print a message at the end, this will accomplish our goal:
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) {
continue;
}
}
}
System.out.println("Error. No matching elements. Please try again.");
} while (true);
Sample Output:
Enter the name or symbol of an element in the periodic table.
No
Error. No matching elements. Please try again.
l
Error. No matching elements. Please try again.
He
Element: Helium (He)
Group: Noble Gas
Atomic Mass: 4.003
You complicate the code by mixing the search for the name and the search for the symbol. The search for the name does not need to be inside the for loop:
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter the name or symbol of an element in the periodic table. ");
boolean found = false;
do {
String input = reader.nextLine().trim();
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);
found = true;
} catch (IllegalArgumentException e) {
}
for (Element sy : Element.values()) {
if (sy.symbol.equalsIgnoreCase(input)) {
found = true;
System.out.println("Element: " + sy + " (" + sy.symbol + ")" + "\nGroup: " + sy.group + "\nAtomic Mass: " + sy.weight);
}
}
if (!found)
System.out.println("That name or symbol is not valid. Please try again. ");
} while (!found);
reader.close();
}

Time Complexity of while loop in case of while(boolean)?

I am trying to understand time complexity calculation of a function but i am stuck at this point. Unlike for loop this while loop shown in the code below will depend on the input String length. How to calculate Time complexity for such cases?
The function Does this
Blockquote
Input Data: 4Gopi7Krishna3Msc5India
Output Data: {"4":"Gopi","7":"Krishna","3":"Msc","5":"India"}
Input data and length may vary each and every time.
public static String SplitData(String input) {
try {
String outputJSON = "{";
boolean run = true;
while (run) {
String firstChar = String.valueOf(input.charAt(0));
int length = Integer.parseInt(firstChar);
if (length > 0) {
String data = input.substring(1, (length + 1));
outputJSON = outputJSON + "\"" + String.valueOf(length) + "\":\"" + data + "\"";
if (length + 1 == input.length()) {
run = false;
outputJSON = outputJSON + "}";
System.out.println("TAG " + length + " LENGTH " + length + " DATA " + data + " INPUT " + input);
} else {
outputJSON = outputJSON + ",";
input = input.substring(length + 1, input.length());
System.out.println("TAG " + length + " LENGTH " + length + " DATA " + data + " INPUT " + input);
}
} else //IF INPUT IS NOT VALID MAKE THE RETURN JSON NULL
{
run = false;
outputJSON = "Invalid Input";
}
}
return outputJSON;
} catch (Exception e) {
e.printStackTrace();
return "Invalid Input";
}
}
complexity depends on the number of the possible operations before the execution ends, a for loop wouldn't be faster if you don't change what is done inside.
this function could be much simpler and faster by just using String manipulation functions
public static void main(String args[]){
String s = "4Gopi7Krishna3Msc5India";
String res = "";
String sp[] = s.split("[0-9]+");
res += "{";
for (int i = 0; i<sp.length; i++){
String sss = sp[i];
if(sss.length()==0)
continue;
res += "\""+sss+"\":\""+Integer.toString(sss.length())+"\"" ;
res += (i == (sp.length - 1))?"":",";
}
res+="}";
System.out.println(res);
}

How do I return the string in this for loop?

I have this DieRolling class that we are making for AP Computer Science. This method is supposed to return all the numbers they have rolled in a "neat" manner. Here is the code:
public void printNum()
{
for (int i=0;i<100;i++)
{
System.out.println("Roll " + (i+ 1) + ": " + numbers[i]);
}
}
I need to return the whole for loop, but I cant figure out how.
What should I do?
Thanks!
(This is my first post on here so sorry if it is kind of messed up)
You should declare printNum as a String then result a concatenate of all strings.
public String printNum(final int pToPrint)
{
StringBuilder result = new StringBuilder();
for(int i = 0; i < pToPrint; i++)
result.append("Roll " + (i+ 1) + ": " + numbers[i] + System.lineSeparator());
return result.toString();
}
Then you would call for example System.out.println(printNum(100));
You could simply return the array...
public int[] printNum() {
// ...
return numbers;
}
If you want to format the result, you could use
public String printNum() {
// ...
Arrays.toString(numbers);
}
If you want to customise the format, you could use...
public String printNum() {
StringBuilder sb = new StringBuilder(128);
for (int i=0;i<numbers.length;i++)
{
System.out.println("Roll " + (i+ 1) + ": " + numbers[i]);
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(numbers[i]);
}
return sb.toString();
}
Or if you're using Java 8
public String printNum() {
StringJoiner joiner = new StringJoiner(", ");
for (int i=0;i<numbers.length;i++)
{
System.out.println("Roll " + (i+ 1) + ": " + numbers[i]);
joiner.add(Integer.toString(numbers[i]));
}
return sb.toString();
}
You'll first need to change the return type from void to something reasonable. I suggest that you use either an array of int, since you apparently know that you'll be returning exactly 100 numbers, or an ArrayList<Integer> if that assumption is incorrect, fill up your array or List in the loop, and return it. AGain, you'll need to change the return type to be the type of whatever you decide to return.
Since this is homework, the details should be left to you.
You can return only one time from a function.
So if you want to return all numbers, you can return an array if that numbers.
Just create a String variable String result = ""; and at each loop add numbers to the string. result += "Roll " + (i+ 1) + ": " + numbers[i] + "\n";
Or something. But you for sure need to change your return type. For the above solution it should be String instead of void.

Searching object

I want to search object inside arraylist get value from user input and print it to text area. here is the code.
//the arrayList I declared
Book[]myBook = new Book [30];
int index = 0;
private void searchBtnActionPerformed(java.awt.event.ActionEvent evt) {
String title = titleTF.getText();
boolean found = false;
for (int i = 0; i < index; i++) {
if (myBook[i].getTitle().equals(title));
{
outputTA.append("Book Title : " + myBook[i].getTitle() + "\n");
outputTA.append("Book Author : " + myBook[i].getAuthor() + "\n");
outputTA.append("Year of Publication : " + myBook[i].getYear() + "\n");
outputTA.append("Book Status : " + myBook[i].getStatus() + "\n");
outputTA.append("======================================\n");
found = true;
break;
}
}
if (found == false) {
JOptionPane.showMessageDialog(this, "Book is not Found! Please Try again!");
}
}
The problem is, when I click the search button, it will display the first object in the arraylist. Which line of code is wrong?
First off, your index is 0 so your for doesn't loop. Replace index with myBook.size()

Fill in "secret word" letters

I am doing a hangman project.
I have got most of the code working.
The one part I can't get working is where the "secret word" has more than one letter which is the same. For example "hello" has 2 "l"'s.
This is the code for the part of the code where it replaces the "----" (hello) with the letter that was guessed if the guess was right:
int pos = $Input.indexOf($Guessed);
if (pos == -1)
{
System.out.print("Search string '" + $Guessed + "' not found");
}
else
{
System.out.println("\nSearch string found at " + (pos + 1));
pos = $Input.indexOf($Guessed);
String before = $Display.substring(0, pos);
String after = $Display.substring(pos + $Guessed.length());
System.out.println(before + $Guessed + after);
$Display = before + $Guessed + after;
System.out.println($Display);
$GuessAmt++;
}
I have looked at various answers on here but I cannot get one to work so far.
Obviously if someone guessed "l" then "-----" would change to "--ll-" for (hello).
I am not looking for someone to code this for me as I enjoy a challenge but a bit of a hint would be lovely!!
Obviously from looking at my code you may be able to guess we are not allowed to use arrays yet unfortunately. This is only an intro to Java class really.
Any help would be appreciated.
EDIT: Just to be clear, at the moment it ONLY does the first "l" not both the "l"'s of (hello).
EDIT: Changed to this. However, now it is repeating the "inside if" print statement over and over. Cant see how to fix this!
int pos = $Input.indexOf($Guessed);
if (pos == -1)
{
System.out.print("Search string '" + $Guessed + "' not found");
}
else
{
//System.out.println("\nSearch string found at " + (pos + 1));
for(int i=0;i<$StrLength;i++)
{
System.out.println(i);
if($Input.charAt(i) == $Guessed.charAt(0))
{
i = $Input.indexOf($Guessed);
String before = $Display.substring(0, i);
String after = $Display.substring(i + 1);
System.out.println("inside if" + before + $Guessed + after);
$Display = before + $Guessed + after;
}
}
System.out.println($Display);
$GuessAmt++;
}
If you still wanna use the indexOf you can use its overloaded version as well to insure that you have gone through all letter occurrences:
int index = str.indexOf('l');
while(index >= 0) {
// FILL THE BLANKS WITH THE LETTER
index = str.indexOf('l', index +1);
}
You can iterate over the String and check every character individually using word.charAt(i).
for (int i = 0; i < word.length; i++) {
if (word.charAt(i) == guessedChar) {
// do stuff
}
}

Categories

Resources