Reputation: 155
I wrote a code here to do the following: Prompt the user for how many numbers are going to be entered. We called this value userRequest. So, userRequest times we do the following: read a String. This String will have the form: a mixture of digits and letters. return the integers of the String and the letters separated.
but in the returning code, I scanned the string character by character, so it printed each input separately. But, my question is how can I print the numbers together as one integer and the letters together as on string. (I think it needs arrays, but I couldn't call an array when it inside a loop)
import java.util.*;
public class Program8{
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
int userRequest;
int returnNum;
System.out.print("How many numbers do you wish to enter? ");
while (!scan.hasNextInt()){
System.err.print("Please try again, with digits only: ");
scan.next();
}//while
userRequest = scan.nextInt();
int sortingNum = 1;
String str;
char ch;
str = scan.nextLine();
for (int i = 0; i < userRequest; i++){
System.out.print("* Please enter a string #" + sortingNum + ": ");
str = scan.nextLine();
System.out.println("- String #" + sortingNum++ + " = " + str);
for (int j = 0; j < str.length(); j++){
ch = str.charAt(j);
if ((ch + 0) >= 48 && (ch + 0) <= 57){
int digit = ((ch + 0) - 48);
System.out.println(digit);
}
}
System.out.println();
for (int k = 0; k < str.length(); k++){
if (str.toLowerCase().charAt(k) >= 'a' && str.toLowerCase().charAt(k) <= 'z')
System.out.println(str.charAt(k));
}
}//for
}//main
}//Program8
Upvotes: 0
Views: 272
Reputation: 545
For the number:
Add the logic to multiply a variable by 10 and add the digits extracted.
For the string:
Add the logic to append the characters to a stringbuilder object.
Code:
int finalNumber = 0;
for (int j = 0; j < str.length(); j++){
ch = str.charAt(j);
if ((ch + 0) >= 48 && (ch + 0) <= 57){
int digit = ((ch + 0) - 48);
finalNumber = finalNumber*10 + digit;
//System.out.println(digit);
}
}
System.out.println(finalNumber);
System.out.println();
StringBuilder finalString = new StringBuilder();
for (int k = 0; k < str.length(); k++){
if (str.toLowerCase().charAt(k) >= 'a' && str.toLowerCase().charAt(k) <= 'z') {
//System.out.println(str.charAt(k));
finalString.append(str.charAt(k));
}
}
System.out.println(finalString.toString());
Upvotes: 1