The code I am using is below. As far as I am aware the logic of the code is fine but when the return is after the print for the char B then the I within the for loop wont increment. If I remove the return statement then the for loop will increment as I wanted it too, however I need the method to end if the B/W is printed so I need the return to be present. Any help is greatly appreciated I've been trying to work out whats wrong for hours now.
if(currentCodeString.contains("" + currentGuessChar)) {
for (int i = 0; i < codeLength; i++) {
System.out.println("" + i);
//System.out.println(currentGuess[i] + " - " + currentCode[i]);
if(checkPins(currentGuess[i], currentCode[i])) {
System.out.print("B");
return;
}
}
System.out.print("W");
return;
}
Use break instead of return in your for loop.
if(currentCodeString.contains("" + currentGuessChar)) {
for (int i = 0; i < codeLength; i++) {
System.out.println("" + i);
//System.out.println(currentGuess[i] + " - " + currentCode[i]);
if(checkPins(currentGuess[i], currentCode[i])) {
System.out.print("B");
break;
}
}
System.out.print("W");
return;
}
return means - "end method", break means - "end loop"
You should replace the return statement with break after you print "B".
why you doesn’t use "Break" Instead of "Return"?
when the B print , Break it!
the use of return in Thread programming.
This is my solution (without break, which i don't like)
if(currentCodeString.contains("" + currentGuessChar)) {
bool found = false;
for (int i = 0; i < codeLength && !found; i++) {
System.out.println("" + i);
//System.out.println(currentGuess[i] + " - " + currentCode[i]);
if(checkPins(currentGuess[i], currentCode[i])) {
System.out.print("B");
found = true;
}
}
if (!found) {
System.out.print("W");
}
}
Related
I've been writing code that manually prints json (without the json library) after reading a CSV. It's to understand the structure for a project of this scale, which involves IO and Exception handling.
So, I've been debugging this snippet of code since yesterday. I've identified the problem, but have not been able to solve it.
I currently have an infinite loop after the exception message is printed. For context, in the part of the code that is missing, the user inputs the number of files and it creates an array of files. The snippet of code inside my message is a method which verifies if a csv has a an empty field. Count is there to count the line numbers, if count == 1 and there is an empty field, it will throw CSVFileInvalidException, which is a custom exception I made for this project. If count is bigger than 1, it throws CSVDataMissingException, i.e. another custom exception.
The timeline of the debugging goes as follows:
At first, when I had the infinite loop, I thought the regex caused my error, since I heard it could be badly implemented. I checked and each element is exactly what I want (a string, which represents a field in the csv). So, it wasn't regex since the behavior was normal.
Secondly, I realized I accidentally put my try block was inside my while loop, so I put it on the outside. No Luck. The issue still persisted.
Then, I figured out the issue. It read the line handled the exception and since there was no failsafe to exit the while loop, it did so non-stop. So, I added an exit condition for the while loop. So, I added
if ((count > 1) && (s.nextLine() == null || s.nextLine().equals(""))) {
break;
}
This checks if the line number is higher than 1 and if the nextLine is null or empty. I thought this had solved the infinite loop problem that I had. Once I implemented this, nothind after the regex ended up being outputted. I checked with multiple println().
I then realized I made a typo in one of the for loops. Now, I'm back to the same behavior it exhibited earlier. It's redoing the same sequence inside the while loop again. In this case, it's looping the message from CSVFileInvalidException, so i.e. "The file called : " + f[i] + " is invalid. A field is missing. The file is not converted to JSON."
So, I'm assuming there's something that doesn't make sense logically. I've tried multiple solutions and the exceptions are now never reached.
Sorry for the long code, the element that is being repeated is at the bottom, and everything else is inside the while loop, so I'm not sure if it's something I implemented there.
for (int i = 0; i < f.length; i++) {
int count = 1;
try {
while (s.hasNextLine()) {
lines = s.nextLine();
if ((count > 1) && (s.nextLine() == null || s.nextLine().equals(""))) {
break;
}
//isolate the commas, and remove the quotes and extra space, so that the text remains clean and similar
String[] line_parts = lines.replaceAll("^\"", "").split("\"?(,|$)(?=(([^\"]*\"){2})*[^\"]*$) *\"?", -1);
Cloned_Elements[] cloned_elements_array = new Cloned_Elements[line_parts.length];
for (int z = 0; z < cloned_elements_array.length; z++) {
String[] array_ofstring = new String[line_parts.length];
for (int x = 0; x < array_ofstring.length; x++) {
array_ofstring[x] = "lol";
}
cloned_elements_array[z] = new Cloned_Elements(array_ofstring);
}
for (int j = 0; j < line_parts.length - 1; j++) {
if (count == 1) {
if (line_parts[j].equals("") || line_parts[j] == null) {
ce.setCloned_array(line_parts);
throw new CSVFileInvalidException("The file called : " + f[i] + " is invalid. A field is missing. The file is not converted to JSON.");
} else {
if (j < line_parts.length) {
String[] length_1 = cloned_elements_array[j].getCloned_array();
cloned_elements_array[j].setCloned_array(line_parts);
}
}
} else {
if (line_parts[j].equals("") || line_parts[j] == null) {
ce.setCloned_array(line_parts);
throw new CSVDataMissingException("In file " + f[i] + ", there is missing data in line #" + (count) + ". Thus, the file is not converted to JSON.");
} else {
if (j < line_parts.length) {
cloned_elements_array[j].setCloned_array(line_parts);
}
}
}
}
count++;
}
} catch (CSVDataMissingException e2) {
System.err.println(e2.getMessage());
try {
p = new PrintWriter(new FileOutputStream(js[js.length - 1], true));
int line_nb = count+1;
String[] error_array = ce.resize_string_arr();
for (int x = 0; x < error_array.length; x++) {
if (error_array[x].equals("") || error_array[x] == null) {
error_array[x] = "xxx";
}
}
p.println("In file " + f[i] + " ,line " +line_nb + " is missing an element.");
for (int z = 0; z < error_array.length; z++) {
p.print(error_array[z] + " ");
}
p.println();
p.println();
break;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (CSVFileInvalidException e1) {
System.err.println(e1.getMessage());
try {
p = new PrintWriter(new FileOutputStream(js[js.length - 1], true));
p.println("File " + f[i] + " is invalid.");
String[] error_array = ce.resize_string_arr();
for (int x = 0; x < error_array.length; x++) {
if (error_array[x].equals("") || error_array[x] == null) {
error_array[x] = "xxx";
}
}
p.println("Field is missing : " + error_array.length + " detected, 1 is missing.");
for (int z = 0; z < error_array.length; z++) {
p.print(error_array[z] + " ");
}
p.println();
p.println();
break;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
I'm working on my university assignment which requires me to program an eviction algorithm. I am new to programming and have only done Python before. Below is what I have done so far. The code compiles fine but I am not getting the output that I was expected to get.
getting user input and then calling the method for no eviction:
System.out.println();
System.out.println("Cache content: ");
print_array(org_cache, size);
System.out.println("Request sequence: ");
print_array(request, count);
try {
copy_array(org_cache, cache, size);
System.out.println("no_evict");
no_evict(cache, size, request, count);
}
catch (Exception e) {
System.out.println("ERROR: no_evict");
the method:
static void no_evict(int[] cache, int c_size, int[] request, int r_size) {
int i = 0;
boolean found = false;
String result = "";
String resultHit = "";
String resultMiss = "";
for(int x = 0; x < r_size; x++) { //for loop goes through every requests
while(i < c_size || found == false) { //while loop brings a page through every cache value
if(request[x] == cache[i]){
found = true;
} else {
i += 1;
}
}
if(found == true) {
result += "h";
resultHit += "h";
} else {
result += "m";
resultMiss += "m";
x += 1; //proceeds to next value in request sequence
}
}
System.out.println(result);
System.out.println(resultHit.length() + "h " + resultMiss.length() + "m");
}
it does not output the result string but instead outputs this:
Cache content:
20 30 10 5 40
Request sequence:
20 30 10
no_evict
You will notice that your program doesn't actually exit. This is because it's stuck in an infinite loop, just as what would happen in Python.
If you run it in a debugger or hit Ctrl-\ in a console, you'll see that it's stuck in this loop:
while(i < c_size || found == false) { //while loop brings a page through every cache value
if(request[x] == cache[i]){
found = true;
} else {
i += 1;
}
}
The condition is true as long as i < c_size because you used ||, logical "or". You probably intended to use &&, so that find = true will break the loop.
PS: The Java compiler doesn't care about indenting, but humans do. Please use your editor's indenting function to make the code easier to read.
As #that other guy mentioned, you are using || instead of &&.
But you don't need the second qualifier. Just use:
i = 0;
while(i < c_size ) {
if(request[x] == cache[i]){
found = true;
break;
} else {
i += 1;
}
}
or
for ( int i=0; i < c_size; i++ ) {
if ( request[x] < cache[i] ) {
found = true;
break;
}
}
There is another problem with your algorithm: you initialise i right at the beginning but never reset it to zero.
You probably want to move the int i = 0 statement between the for and the while statement.
for (int i = 0; i < pac.length; i++)
{
for (int j=0;j<mem.length;j++)
{
String[] words = mem[j].split(" ");
for (int k = 1; k < words.length; k++)
{
if (words[k].equals(pac[i])
{ //done system.out.println here and it's right
if (!members.containsKey(pac[i])) //won't enter this if correctly
{
members.put(pac[i], " " + words[0]);
}
else
{
String old = members.get(pac[i]);
members.put(pac[i], old + " " + words[0]);
}
}
else
{
members.put(pac[i], "");
}
}
}
}
I need the code to take an array pac which contains a list of organizations and then a list of people's names with their organizations after. I have to put them into a hashmap of members. I cant seem to get it to enter the if statement correctly though. It reaches there correctly. I've used the printing to see what should go into it and that part is correct. Members is an empty hashmap yet all but only one iteration of the loops will go into the first if statement when most should go into it.
use label you can solve your problem. because any one iteration of 2nd loop can empty your member. try this
for (int i = 0; i < pac.length; i++) {
action:
for (int j = 0; j < mem.length; j++) {
String[] words = mem[j].split(" ");
for (int k = 1; k < words.length; k++) {
//System.out.println(words[0] + "ttt");
if (words[k].equals(pac[i])) {
System.out.println(words[k]);
if (!members.containsKey(pac[i]))
{
members.put(pac[i], " " + words[0]);
break action;
} else {
String old = members.get(pac[i]);
members.put(pac[i], old + " " + words[0]);
break action;
}
} else {
members.put(pac[i], "");
}
}
}
}
and use persons as a key for members instead of organization. because a org have more number of persons.
here is the scoop. I have a program that loops through an ArrayList and checks to see if the values are equal to an inputted keyword(inputArray[0])
I want to add a default action incase inputArray[0] is not equal to any of the values inside of the keyList
The else if is where I am having the problem. I want my loop to go through ALL of the values in keyList before it resorts the "last resort" - an else statement. Right now my problem is that in the first if statement it sees that inputArray[0] is not equal to keyList[x] and it goes to the else statement without going through another run of the loop.
As you can see, I tried using an else if statement, where if my loop's counter, x, is larger than the size of keyList then it will do the code inside, but that seemingly does not work. I also added continue;to the else statement to ensure that it is going through the loop, which according to the console, it is. (I know because of the System.out statement at the beginning of the loop.)
public static void wikiInit(ArrayList keyList, ArrayList nameList, ArrayList domainList, ArrayList softwareList, String[] inputArray, EntityPlayer player)
{
System.out.println("These are the current lists:");
System.out.println("Key List: " + keyList);
System.out.println("Name List: " + nameList);
System.out.println("Domain List: " + domainList);
System.out.println("Software List: " + softwareList);
// KEY PARSER
for(int x = 0; x < keyList.size(); x++)
{
System.out.println("Starting the loop");
if((keyList.get(x)).equals(inputArray[0]))
{
//getWikiName = wikiNameArray[x]
//getWikiDomain = wikiDomainArray[x]
//getWikiSoftware = wikiSoftwareArray[x]
StringBuilder hyperlinkBuilder = new StringBuilder();
for(int y = 1; y < inputArray.length; y++)
{
hyperlinkBuilder.append(inputArray[y] + " ");
}
if((softwareList.get(x)).equals("MEDIAWIKI"))
{
String hyperlink = "http://" + domainList.get(x) + "/index.php?search=" + hyperlinkBuilder.toString();
System.out.println("Searching for " + hyperlinkBuilder.toString() + " on the " + nameList.get(x));
player.addChatMessage("Searching for " + hyperlinkBuilder.toString() + " on the " + nameList.get(x));
BrowserHandler.browserInit(hyperlink.replace(" ", "+"), player);
System.out.println("Opening " + hyperlink.replace(" ", "+"));
break;
}
}
else if(x > keyList.size())
{//LAST RESORT
}
else
{
continue;
}
}
}
instead of loop use
if(keyList.contains(inputArray[0])){
int x = keyList.indexOf(inputArray[0]);
StringBuilder hyperlinkBuilder = new StringBuilder();
for(int y = 1; y < inputArray.length; y++)
...
}
else { // last resort code
}
If the default action should only happen after all elements have been checked, it should happen outside the loop. You can do this by using a variable to signal when this happens:
boolean found = false;
for(int x = 0; x < keyList.size(); x++)
{
System.out.println("Starting the loop");
if((keyList.get(x)).equals(inputArray[0]))
{
found = true;
...
}
}
if (!found) {
//The value was never found, do something special.
}
Having said that, in this case it would be much easier to use keyList.contains, as in bellabax's answer.
One way is to simply set a found variable to false before the loop and set it to true inside the loop if you find a key match.
Then after the loop:
if (!found)
complainBitterly();
Try using a boolean. Set it to false before the for loop, and if inputArray[0] is equal to keyList[x], set the boolean to true (in your if statement).
Then have an if statement after the for loop that will do your last case resort if the bool is still false.
The good news is you can make this a lot simpler by making 2 changes.
First, extract those 4 separate lists that you reference and combine them as a list of objects with fields for each list, 'ParameterTuplein the code. Second, you can track loop exit status with another variable,foundMediaWikiKey` in the code.
/**
* Not sure of a better name for this class, you'll need to look at in the larger sense.
* Also, in production you probably want to use getters for these, rather than final
* public and the constructor
*/
public class ParameterTuple {
public ParameterTuple(String key, String name, String domain, String software) {
this.key = key;
this.name = name;
this.domain = domain;
this.software = software;
}
public final String key;
public final String name;
public final String domain;
public final String software;
}
public static void wikiInit(ArrayList<ParameterTuple> paramList, String[] inputArray, EntityPlayer player) {
System.out.println("These are the current lists:");
System.out.println("List: " + paramList);
// Variable to keep track of how we exited the loop.
boolean foundMediaWikiKey = false;
// KEY PARSER
for(ParameterTuple param : paramList)
{
System.out.println("Starting the loop");
if(param.key.equals(inputArray[0])) {
StringBuilder hyperlinkBuilder = new StringBuilder();
for(int y = 1; y < inputArray.length; y++) {
hyperlinkBuilder.append(inputArray[y] + " ");
}
if(param.software.equals("MEDIAWIKI")) {
String hyperlink = "http://" + param.domain + "/index.php?search=" + hyperlinkBuilder.toString();
System.out.println("Searching for " + hyperlinkBuilder.toString() + " on the " + param.name;
player.addChatMessage("Searching for " + hyperlinkBuilder.toString() + " on the " + param.name;
BrowserHandler.browserInit(hyperlink.replace(" ", "+"), player);
System.out.println("Opening " + hyperlink.replace(" ", "+"));
// Keep track of how we exited the loop
foundMediaWikiKey = true;
break;
}
}
}
// When we exit, check to see how we did so.
if (!foundMediaWikiKey) {
// Last Resort
}
}
We usually do it like this where we search first and then put the code to handle the found one later.
I also lifted the one part out of the loop, since it didn't need to be in there. It could also go down in the "found" part of the code but I liked getting it out of the way to make the code more readable.
Also, the test for MEDIAWIKI is left in the loop (unlike my earlier version of this). Thanks to #paxdiablo for that. It is also a failing of some other answers here (as of right now).
StringBuilder hyperlinkBuilder = new StringBuilder(); // lift this out of the loop
for(int y = 1; y < inputArray.length; y++) {
hyperlinkBuilder.append(inputArray[y] + " ");
}
int found = -1;
for(int x = 0; x < keyList.size(); x++)
{
System.out.println("Starting the inside of the loop");
if((keyList.get(x)).equals(inputArray[0])) {
if((softwareList.get(x)).equals("MEDIAWIKI"))
found = x;
break;
}
}
}
if (found >= 0) {
int x = found;
//getWikiName = wikiNameArray[x]
//getWikiDomain = wikiDomainArray[x]
//getWikiSoftware = wikiSoftwareArray[x]
String hyperlink = "http://" + domainList.get(x) + "/index.php?search=" + hyperlinkBuilder.toString();
System.out.println("Searching for " + hyperlinkBuilder.toString() + " on the " + nameList.get(x));
player.addChatMessage("Searching for " + hyperlinkBuilder.toString() + " on the " + nameList.get(x));
BrowserHandler.browserInit(hyperlink.replace(" ", "+"), player);
System.out.println("Opening " + hyperlink.replace(" ", "+"));
} else {
//LAST RESORT ... fill in 'not found' code
}
I want my loop to go through ALL of the values in keyList before it
resorts the "last resort" - an else statement
else if(some condition)
{
if(x!=keylist.size()-1) // USE IT HERE
{ continue; }
//LAST RESORT
}
I'm making a cryptography/cryptanalysis program using java as a homework for my master. Anyway, i use a method to delete the uselless whitespaces and make the String i display to the JTextArea proper. This method is great for small texts but it gives me a StringIndexOutOfBoundsException when i use bigger texts (loaded from a .txt file). Can anyone help?
Thanks in advance.
This is the method:
public void Data(String s) {
System.out.print("Analysis" + "\n" + s);
jTextArea1.setText(s);
StringBuilder buf = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (!Character.isWhitespace(s.charAt(i))) {
buf.append(s.charAt(i));
} else if (Character.isWhitespace(s.charAt(i)) && !Character.isWhitespace(s.charAt(i + 1))) {
buf.append(s.charAt(i));
}
}
System.out.println(buf.toString() + "\n" + "from buf");
jTextArea1.setText(buf.toString());
}
You are going up to s.length() in the for loop but accessing s.charAt(i + 1) in the second if statement. Try to only go up to s.length() - 1:
for (int i = 0; i < s.length() - 1; i++) {
if (!Character.isWhitespace(s.charAt(i))) {
buf.append(s.charAt(i));
} else if (Character.isWhitespace(s.charAt(i)) && !Character.isWhitespace(s.charAt(i + 1))) {
buf.append(s.charAt(i));
}
}
And then check the last character afterwards.
s.charAt(i + 1) in !Character.isWhitespace(s.charAt(i + 1))
It fails when i == s.length() - 1
You might want to use s.replaceAll("\\s\\s+"," ") instead of reinventing the wheel.
You are using this statement
Character.isWhitespace(s.charAt(i + 1)
meaning you are accessing an character of your string length plus 1.
hi i hope you can use the below one, instead the above
//StringBuilder buf = new StringBuilder();
/* These lines are not needed
for (int i = 0; i < s.length(); i++) {
if (!Character.isWhitespace(s.charAt(i))) {
buf.append(s.charAt(i));
} else if (Character.isWhitespace(s.charAt(i)) && !Character.isWhitespace(s.charAt(i + 1))) {
buf.append(s.charAt(i));
}`enter code here`
}
*/
s = s.replaceAll("\\s+"," ");
// Whenever you print the object(reference) toString() method is called by default. so no need to call explicitly
// System.out.println(buf.toString() + "\n" + "from s");
System.out.println(s + "\n" + "from buf");
// jTextArea1.setText(s);
jTextArea1.setText(s);