In: Computer Science
Write a java code that first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in the string is not a valid integral number, or if no such sequence exists because either string is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned.
Example 1:
Input: "42"
Output: 42
Example 2:
Input: " -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign. Then take as many numerical digits as possible, which gets 42.
Example 3:
Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.
Example 4:
Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical digit or a +/- sign. Therefore no valid conversion could be performed.
Note 1: Place single line comments wherever it is necessary before a line of code to explain the lines of code in Java Project.
Note 2: When you are testing your code, drop the " around the input values.
Note 3: In this project, you should use the String methods you have learned in this class and implement a loop structure.
Below is code:
import java.util.*;
public class Main
{
public static void main(String[] args) {
String isNext = "y";
Scanner sc= new Scanner(System.in);
//define regular expression
String regex = "(\\s)[^\\d]+";
//loop structure.
while(isNext.equals("y"))
{
System.out.print("Input: ");
//take input from user
String str= sc.nextLine();
//remove double quots and spaces from starting
str = str.replace("\"", "");
str = str.trim();
//get number from string with matches regular expression
String[] str1 = str.split(regex);
try {
//print numerical digit.
System.out.println("Output: "+Integer.parseInt(str1[0]));
} catch (NumberFormatException e) {
//othervise print 0
System.out.println("Output: "+0);
}
System.out.print("Do you want to continue? (y/n): ");
isNext= sc.nextLine();
}
}
}
Output: