Java For Loop repeat if value is more - java

I am taking characters from a string and its values are added still I am getting a particular value.. suppose my value to get is 50 .. i need to take character each from a string and add its values
for example the value I need to get is 10
and value for letters a=1,b=2,c-3;
and the string is abca so its total value is 1+2+3+1 = 7
so 10 didn't reached so I need to add once agin from start like abca 7 + 1 + 2. So at the place of b we got the 10 value.. so the result is 2.
I know how to take the value for once but the second time calculation an dthird time I am not getting if anyone can help..pls help
The code so far I completed..
long currentValueFN = 0;
long value = 0;
char[] currentFN = new char[text.length()];
currentFN = text.toCharArray();
Long l = Long.parseLong(String.valueOf(currentAge));
for(int i=0; i<text.length(); i++)
{
currentValueFN += valueLetters( currentFN[i] );
if(currentValueFN >= l)
{
value = valueLetters( currentFN[i] );
}
}
return value;

long currentValueFN = 0;
long value = 0;
char[] currentFN = new char[text.length()];
currentFN = text.toCharArray();
Long l = Long.parseLong(String.valueOf(currentAge));
while(currentValueFN < l ) //check if current value is enough
{
for(int i=0; i<text.length(); i++)
{
currentValueFN += valueLetters( currentFN[i] );
if(currentValueFN >= l)
{
value = valueLetters( currentFN[i] );
break;
}
}
}
return value;
1) if there are enough characters in "text": will escape from for by break and then from while by expression;
2) if there aren't enough characters in "text": will finish for and start it again by while expression. until 1)

please forgive me if my answer is wrong.
1)I have taken a string variable called "variable" and converted it to character array called "character_array"(array name).
2)Then i converted the character array elements to its equivalent ascii code and it is stored in an integer array called "value_array"(array name).
3)Then i checked the condition that the givenvalue is less than the addedvalue.
public class Stack {
public static void main(String args[])
{
long addedvalue=0;
long requiredvalue=600;
String variable="ravi";
char characterarray[]=new char[variable.length()];
for(int i=0;i<variable.length();i++)
{
characterarray[i]=variable.charAt(i);
System.out.println(characterarray[i]);
}
int valuearray[]=new int[variable.length()];
for(int j=0;j<variable.length();j++)
{
valuearray[j]=(int)(variable.charAt(j));
System.out.println(valuearray[j]);
}
while(addedvalue<=requiredvalue)
{
for(int j=0;j<variable.length();j++)
{
valuearray[j]=(int)(variable.charAt(j));
if(addedvalue>=requiredvalue)
break;
addedvalue=addedvalue+valuearray[j];
System.out.println(j);
}
}
}
}

This should help you.
currentValueFN =0;
a=0;
while(currentValueFN !=l){
a=valueLetters( currentFN[i] );
currentValueFN +=a;
if(currentValueFN >= l)
{
value = a;
break;
}
}
return value;

Related

index out of range error in character array

Please I am practiceing some java questions. I am trying to return a non repeating character in an integer. I have written my code and it works for some strings but some are bringing out index out of range error. I do no know where I have done something wrong
Here is my code:
class Challenge {
static final int n = 256;
static char[] count = new char[n];
String str;
static void charCounter( String str ) {
for(int i = 0; i < str.length(); i++){
count[str.charAt(i)]++;
}
}
public static String firstNonRepeatingLetter( String str ) {
charCounter(str);
int pos = -1, i;
for(i = 0; i < str.length(); i++){
if(count[str.charAt(i)] == 1){
pos = i;
break;
}
}
return Character.toString(str.charAt(pos));
}
}
You haven't considered what will happen in the case where all letters repeat, for example the string "ABBA".
You haven't specified full what the method is supposed to do in this case, but if returning an empty string is acceptable, you can change the return statement to:
if (pos < 0) return "";
return Character.toString(str.charAt(pos));
if(count[str.charAt(i)] == 1){
pos = i;
break;
}
If your input String do not satisfies count[str.charAt(i)] == 1. Then the pos value would remains -1 -> it would cause the error at return statement

Looping through two separate if statements

