import java.util.Scanner;
public class finnTall {
public static void main(String[]args){
int antallTall;
int antallLest;
double nesteTall;
double minsteVerdi;
double nestMinsteVerdi;
Scanner tast = new Scanner(System.in);
System.out.println("Hvor mange tall?");
antallTall = tast.nextInt();
tast.nextLine();
antallLest= 1;
System.out.println("Skriv første tall: ");
minsteVerdi = tast.nextDouble();
tast.nextLine();
for(antallLest=1;antallTall>antallLest;antallLest++){
System.out.printf("Skriv %d. tall: ",antallLest+1);
nesteTall = tast.nextDouble();
tast.nextLine();
if(nesteTall>minsteVerdi)
nestMinsteVerdi=nesteTall;
if(nesteTall<minsteVerdi)
nesteTall = minsteVerdi;
if(nesteTall>minsteVerdi && nesteTall<nestMinsteVerdi)
nestMinsteVerdi = nesteTall;
}
System.out.printf("Minste verdien av tallene du har oppgitt er: %f\n",minsteVerdi);
System.out.printf("Nest minste verdi av tallene du har oppgitt er: %f\n",nestMinsteVerdi);
tast.close();
}
}
사용자가 제공하는 가장 낮은 두 번째 숫자를 계산하는 프로그램입니다.변수가 초기화되지 않은 것으로 보입니다.
어떤 이유인지 로컬 변수 nestMinsteVerdi
이 초기화되지 않았기 때문에 오류가있는 이유 또는 위치를 파악할 수 없습니다. 나는 좋은 2 시간 동안 이것으로 고투하고있다.
미리 감사드립니다.
나는 당신이 말하는 것을 얻지 만 동시에 나는 그렇지 않습니다. 코드에서 변경해야 할 부분은 무엇입니까? 직접보고 싶지 않다면 –
실행 중에 코드를 통해 어떤 경로를 취했는지에 관계없이'nestMinsteVerdi'가 값을 사용하기 전에 값을 주어야합니다. 한 가지 방법은 선언에'double nestMinsteVerdi = 0.0' (또는 어떤 값이든간에)의 기본값을 제공하는 것입니다. 또 다른 경우는 if (nesteTall> minsteVerdi)에 대한 'else'케이스입니다. –
@Bendik 세 번째 방법은 'boolean' 플래그 변수를 사용하여 값을 찾았는지 여부를 추적하고 값을 찾지 못한 경우 끝에 출력하지 않는 것입니다 그것에 할당 할 수 있습니다. –