Using a for loop to search an array - java

for (int i = 0; i < str.length(); i ++) // Checks every position of array
{
arr[i] = str.charAt(i); // Ignore this, not needed
if (arr[i] != ',' || arr[i] != '.' || arr[i] != '$') // Checks every position of array to see if any character equals a comma, decimal point, or a dollar sign
{
// Ignore below
/*
valueString = String.valueOf(value);
numOfAsterisks = arr.length - valueString.length();
for (int asterisk = 0; asterisk <= numOfAsterisks; asterisk ++)
{
System.out.print("*");
}
System.out.println((int)value);
*/
}
}
Here, what I want to do is to check an array of characters and see if the array contains a comma, a decimal point, or a dollar sign. If the array does not contain any of these characters, then the commented-out portion (where it says "Ignore below") will be executed. The only problem I have here is that because if (arr[i] != ',' || arr[i] != '.' || arr[i] != '$') is under the outside for loop, the commented-out part is executed multiple times. I need the code to execute only once, but still check each position of the array.

If I understand your question correctly, what you actually want is something like this:
boolean found = false;
for(int i = 0; i < str.length; i++) {
char c = str.charAt(i);
if(c == ',' || c == '.' || c == '$') {
found = true;
break;
}
}
if(!found) {
/* Your commented-out code */
}
Note that this can also be formulated as such:
skip: {
for(int i = 0; i < str.length; i++) {
char c = str.charAt(i);
if(c == ',' || c == '.' || c == '$')
break skip;
}
/* Your commented out code goes here. */
}
Choose for yourself which you like more. :)

Related

Extract data inside parenthesis except being enclosed by semicolon

Want to extract data inside parenthesis. But if those parenthesis are inside between single quotes. Then it should be neglected. Using regular expression.
Input:
XCA(AA+BB)AA(AD'A(CC)B')
Expected Output:
AA+BB
AD'A(CC)B'
String in="XCA(AA+BB)AA(CC)AD'(CC)'XCA(AA+BB)";
String result="";
boolean x=false;
for (int i = 0; i < in.length(); i++){
char ch = in.charAt(i);
String part = String.valueOf(ch);
int number = 0;
if (ch == '\'' ) {
part = "";
number++;
for (int j = i + 1; j < in.length(); j++) {
char d = in.charAt(j);
if (d == '\'') {
number++;
}
if (d == '\'') {
number--;
i = j;
if (number == 0) {
break;
}
}
part += d;
}
}
if (ch == '(' ) {
part = "";
number++;
for (int j = i + 1; j < in.length(); j++) {
char d = in.charAt(j);
if (d == '(') {
number++;
}
if (d == ')') {
number--;
i = j;
if (number == 0) {
break;
}
}
part += d;
}
System.out.println(part);
}
result += part;
}
\(
(
(
[^\(\)]+|
'\(|
\)'
)+
)
\)
It consists of three main parts.
[^\(\)]+ Anything that is not an parenthesis
' \( an escaped open parenthesis '(
\)' an escaped closing parenthesis )'
All enclosed in a matching parenthesis literals then an outer group (group 1) without repetition and an inner group with repetition.
The matches in group 1 are
AA+BB
AD'(CC)'

StringIndexOutofBoundsException Error when inputing an empty String Java [duplicate]

