write a program in java to extract the first number and last number from a word
- User
write a program in java to extract the first number and last number from a word
Assistant
Here's a simple Java program that extracts the first and last numbers from a word:
import java.util.Scanner; public class ExtractNumbers { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a word: "); String word = scanner.nextLine(); scanner.close(); if (word.isEmpty()) { System.out.println("The input word is empty."); return; } String firstNumber = ""; String lastNumber = ""; for (int i = 0; i < word.length(); i++) { char currentChar = word.charAt(i); if (Character.isDigit(currentChar)) { if (firstNumber.isEmpty()) { firstNumber = String.valueOf(currentChar); } lastNumber = String.valueOf(currentChar); } } System.out.println("First number: " + firstNumber); System.out.println("Last number: " + lastNumber); } }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.