For loop in Java

Asked

Viewed 372 times

0

need to receive an n number and then repeat the receipt and processing of the v string, n times. I tried to do the following:

    import java.util.Scanner;
    public class Main {
    public static void main(String []args){
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    for(int x = 1; x < n; x++){
        String v = sc.next();
        int valorLed = 0;
        char [] numLed = { 6, 2, 5, 5, 4, 5, 6, 3, 7, 6 };
        char [] listV = v.toCharArray(); 
        int k = 0;
        int soma = 0;

        for(int i = 0; i < listV.length; i++ ){
            k = (listV[i]-48);
            k = numLed[k];
            soma += k;
        }
        System.out.print(soma +" leds");
    }
}
    }

But it didn’t work. How to proceed? For example, if n equals 2, then I will receive two different V’s and print two different outputs.

  • "It didn’t work" is very generic. What exactly didn’t work? Give more details of the problem.

1 answer

0


The line for(int x = 1; x < n; x++)

Has to be x <= n for(int x = 1; x <= n; x++)

or x start of 0

for(int x = 0; x < n; x++)

public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("\nEntre com o valor de N :");
        int n = sc.nextInt();
        System.out.println("\nNumero digitado :"+n);
        for(int x = 1; x <= n; x++){
            System.out.println("\nEntre com o valor de V passagem :"+x);
            String v = sc.next();
            int valorLed = 0;
            char [] numLed = { 6, 2, 5, 5, 4, 5, 6, 3, 7, 6 };
            char [] listV = v.toCharArray(); 
            int k = 0;
            int soma = 0;
            for(int i = 0; i < listV.length; i++ ){
                k = (listV[i]-48);
                k = numLed[k];
                soma += k;
            }
            System.out.print("\n"+soma +" leds");
        }

    }
  • So even so, the code is not repeated n times

  • This passing yes is that you have two Keyboard readings see the step by step I posted

Browser other questions tagged

You are not signed in. Login or sign up in order to post.