This question already has answers here:
Java charAt() String index out of range: 0
(5 answers)
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
Hi I keep getting this error whenever I try to input an empty String. Everything else so far works and if I put a space inside the String it works. I know this is really picky but I'm super curious what I should do in this situation to make sure it returns just an empty String.
**> HW2.nthWord(2,"")
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at HW2.nthWord(HW2.java:124)**
I did create a special instance for when this value is put in but it still does not work.
What do I need to to correct this?
/*nthWord takes an int and a String as input and returns a String:
The input int represents a number n that is assumed to be positive, and the output string
contains every nth word of the input string, starting with the first word, separated by a single space.
For this method, a word is defined to be a sequence of non-space characters.
There should be no space at the end of the output string.
*/
public static String nthWord( int number, String input ){
StringBuilder create = new StringBuilder();
int totalspaces = 0; //This is to hold a count of the number of spaces in a String
if( number == 0){
return input;
}
if(input == ""){
return input;
}
else{
for(int i = 0; input.charAt(i) != ' '; i = i + 1){
create.append(input.charAt(i));
}
for( int i = 0; i < input.length() - 1 ; i = i + 1){
if(input.charAt(i) == ' ' && i < input.length() - 1 && input.charAt(i+1) != ' '){
if( i != input.length()-1 && input.charAt(i+1) != ' '){
totalspaces = totalspaces + 1;
}
if(totalspaces % number == 0 && totalspaces != 0){
create.append(' ');
for(int j = i+1; input.charAt(j) != ' ' && j < input.length(); j = j+1){
create.append(input.charAt(j));
i = j;
}
}
}
}
return create.toString();
}
}
I noticed a few things
for(int i = 0; input.charAt(i) != ' '; i = i + 1){
create.append(input.charAt(i));
}
This loops will keep adding characters of "input" until it reaches a space' ' character. If input does not have a space character then this loop will go beyond the length of input and cause the error. You may want something like:
for(int i = 0; i < input.length(); i = i + 1){
if(input.charAt(i) == ' ' ){
break;
} else {
create.append(input.charAt(i));
}
}
Also, when you get to the line:
if(input.charAt(i) == ' ' && i < input.length() - 1 && input.charAt(i+1) != ' '){
you already know that i < input.length() - 1 because you are in a for loop. You may change that line to:
if(input.charAt(i) == ' ' && input.charAt(i+1) != ' '){
For the same reason, your next section:
if( i != input.length()-1 && input.charAt(i+1) != ' '){
totalspaces = totalspaces + 1;
}
can be changed to
if( i != input.length()-1 ){
totalspaces = totalspaces + 1;
}
Also, I noticed that you may be making the problem harder than it needs to be. The problem will be much easier if you solve it in a single for-loop.
for(int i = 0; i < input.length(); i = i + 1){
if( x ) //x is some code that determines if you are part of the nth word
create.append(input.charAt(i));
}

How do I check if a position in my vector of vectors is out of bounds?

I have a vector of vectors filled with characters from a text file. It is essentially a simple outbreak simulator, with 'i' characters being infected, and 's' characters being susceptible to infection. The point is to run through the matrix and if it comes across an 'i', it then changes all 's' around it into an 'i'. I run into a problem when checking the elements around it due to checking positions out of the bounds on the edges of the matrix. Is there a way to check these bounds in my if statements?
Here is the code:
for (int i = 0; i < population.size(); i++) {
for(int j = 0; j < population[i].size(); j++) {
if(population[i][j] == 'i') {
if(population[i-1][j] == 's') {
population[i-1][j] = 'i';
}
if(population[i-1][j+1] == 's') {
population[i-1][j+1] = 'i';
}
if(population[i][j+1] == 's') {
population[i][j+1] = 'i';
}
if(population[i+1][j+1] == 's') {
population[i+1][j+1] = 'i';
}
if(population[i+1][j] == 's') {
population[i+1][j] = 'i';
}
if(population[i+1][j-1] == 's') {
population[i+1][j-1] = 'i';
}
if(population[i][j-1] == 's') {
population[i][j-1] = 'i';
}
}
}
}
Instead of directly referencing a particular array entry, you could do something like the following:
void checkForInfectionAndInfectIfNeeded(int i, int j) {
for (int row = -1; row <= 1; row++) {
for (int column = -1; column <=1; column++) {
infect(i + row, j + column);
}
}
}
void infect(int i, int j) {
if (i < 0 || i >= population.size() || j < 0 || j >= population[j].size()) {
return;
} else {
population[i][j] = 'i';
}
}
This way, the infect method is the only that checks the boundaries, and you replace your long list of manually checking the surrounding locations with two loops.

Java- getting wrong output

Here's my code that I've written :
public String binary(String s)
{
String[] a = {
"0000","0001","0010","0011","0100","0101","0110","0111",
"1000","1001","1010","1011","1100","1101","1110","1111"
};
String k = "";
for(int i = 0; i <= s.length() - 1; i++)
{
if (s.charAt(i) == 'a') { k += a[10]; }
else if (s.charAt(i) == 'b') { k += a[11]; }
else if (s.charAt(i) == 'c') { k += a[12]; }
else if (s.charAt(i) == 'd') { k += a[13]; }
else if (s.charAt(i) == 'e') { k += a[14]; }
else if (s.charAt(i) == 'f') { k += a[15]; }
else { k += a[i]; }
}
return k;
}
I am getting output as a[0-9] = 0000. How can I fix this? What am I doing wrong?
The problem is with use of a[i]. It is a logical error. Because i is loop variable which indicates the current index in s String. But you are using it to indexing it in variable a. So, i variable is use incorrectly here.
Following is corrected (and a bit optimized) code. See it working here:
public class HexaDecimal
{
public String binary(String s)
{
String[] a= {"0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"};
String k="";
for(int i=0;i<s.length();i++)
{
char ch = Character.toUpperCase(s.charAt(i));
if(ch>='A' && ch <= 'F') k+= a[ch - 'A' + 10];
else k+= a[ch - '0'];
}
return k;
}
}
Replace k+=a[i]; with k+=a[s.charAt(i) - '0'];
You're using your string index loop variable as an index into a rather than the character at that location in the string.
You need to do - '0' to convert from unicode codepoint to the value it represents as an ASCII digit (which I assume you want to use here)
Your last else does the incorrect calculation. It does not take into consideration what is inputted, only the position. You want it to be
else {
k += a[s.charAt(i) - '0'];
}
There are easier ways to get the binary representation of hexadecimals, and you probably also want to check the input that it does not contain anything else than 0-9 or a-f.
You can change the for loop to this:
for(int i=0; i < s.length(); i++)
{
char c = s.charAt(i);
if (c >= '0' && c <= '9') k += a[c - '0'];
else if (c >= 'a' && c <= 'f') k += a[c - 'a' + 10];
else if (c >= 'A' && c <= 'F') k += a[c - 'A' + 10];
else throw new InvalidArgumentException(s);
}
This is a lot simpler and self-explanatory, at least in my opinion. Handles digits, uppercase and lowercase letters, and fails in an expected way on bad input.

Binary to Decimal - java

I want to write a program which receive a string value and print the decimal number.
In addition, if the string value is not 1 or 0, I need to print a message.
I wrote this code but it is always getting inside the if command.
I Would appreciate your support!
Thank you
import java.util.Random;
public class Decimal {
public static void main(String[] args) {
String input = (args[0]);
int sum = 0;
for (int i = 0; i <= input.length(); i++) {
if (!(input.charAt(i) == '0') || (input.charAt(i) == '1')) {
System.out.println("wrong string");
break;
}
char a = input.charAt(i);
if (a == '1') {
sum |= 0x01;
}
sum <<= 1;
sum >>= 1;
System.out.println(sum);
}
}
}
The ! (not) operator of the if statement only applies to the first part:
if ( ! (input.charAt(i) == '0')
||
(input.charAt(i) == '1')
) {
So that is the same as:
if ((input.charAt(i) != '0') || (input.charAt(i) == '1')) {
When you actually meant to do:
if (input.charAt(i) != '0' && input.charAt(i) != '1') {
It's a good thing though, because once that works, you're going to get an IndexOutOfBoundsException when i == input.length(). Change the loop to:
for (int i = 0; i < input.length(); i++) {
And for performance, move variable a up and use it in that first if statement. Rename to c or ch is more descriptive/common.
Doing both sum <<= 1 and sum >>= 1 leaves you where you started. Is that what you wanted? You should also do the left-shift before setting the right-most bit.
Applying all that, I believe you meant to do this:
String input = args[0];
int sum = 0;
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c != '0' && c != '1') {
System.out.println("wrong string");
break;
}
sum <<= 1;
if (c == '1')
sum |= 1;
}
System.out.println(sum);

Categories