Below is a Java program that converts a string input from the user into an integer:
import java.util.Scanner;
public class StringToInteger {
public static void main(String[] args) {
// Create a Scanner object to read input from the console
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter a number as a string
System.out.print("Enter a number as a string: ");
// Read the input from the console
String inputString = scanner.nextLine();
// Convert the string to an integer using parseInt method of Integer class
try {
int number = Integer.parseInt(inputString);
System.out.println("The integer value is: " + number);
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid integer.");
}
// Close the scanner
scanner.close();
}
}
This program prompts the user to enter a number as a string, reads the input from the console using the `Scanner.nextLine()` method, and then attempts to convert the string to an integer using the `Integer.parseInt()` method. If the input string cannot be parsed as an integer, it catches a `NumberFormatException` and notifies the user about the invalid input. Otherwise, it prints the converted integer value. Finally, it closes the `Scanner` object.