Answer:
import java.util.Scanner;
public class FirstWord {
public static void main(String[] args) {
//NOW YOU WANT TO COLLECT INPUTS FROM THE STUDENT OR USER
//IMPORT THE SCANNER CLASS FIRST outside your class
// THEN YOU CREATE AN OBJECT OF THE SCANNER CLASS
Scanner input = new Scanner(System.in);
//CREATE A VARIABLE TO HOLD THE USER INPUT
String text = input.nextLine();
//The variable holder will be used to store characters from the for loop
String holder="";
//Create a for loop that loops through the user's input
for(int i=0; i<text.length(); i++){
//As the loop increases, we get the character in the user's input and store them one by one in the variable holder
holder+=text.charAt(i);
if(text.charAt(i)==' '){
//If the loop encounters a space, it means a complete word has been gotten from the user's input
//Then the break below Breaks the loop, and the loop stops running
break;
}
}
System.out.println(holder);
}
Explanation:
text.length() returns the length of the sequence of characters present in length
text.charAt(a number) Returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.
Create a for loop
How does a for loop work?
It collects a starting point, an end point and an increment respectively....all these are passed in as arguments into the for loop
For example, the code above starts from 0, calculates the number of characters in the user's input and sets it as the end point, the loop runs from zero to the length of the text of the user...
Note: i++ in the loop is the increment, it means the loop increases by 1