2014-11-24 2 views
-1

hey У меня есть оператор if и else, который я хотел бы зацикливать, если else происходит, так как это означает, что пользователь не ввел требуемую сумму, поэтому программа перезапустится здесь, это код любых идей ?Зацикливание инструкции if в Java

System.out.println("The area of the glass is " + area); 

    if (thick == 3) 
    { 

     System.out.println("The price to replace the glass will be £" + price1); 
     System.out.println("With VAT the price is £" + Final1 ); 
    } 
    else if (thick == 5) 
    { 

     System.out.println("The price to replace the glass will be £" + price2); 
     System.out.println("With VAT the price is £" + Final2); 
    } 

    else if (thick == 7) 
    { 

    System.out.println("The price to replace the glass will be £" + price3); 
    System.out.println("With VAT the price is £" + Final3); 
    } 
    else 
    { 
    System.out.println("Sorry for the inconvenience but we do not do this size thinkness."); //If the we don't have the thickness this is displayed 
    } 

Заранее спасибо

+0

вы имеете в виду вы проверяете для пользовательского ввода, и если они входят в его неправильно вы хотите начать все заново? – Luminusss

+0

Да, в основном, если пользователь не вводит 3 5 или 7, то я хочу, чтобы программа перезапустила довольно новую для java, поэтому любые примеры могут быть большой помощью. –

+0

просто добавил еще один ответ, теперь у вас должно быть несколько предложений. – Luminusss

ответ

2

Используйте петлю в то время как петли, пока переменная не является приемлемым:

thick = 0; 
while (thick != 3 && thick != 5 && thick != 7) { 
    // read new thick value from user 
    // your current code 
} 

Вы можете выразить выше более аккуратно:

for (thick = 0; !Arrays.asList(3, 5, 7).contains(thick);) 
    // read new thick value from user 
    // your current code 
} 
+0

Это, наверное, один из самых чистых способов сделать это. – Luminusss

+0

Спасибо всем, что мне было нужно, было просто и просто для ухищрения заданий. –

0

Вы могли бы использовать цикл. Если введен правильный ответ, выйдите из цикла. В противном случае продолжайте цикл.

Пример:

while(true){ 
    <get input here> 
    if(thick==3){ 
     <do stuff> 
     break; 
    } 
    else if(...){ 
     <do stuff> 
     break; 
    } 
    ... 
    else{ 
     <do stuff> 
    } 
} 
0
do { 
your code 
}while(the_else_occurs); 

А именно:

boolean flag=false; 
do{ 
    if (thick == 3) 
    { 

     System.out.println("The price to replace the glass will be £" + price1); 
     System.out.println("With VAT the price is £" + Final1 ); 
    } 
    else if (thick == 5) 
    { 

     System.out.println("The price to replace the glass will be £" + price2); 
     System.out.println("With VAT the price is £" + Final2); 
    } 

    else if (thick == 7) 
    { 

    System.out.println("The price to replace the glass will be £" + price3); 
    System.out.println("With VAT the price is £" + Final3); 
    } 
    else { 
     flag=true; 
    System.out.println("Sorry for the inconvenience but we do not do this size thinkness."); //If the we don't have the thickness this is displayed 
    } 
    }while(flag); 
0

Я думаю, вы должны бросить в некоторых проверки входных данных:

while(thick != 3 && thick != 5 && thick != 7 && thick != null){ 

    System.out.println("Sorry for the inconvenience but we do not do this size thinkness.");  

    //If the we don't have the thickness this is displayed 
} 
+0

спасибо @ rink.attendant.6 должно было позволить мне исправить это самостоятельно. – penjoku

0

Вы также можете попробовать создать метод и ссылаясь на его (рекурсии), если его не введен правильно:

public void MyMethod() { 

System.out.println("The area of the glass is " + area); 

if (thick == 3) 
{ 

    System.out.println("The price to replace the glass will be £" + price1); 
    System.out.println("With VAT the price is £" + Final1 ); 
} 
else if (thick == 5) 
{ 

    System.out.println("The price to replace the glass will be £" + price2); 
    System.out.println("With VAT the price is £" + Final2); 
} 

else if (thick == 7) 
{ 

System.out.println("The price to replace the glass will be £" + price3); 
System.out.println("With VAT the price is £" + Final3); 
} 
else 
{ 
System.out.println("Sorry for the inconvenience but we do not do this size thinkness."); //If the we don't have the thickness this is displayed 
MyMethod(); 
} 
} 

Единственное, что с этим связано с тем, что вы должны быть осторожны с переполнением стека. А вот инструкция switch может быть хорошей заменой. Всего несколько предложений.

0

вы можете использовать хэш-карту вместо:

HashMap<int, PointF> map = new HashMap<int, PointF>() 
{ 
    { 3, new PointF(4.5f, 6) }, 
    { 5, new PointF(8, 6.3f) }, 
    { 6, new PointF(9, 8) }, 
}; 

if (map.containsKey(thick)) 
{ 
    System.out.println("The price to replace the glass will be £" + map.get(thick).x); 
    System.out.println("With VAT the price is £" + map.get(thick).y); 
} 

если вы можете переключаться PointF с пользовательским классом это woulb будет WAY лучше

Смежные вопросы