The code below is a simplified version of a method I am working on for a java project. The method will sort through a list of items(two different categories), in this case 0,s and 1's. The code reads through an array of numbers stops at either 0 or 1 and then prints out both the 0 or one and the string of numbers following the 0 or 1. If a preceding string is a 1 or a zero then it will stop and switch to another if statement. However it only executes each statement once. However there is more in the array that it needs to read through and organize. I would like to set up some sort of loop so that it loops through the set of if statements until it has read through the entire array.
public class tester
{
public static void main(String[] args )
{
String flags[] = {"0","23","25","34","1","9","12","13","0","67","2","43"};
String array[] = new String[flags.length];
String zeros [] = new String[array.length];
String ones[] = new String[array.length];
int i,j,k,h;
int count = 0;
for (i = 0; i<flags.length; i++)
{
if (flags[i].equals("0"))
{
for (j=0; !flags[j].equals("1") ; j++)
{
count = j+1;
array[j] = flags[j];
zeros[j] = flags[j];
}
} else
if (flags[count].equals("1"))
{
j = 0;
for(k=count; !flags[k].equals("0");k++)
{
array[k] = flags[k];
j++;
ones[j-1] = flags[k];
}
}
}
for(i=0; i<zeros.length; i++)
{System.out.println(zeros[i]);}
System.out.println();
for(i=0; i<ones.length; i++)
{System.out.println(ones[i]);}
}
}
What it prints out now:
0
23
25
34
null
null
null
null
null
null
null
null
1
9
12
13
null
null
null
null
null
null
null
null
String flags[] = {"9","0","23","25","34","1","9","12","13","0","67","2","43"};
String array[] = new String[flags.length];
String zeros [] = new String[array.length];
String ones[] = new String[array.length];
int i;
boolean addingZeroes = false;
boolean addingOnes = false;
int zeroCount = 0;
int onesCount = 0;
for (i = 0; i<flags.length; i++) {
if (flags[i].equals("0")) {
zeros[zeroCount] = flags[i];
zeroCount++;
addingZeroes = true;
addingOnes = false;
} else if (flags[i].equals("1")) {
ones[onesCount] = flags[i];
onesCount++;
addingZeroes = false;
addingOnes = true;
} else if (addingZeroes) {
zeros[zeroCount] = flags[i];
zeroCount++;
} else if (addingOnes) {
ones[onesCount] = flags[i];
onesCount++;
}
}
for(i=0; i<zeroCount; i++) {
System.out.println(zeros[i]);
}
System.out.println();
for(i=0; i<onesCount; i++) {
System.out.println(ones[i]);
}
Hey, couple things were wrong. Basically, you need a little state machine where you need to know whether you are in the midst of storing the sequence after a 1 or a 0. I used the boolean values (eg addingZeroes) for that.
Then, you need to separately keep track of your element count (eg zeroCount) for each of the storage arrays. You might have 20 digits after a 0 and just 2 after a 1.
Finally, at the end, your length of your storage arrays is not what you want - you want the amount of values you ended up storing. That's why you got all those "nulls".
One other thing I noticed is that your j value is initialized always to 0 in the 0 block, so you would always be using the lowest values of the start array.

Java: parse string to int and compute the sum

