for statement errors and troubels

hello! I am trying to create a program that will take 8-digits, flip it around, and read them backwards. So far, I have:

[code]for (i = 7; i < length; i-=2)
{
System.out.print (creditCardNumber.substring(i, i+1));
System.out.print (new StringBuilder(creditCardNumber).reverse().toString());
}[/code]

I get an error message that says: "[italic]String index out of range: -1[/italic]." how do i stop it after it gets out of range?

Also, I would like to set the reversed, backwards string to a variable, but I know I can't do it in the for statement because it will print out the variable every time. I couldn't really do it outside since the for statement won't be there. Would an if statement do it?

Thanks.

Comments

  • Hey,
    The code is attempting to reverse the string twice. The [link=http://download.oracle.com/javase/6/docs/api/java/lang/StringBuilder.html#reverse()]StringBuilder[/link] class has a method you discovered that does what you want. ie.
    [code] StringBuilder sb1 = new StringBuilder("1234567");
    System.out.println("number reversed: " + sb1.reverse());[/code]
    You ask how to control the index in the loop from getting out of bounds. It is controlled by the second expression in the "for loop expression", ie.
    [code]i < length;[/code] The problem is that the expression used allows the loop to continue while i is less than length, which is presumably 8, which will lead to the problem. The code is designed to decrement i by 2 after each loop. i will change to an invalid index value in the 5'th cycle of the loop. To keep the index within bounds, ie. not allowed to be negative in this case, the following expression controls that:
    [code]i > 0;[/code]
    Regarding the last issue, being able to access a variable outside the scope of a for block, [u][b]declare[/b][/u] the variable that you want the program to access at a location that allows the variable to be used when needed. For instance, if needed at the end of a method, define the variable at the beginning of the method - it will be available throughout the method.

    Regards, se52
  • so here is what i have so far:

    [code]
    String reverse = "";

    for (i=(length-1); i>0; i-=2)
    {
    reverse=reverse + creditCardNumber.charAt(i);
    }
    System.out.print(reverse);

    int sum = reverse.substring(i, i+1);

    System.out.print ("
    " + sum);
    [/code]

    What I am attempting to do is add up all of the numbers (every-other one). I'm thinking a while statement would do the job best? For every i/i+1, add them up. Am I on the right track?
  • Hey,
    There is no reason I know of to use a reverse function or to look backward assuming that the sum of the numbers from the left most digit and every other one are to be added. Here is sample code to accomplish the task.
    [code]
    String number = "1234567";
    int everyOtherSum = 0;
    for (int i=0; i < number.length(); i += 2){
    everyOtherSum = everyOtherSum + Character.getNumericValue(number.charAt(i));
    }
    System.out.println("the sum of every other character is: " + everyOtherSum);[/code]

    g.l. se52
  • Hm, when I run it, it outputs after the message,

    System.out.println("the sum of every other character is: " + everyOtherSum);

    Also, in the next part i have to take the rest of the numbers that were not included, and double them. then add all those digits. for example, 12345678 => 14 10 6 2 => 1+4+1+0+6+2.

    do i have the right idea below?:

    [code]String number = "12345678";
    int doubleDigit;
    int doubleAddition;
    int totalDoubleAddition;

    for (int i=1; i < number.length(); i += 2){
    doubleDigit = (Character.getNumericValue(number.charAt(i))*2); //Gets the number (i) that is multiplied by 2
    doubleAddition = (doubleDigit.charAt(0) + doubleDigit.charAt(1)); // Gets the character at spot 0 and 1, and adds the two.
    totalDoubleAddition = doubleAddition + doubleAddition+i; //Adds the first number from the previous step, to the rest of the numbers
    }

    System.out.print("The sum of every other character is: " + totalDoubleAddition);[/code]
  • Looks like you are on the right track. Only use charAt() method on a String or StringBuilder, etc. What the program needs to do is process numbers and strings.
    doubleDigit is a number and to access its digits for summation, doubleDigit needs to be in a "string" format.
    The following code shows how to go from number to string. Use these pieces to accomplish the assignment.
    [code]
    String number = "12345678";
    String doubleDigitString;
    String digitString = new String("");
    int doubleDigit;

    for (int i = 1; i < number.length(); i += 2) {
    doubleDigit = (Character.getNumericValue(number.charAt(i)) * 2); //Gets the number (i) that is multiplied by 2
    doubleDigitString = String.valueOf(doubleDigit); // Save 2(i) as a string
    digitString = digitString + doubleDigitString; // Append string
    }

    System.out.println("Every other number, doubled as a string is: " + digitString);
    [/code]
  • by the way, we start at the second-to the right digit ;)

    i think i am starting to understand this! :)

    [code] for (i = 0; i < number.length(); i += 2) {
    doubleDigit = (Character.getNumericValue(number.charAt(i)) * 2); //Gets the number (i) that is multiplied by 2
    doubleDigitString = String.valueOf(doubleDigit); // Save 2(i) as a string
    digitString = digitString + doubleDigitString; // Append string
    }

    int stringSum;
    for (i=0; i < number.length(); i++){
    stringSum = digitString.charAt(i); // We don't need "+ digitString.charAt(i+1)" since "i++" is included and is therefore, always incrememnted by one?
    }

    System.out.println("Every other number, doubled, then added up, is: " + digitString);[/code]

    I just get an "out of range" error :p
  • You need to show all the code for someone to properly assess problems.

    However, I will guess that the problem is that rather than controlling on
    [color=Blue]digitString.length()[/color], number.length() is wrongly being used.

    [code]for (i=0; i < [color=Red]number.length()[/color]; i++)[/code]

    ps. [code]stringSum = digitString.charAt(i);[/code] only does repeated assignments, no addition is being performed. Also Character.getNumericValue() needs to be used to convert a "char" to an "integer".
  • ahhh.... my answers are only 1 off now!!!! (or i could just cheat, and add one at the end! =D )

    [code] String number = "71691578";
    String doubleDigitString;
    String digitString = new String("");
    int doubleDigit;
    int i;

    for (i = 0; i < number.length(); i += 2) {
    doubleDigit = (Character.getNumericValue(number.charAt(i)) * 2); //Gets the number (i) that is multiplied by 2 = 14
    doubleDigitString = String.valueOf(doubleDigit); // Save 2(i) as a string = 14
    digitString = digitString + doubleDigitString; // Append string = 261014
    }

    System.out.println(digitString);

    int stringSumNumbers=0;
    int stringSumFinal=0;
    int numbersToBeAdded=0;

    for (i=0; i < digitString.length(); i++){
    stringSumNumbers = digitString.charAt(i); // Gets the numbers to be added together
    numbersToBeAdded = Character.getNumericValue(stringSumNumbers); // Converts the character to a numeric value
    stringSumFinal = numbersToBeAdded+(numbersToBeAdded+i); // Adds up all of the numbers and sets to a variable
    }
    System.out.println(stringSumNumbers);
    System.out.println(numbersToBeAdded);
    System.out.println("Every other number, doubled, then added up, is: " + stringSumFinal);[/code]
  • Hey,
    Logic flaw in accumulation expression.
    [code]
    String number = "71691578";
    String doubleDigitString;
    String digitString = new String("");
    int doubleDigit;
    int i;

    for (i = 0; i < number.length(); i += 2) {
    doubleDigit = (Character.getNumericValue(number.charAt(i)) * 2); //Gets the number (i) that is multiplied by 2 = 14
    doubleDigitString = String.valueOf(doubleDigit); // Save 2(i) as a string = 14
    digitString = digitString + doubleDigitString; // Append string = 261014
    }

    System.out.println(digitString);

    char stringSumNumbers = ' '; // this field will hold a "char" so it is of type "char"
    int stringSumFinal = 0;
    int numbersToBeAdded = 0;

    for (i = 0; i < digitString.length(); i++) {
    stringSumNumbers = digitString.charAt(i); // Gets the numbers to be added together
    numbersToBeAdded = Character.getNumericValue(stringSumNumbers); // Converts the character to a numeric value
    stringSumFinal = stringSumFinal + numbersToBeAdded; [color=Blue]// summation requires: new sum = (old sum) plus (next number)[/color]
    [color=Red]// WRONG EXPRESSION stringSumFinal = numbersToBeAdded + (numbersToBeAdded + i); // Adds up all of the numbers and sets to a variable
    [/color] }
    System.out.println(((Character)stringSumNumbers).toString());
    System.out.println(numbersToBeAdded);
    System.out.println("Every other number, doubled, then added up, is: " + stringSumFinal);
    [/code]
  • i get an error at charLastChar in regards to an int not being able to be dereferenced. i am trying to get the last digit, and check to see if it is a 0.

    [code]
    int stringSumNumbers=0;
    int stringSumFinal=0;
    int numbersToBeAdded=0;

    for (i=0; i < digitString.length(); i++){
    stringSumNumbers = digitString.charAt(i); // Gets the numbers to be added together
    numbersToBeAdded = Character.getNumericValue(stringSumNumbers); // Converts the character to a numeric value
    stringSumFinal = stringSumFinal + numbersToBeAdded; // summation requires: new sum = (old sum) plus (next number)
    }

    System.out.println("Every other number, doubled, then added up, is: " + stringSumFinal);

    // Part Three

    Integer.parseInt(digitString);

    combinedSumAnswer = stringSumFinal + stringSumFinal2;

    char lastChar=combinedSumAnswer.charAt(length-1);
    [/code]
  • Hey,
    not sure what you are trying to do, some of the code is missing like the definition of [b][u]digitString[/u][/b] and others.
    The "display" says "Every other number, doubled, then added up" but each number in the string is summed and nothing is doubled.
    The error occurs because a method, like charAt() is attempted on an "untyped", ie. not declared variable, combinedSumAnswer

    The following code eliminates the compile errors, but may not do what you want it to do.
    [code]
    String digitString = "12345678";
    char stringSumNumbers; // =0;
    int stringSumFinal=0;
    int numbersToBeAdded=0;
    int i; // ADDED
    for (i=0; i < digitString.length(); i++){
    stringSumNumbers = digitString.charAt(i); // Gets the numbers to be added together
    numbersToBeAdded = Character.getNumericValue(stringSumNumbers); // Converts the character to a numeric value
    System.out.println(" number to be added: " + numbersToBeAdded);
    stringSumFinal = stringSumFinal + numbersToBeAdded; // summation requires: new sum = (old sum) plus (next number)
    }

    System.out.println("Every other number, doubled, then added up, is: " + stringSumFinal);

    // Part Three

    Integer.parseInt(digitString); // SHOULD THIS BE ASSIGNED TO stringSumFinal2 ???

    Integer combinedSumAnswer = stringSumFinal; // + stringSumFinal2; // stringSumFinal2 is not defined

    String combinedSumAnswerString = combinedSumAnswer.toString();

    char lastChar=combinedSumAnswerString.charAt(combinedSumAnswerString.length()-1);
    System.out.println(lastChar);
    }

    }[/code]

    Read about various class methods following these links:
    [link=http://download.oracle.com/javase/6/docs/api/java/lang/Integer.html]Integer[/link]
    [link=http://download.oracle.com/javase/6/docs/api/java/lang/String.html]String[/link]
    [link=http://download.oracle.com/javase/6/docs/api/index.html?java/lang/String.html]any class[/link] select the class from the bottom panel on the left

    Please start a new thread if there are additional questions.




    regards, se52
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories