191k views
3 votes
In Java: Write a program whose inputs are three integers, and whose output is the smallest of the three values.Ex: If the input is: 7 15 3Output: 3Code:import java.util.Scanner;public class LabProgram{public static int LargestNumber(int num1, int num2, int num3){if(num1 > num2 && num1 > num3)return num1;else if(num2 > num3)return num2;elsereturn num3;}public static int SmallestNumber(int num1, int num2, int num3){if(num1 < num2 && num1 < num3);return num1;else if(num2 < num3)return num2;elsereturn num3;}public static void main(String[] args){int a,b,c, largest, smallest;Scanner sc=new Scanner(System.in);System.out.println("\\Enter the numbers:");a=sc.nextInt();b=sc.nextInt();c=sc.nextInt();largest = LargestNumber(a,b,c);smallest = SmallestNumber(a,b,c);System.out.println("\\Largest: "+largest);System.out.println("Smallest: "+smallest);}}Error: LabProgram.java:20: error: 'else' without 'if' else if(num2 < num3)

User Radix
by
8.3k points

1 Answer

2 votes

The error message is indicating that there is an 'else' statement without an associated 'if' statement. This is likely caused by a semicolon at the end of the following line.

This semicolon is ending the if statement and causing the following else statement to not be associated with an if statement.

To fix this error, you can remove the semicolon and it should work fine.

It should be like this.

Also, you can remove the first method LargestNumber(int num1, int num2, int num3) and its calling in the main method as it's not needed and causing confusion.

Here's the final code:

-------------------------------------------------

import java.util.Scanner;

public class LabProgram{

public static int SmallestNumber(int num1, int num2, int num3){

if(num1 < num2 && num1 < num3) return num1;

else if(num2 < num3) return num2;

else return num3;

}

public static void main(String[] args){

int a,b,c, smallest;

Scanner sc=new Scanner(System.in);

System.out.println("\\Enter the numbers:");

a=sc.nextInt();

b=sc.nextInt();

c=sc.nextInt();

smallest = SmallestNumber(a,b,c);

System.out.println("\\Smallest: "+smallest);

}

}

---------------------------------------------------------------------------

In this code, the user inputs 3 integers, the program then uses an if-else statement inside the method SmallestNumber(int num1, int num2, int num3) to determine the smallest of the three values, and then it prints the smallest value on the console.

User Rosenfeld
by
7.3k points