Paul B Fitzsimons
Paul B Fitzsimons

Reputation: 85

Basic question about for loop with char array (Java)

My assignment is to go through a users input and convert it to a total sum. Idea is to change all the letters to a corresponding number, as in a = 1 and so on.

Really basic stuff but I'm at a loss, my idea was to convert the users response to a char array and then loop through each char and then use a switch or multiple loops to get the value but I can't even get a for loop to work because I'm getting "Cannot invoke charAt(int) on the array type char[]".

public class question3 {

    public static void main(String[] args){
        Scanner userTypes = new Scanner(System.in);

        String wordValue;
        System.out.print("Please enter a string");
        wordValue = userTypes.next();

        String lowerCase;
        lowerCase = wordValue.toLowerCase();

        char[] arrayConvert = lowerCase.toCharArray();

        System.out.println(arrayConvert);
        int fullNumber;
        System.out.print("Please enter an int");
        fullNumber = userTypes.nextInt();

        double decimalNumber;
        System.out.print("Please enter a double");
        decimalNumber = userTypes.nextDouble();

        double totalNumber;
        totalNumber = fullNumber + decimalNumber;
        System.out.print("your result is " + totalNumber);

        for(int i=0; i< arrayConvert.length;i++) {
            if(arrayConvert.charAt(i)== ("a")){

            }
        }
    }

Upvotes: 2

Views: 153

Answers (2)

Ganesa Vijayakumar
Ganesa Vijayakumar

Reputation: 2602

My first question, Why do you want to get a string and converting into int or long. It looks you need to do code for all the inputs (i,e- if you want to get 1000 values as inputs then you need to write code stdout and next* operation for 1000 times.

Try the below one which will help users to choose their choice of inputs and get the sum value of those inputs.

SumGivenInputs.java

import java.util.Arrays;
import java.util.Scanner;

public class SumGivenInputs {

   public static void main(String[] args) {
       Scanner scan = new Scanner(System.in);
       System.out.print("Enter the number of inputs\n");
       int noOfInput = scan.nextInt();

       System.out.printf("Enter the %d input%s \n", noOfInput, noOfInput > 1 ? "s one by one" : "");
       Integer[] inputList = new Integer[noOfInput];
       for (int i = 0; i < noOfInput; i++) {
           inputList[i] = scan.nextInt();
       }
       int result = 0;
       for (Integer input : Arrays.asList(inputList)) {
           result += input;
       }
       System.out.printf("Sum = %s", result);
   }
}

Output:

Enter the number of inputs
5
Enter the 5 inputs one by one 
10
20
30
5
50
Sum = 115

Upvotes: 0

mcord
mcord

Reputation: 21

I didn't test your code, but charAt isn't a char[] method. Try this:

for(int i=0; i< arrayConvert.length;i++) {
    if(arrayConvert[i] == 'a'){

    }
}

Upvotes: 2

Related Questions