Duvida em parar o while dentro for[RESOLVIDO]

estou com uma duvida tenho um for e um while dentro dele,depois q eu achar a o registro q me importar eu quero retornar o valor achado e sair do while e for,pelo q sei era so colocar o break mais no momento q eu coloco o return da erro no break?

 public String trataD(String assinantes) throws SQLException 
	{
		
		Statement st_danal =  cnn.createStatement();
		HashSet <String> destindexS  = new HashSet<String>();
		for(int i = 0;i < assinantes.length();i++)
		{
			sql = " select distinct digstring,destindex " + 
			  " from danal "+
			  " where digstring = '" + (i == 0 ? assinantes : assinantes.substring(0,assinantes.length() - i)) + "'";
					
			//System.out.println(i == 0 ? assinantes : assinantes.substring(0,assinantes.length() - i));
			ResultSet rs_danal = st_danal.executeQuery(sql);
			
				while(rs_danal.next())
				{
					System.out.println("Comecando While");
					//destindexS.add(rs_danal.getString("destindex"));
					System.out.println(assinantes + " | "+rs_danal.getString("digstring") +" | "+ rs_danal.getString("destindex"));
					return rs_danal.getString("destindex");
					break; //<== erro aki
				}
		}
		
		return null;
	}

Quando vc manda dar um Return automáticamente nada mais vai ser executado nesse bloco.

Por isso o return tem que ser o último comando, entendeu?

Experimente trocar de ordem:

break;  
return rs_danal.getString("destindex");  

isso nao pode,pq qnd da o break ele vai sair de tudo e nao vai retornar da ate erro !!!

Você tem um While e um For, e o retorno do seu método é uma String ???
Algo está estranho não ?
Você tem que retornar um Array, ou sei lá uma String concatenada.

O Problema não é o While ou o For, o problema é “O que esse metódo vai retornar ?”
Tirando o fato, que você acabará fazendo 500 SQLs, se você tiver 500 assinantes.

E ai dicabeca,

 Seguinte.....

 Pelo que entendi o erro é o tal de "Unreachable code". No seu caso tem que dar este erro mesmo porque quando vc coloca o return torna-se impossível executar o break e quando vc coloca o break no lugar do return torna-se impossível executar o return.

 Pra te ajudar acho que vc precisa dizer o que você tá querendo fazer dentro deste método. Tudo parece tranquilo mas subtamente você colocou um return/break dentro do while logo na primeira iteração, "meteu o pé no pau da barraca" sem dó.

 Acho que vc estava indo bem na idéia mas está com problemas na finalização.

System.out.println(“Abraços”);

bom na verdade,nem gera erro pq a ide ja acusa erro de sintaxe qnd coloco o break, tem uma solucao mais nao é a melhor.essa funcao faz o seguinte, vou passar uma string com 8 caracteres e vou fzr uma varredura na tabela nadal,sendo q primeiro eu tento achar com 8 digitos mesmo c nao achar eu vou diminuindo pegando os 7,6… primeiros digitos e assim vai, sendo que c encontrar me mande o destindex e pare de fzr o loop,pq ja achei o q quero entenderam ?

Tenta usar Labeled Statements para parar um loop interno e continuar o externo:

/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */ 

class BreakWithLabelDemo {
    public static void main(String[] args) {

        int[][] arrayOfInts = { { 32, 87, 3, 589 },
                                { 12, 1076, 2000, 8 },
                                { 622, 127, 77, 955 }
                              };
        int searchfor = 12;

        int i;
        int j = 0;
        boolean foundIt = false;

    search:
        for (i = 0; i < arrayOfInts.length; i++) {
            for (j = 0; j < arrayOfInts[i].length; j++) {
                if (arrayOfInts[i][j] == searchfor) {
                    foundIt = true;
                    break search;
                }
            }
        }

        if (foundIt) {
            System.out.println("Found " + searchfor +
                               " at " + i + ", " + j);
        } else {
            System.out.println(searchfor
                               + " not in the array");
        }
    }
}

[quote]
Tenta usar Labeled Statements para parar um loop interno e continuar o externo:

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/branch.html [/quote]

eu quero q retorne o valor e parar os 2 loops!!!

NADA que você colocar depois do return vai ser executado… o return tem que ser a última instrução de um método.

mais como eu vou retornar o q quero e parar o loop,nao tem como, vai ter q ser na marreta entao ?

dicabeca, você pode explicar melhor o que você quer?
Porque se for o que eu to pensando tem sim uma saída…

Abraços,

Tentou usar o labeled statement para o os dois loops, não sei se é possivél , mas caso for voce pode assim que atender a sua condição de achar o que precisa, setar o conteudo na variavel que será retornada e dar dois breaks labeled…

[quote]pimenta:
dicabeca, você pode explicar melhor o que você quer?
Porque se for o que eu to pensando tem sim uma saída…

Abraços,[/quote]

Faz assim:

 public String trataD(String assinantes) throws SQLException 
	{
		
		Statement st_danal =  cnn.createStatement();
		HashSet <String> destindexS  = new HashSet<String>();
                Strinf resultado = null;

		for(int i = 0;i < assinantes.length();i++)
		{
			sql = " select distinct digstring,destindex " + 
			  " from danal "+
			  " where digstring = '" + (i == 0 ? assinantes : assinantes.substring(0,assinantes.length() - i)) + "'";
					
			//System.out.println(i == 0 ? assinantes : assinantes.substring(0,assinantes.length() - i));
			ResultSet rs_danal = st_danal.executeQuery(sql);
			
				while(rs_danal.next())
				{
					System.out.println("Comecando While");
					System.out.println(assinantes + " | "+rs_danal.getString("digstring") +" | "+ rs_danal.getString("destindex"));
					resultado = rs_danal.getString("destindex");
					break;
				}

                        if (resultado != null) {
                           break;
                        }
		}
		
		return resultado;
	}

O return encerra o método, não precisa de break.

Tá aí… se entendi bem o que o Foxlol colocou resolve seu problema.

Abraços,

cara … eu acho q nun to entendendo sua duvia … pq ela me parece MUITO simples … mas pelo o q eu entendi é o seguinte

quando vc executa esse linha

return rs_danal.getString(“destindex”);

que está dentro do while …

ele sai do while e sai do for tambem

esse return ele já é o retorno do método automaticamente (de acordo com os meus testes aki)

ou seja … tira esse breack … deixa só o return … q tah certo … ele vai sair do do METODO INTEIRO nã hora q vc executar esse return rs_danal.getString(“destindex”);

nada mais será executado … nem o while nem o for

Há uma exceção, um bloco finally sempre será executado.

ai galera o Schuenemann esta certo e so isso q precisava,valeu ai pra geral pela ajuda e atencao obrigadao a todos !!!

[quote=Bruno Laturner]
Há uma exceção, um bloco finally sempre será executado.[/quote]

Excelente colocação, Bruno. Como sempre: O detalhe é o que vale!