First off I want to start by saying I'm not just looking for someone to give me the answer to this problem, I am a beginner programmer and am just trying to learn as much as possible. A critique of my code and a friendly nudge in the right direction would be most appreciated! What is really confusing me is my stringParser method. I use this method to loop through the string, picking out the numbers and storing them in a new string to be parsed. What confuses me is how I would be able to add these numbers together? Here is the code:
public static int stringParser(String parsee,int parsed)
{
int indexOfString = parsee.indexOf("="); //Searches for an = sign since there has to be one
String parsee2 = "";
int [] newArray;
String subStringParse = parsee.substring(0,indexOfString); //Substring made to divide string, this one is from 0 index to 1st occurence of =
for(int i = 0;i<subStringParse.length();i++)
{
if(Character.isDigit(subStringParse.charAt(i))) //if the value is a number it is stored in a new string then parsed.
{
parsee2+= subStringParse.charAt(i);
parsed = Integer.parseInt(parsee2);
}
} return parsed;
}
public static int sumInts(int a,int storedSums)
{
//a = new int[20];
for(int i=0;i<a;i++) //loops through parsed string from stringParser
{
storedSums += a; //creates a new value calculating sum
}
return storedSums;
}
As per my guess, you want to parse something like this `12 + 34 = '.
If I'm right, then your for loop is completely wrong. It will return only 34 as integer value. You can debug your code for that.
I suggest you something like this :
int index = 0;
for(int i = 0;i<subStringParse.length();i++)
{
if(Character.isDigit(subStringParse.charAt(i))) //if the value is a number it is stored in a new string then parsed.
{
parsee2+= subStringParse.charAt(i);
parsed = Integer.parseInt(parsee2);
}
newArray[index++] = parsed; //make sure you initialize newArray.
}
return newArray;
Try,
String parsee = "12+13 = 34+45 = 45+-45";
int value = 0;
String parsed = "";
for(String exp : parsee.split("=")){
for(String val : exp.trim().split("\\+")){
value+=Integer.parseInt(val);
}
parsed+=" SUM = "+value;
value = 0;
}
System.out.println(parsed);
Output
SUM = 25 SUM = 79 SUM = 0

Count Character Consecutively in Java

I'm trying to write a method that returns the number of times char c first appears consecutively in s, even if it's a single occurrence of the character. Even spaces break the consecutive count. So the string "I'm bad at programming." should only return 1, if char c was 'a'.
The code below compiles but doesn't print the correct answers. Just something to show my general logic when it comes to approaching this problem.
public class WordCount
{
public int countRun( String s, char c )
{
int counter = 0;
for( int i = 0; i < s.length(); i++)
/*There should be other conditions here that checks for first
appearance consecutively. I've tried my fair share, but no
luck on getting correct results.*/
{
if( s.charAt(i) == c )
{
counter += 1;
}
}
return counter;
}
public static void main( String args[] )
{
WordCount x = new WordCount();
System.out.println( x.countRun( "Add dog", 'd' ) ); //should return 2
System.out.println( x.countRun( "Add dog", 'D' ) ); //should return 0
System.out.println( x.countRun( "Hope you're happy", 'p' )); //should return 1
System.out.println( x.countRun( "CCCCCcccC", 'C' )); //should return 5
}
}
I just need a few pointers (logic-wise or code). Maybe there's a method for Strings that I've never seen before that could make my program much simpler. I have very limited knowledge in programming and in Java.
EDIT: For anyone wondering if this is part of some homework assignment or whatnot, this was a question from a very old midterm. I got it wrong but for some reason but never bothered to ask for the correct answer at the time. I looked at it today and wanted to see if I knew the answer. Looks like I don't.
You could do it in one line:
int result = s.replaceFirst(".*?(" + c + "+).*", "$1").length();
This code uses regex to essentially extract the part of s that is the first contiguous occurrences of c, then gets the length of that.
This will also work for no occurrences, yielding zero.
See live demo.
Add a flag, and break out of the loop when you have found one matching character, then find "anything else". Maybe not the most compact or elegant, but true to the original code. Tested, and produces 2,0,1,5 as expected.
public int countRun( String s, char c )
{
int counter = 0;
boolean foundOne = false;
for( int i = 0; i < s.length(); i++)
{
if( s.charAt(i) == c )
{
counter += 1;
foundOne = true;
}
else {
if(foundOne) break;
}
}
return counter;
}
It occurs to me that counter>0 is an equivalent condition to foundOne==true; that would allow you to simplify the code to:
public int countRun( String s, char c )
{
int counter = 0;
for( int i = 0; i < s.length(); i++)
{
if( s.charAt(i) == c ) counter++;
else if(counter>0) break;
}
return counter;
}
The logic is a tiny bit harder to follow this way, as the variable name foundOne is self-documenting. But per other posts, "small is beautiful" too...
Using assci array counter
public static int countRun(String s, char c) {
int[] counts = new int[256];
int count = 0;
char currChar;
for (int i = 0; i < s.length(); i++) {
currChar = s.charAt(i);
if (currChar == c) {// match
counts[c]++;
} else if (Character.isSpaceChar(currChar)) {
counts[c] = 0;// reset counter for c
} else {// no match
if (counts[c] > 0) {// return accumulated counts if you have
count = counts[c];
return count;
}
}
}
return count;
}
public class A3B2C1 {
public static void main(String[] args) {
String s = "AAABBC";
s = s + '#';//dummy char to consider the last char 'C' in the string
//without using charAt()
int count = 1;
String n="";
int i=0;
StringBuffer bf = new StringBuffer();
char c[] = s.toCharArray();
for(i=0;i< c.length-1;i++)
{
if(c[i] == c[i+1])
{
count++;
}
else
{
n = c[i] +""+count;
bf.append(n);
count=1;
}
}
System.out.println("Output: "+bf);//prints-->> Output: A3B2C1
}
}

List collections interface in java

Please find below a function in my code:
private static List<String> formCrfLinesWithMentionClass(int begin, int end, String id,
List<String> mList, int mListPos, List<String> crf) {
List<String> crfLines = crf;
int yes = 0;
mListPosChanged = mListPos;
//--------------------------------------------------------------------------
for (int crfLinesMainIter = begin; crfLinesMainIter < end; ) {
System.out.println(crfLines.get(crfLinesMainIter));
//---------------------------------------------------------------------------
//the total number of attributes without orthographic features
//in a crfLine excluding the class attribute is 98
if (!crfLines.get(crfLinesMainIter).equals("") && crfLines.get(crfLinesMainIter).split("\\s").length == 98) {
//in mList parenthesis are represented by the symbol
//in crfLines parenthesis are represented by -LRB- or -RRB-
//we make a check to ensure the equality is preserved
if(val.equals(crfLines.get(crfLinesMainIter).split("\\s")[0])) {
yes = checkForConsecutivePresence(crfLinesMainIter, mList, mListPos, id, crfLines);
if (yes > 0) {
mListPosChanged += yes;
System.out.println("formCrfLinesWithMentionClass: "+mListPosChanged);
for (int crfLinesMentionIter = crfLinesMainIter;
crfLinesMentionIter < crfLinesMainIter + yes;
crfLinesMentionIter++) {
String valString = "";
if (crfLinesMentionIter == crfLinesMainIter) {
valString += crfLines.get(crfLinesMentionIter);
valString += " B";
crfLines.add(crfLinesMentionIter, valString);
}
else {
valString += crfLines.get(crfLinesMentionIter);
valString += " I";
crfLines.add(crfLinesMentionIter, valString);
}
}
crfLinesMainIter += yes;
}
else {
++crfLinesMainIter;
}
}
else {
++crfLinesMainIter;
}
}
else {
++crfLinesMainIter;
}
}
return crfLines;
}
The problem I face is as follows:
crfLines is a List collections interface.
When the for loop (between //-----) starts out, the crfLines.get(crfLinesMainIter) works fine. But once, it enters into the if and other processing is carried out on it, even though "crfLinesMainIter" changes the crfLines.get(crfLinesMainIter) seems to get a certain previous value. It does not retrieve the actual value at the index. Has anyone faced such a scenario? Would anyone be able to tell me why this occurs?
My actual question is, when does it occur that even though the indexes might be different a list.get() function still retrieves a value from before which was at another index?
For example:
List crfLines = new LinkedList<>();
if crfLinesMainIter = 2
crfLines.get(crfLinesMainIter) brings me a value say 20 and this value 20 satisfies the if loop condition. So then further processing happens. Now when the for loop executes the values of crfLinesMainIter changes to say 5. In this case, crfLines.get(5) should actually bring me a different value, but it still brings me the previous value 20.
(Not an answer.)
Reworked (more or less) for some modicum of readability:
private static List<String> formCrfLinesWithMentionClass(int begin, int end, String id, List<String> mList, int mListPos, List<String> crf) {
List<String> crfLines = crf;
mListPosChanged = mListPos;
int i = begin;
while (i < end) {
if (crfLines.get(i).equals("") || (crfLines.get(i).split("\\s").length != 98)) {
++i;
continue;
}
if (!val.equals(crfLines.get(i).split("\\s")[0])) {
++i;
continue;
}
int yes = checkForConsecutivePresence(i, mList, mListPos, id, crfLines);
if (yes <= 0) {
++i;
continue;
}
mListPosChanged += yes;
for (int j = i; j < i + yes; j++) {
String valString = crfLines.get(j);
valString += (j == i) ? " B" : " I";
crfLines.add(j, valString);
}
i += yes;
}
return crfLines;
}
What is mListPostChanged? I find it confusing that it's being set to the value of a parameter named mListPos--it makes me think the m prefix is meaningless.
What is val in the line containing the split?

Categories