Using delimeter to seperate Scanner input into different dataTypes.(String, int, - delimiter

how can i use delimiter " : " to receive a string from (system.in ) E.g Ben : 50. Jessica : 30 and so on , and then print as Ben, 50 using my own System.out.print (name + "," + score); I was able to print out the string as string but its not printing out the integer as integer. I need to calculate the average of all the score and that is why i need integer to remain integer so the average method can work Here is my code . Here is my code so far. Please help !!!
-------------------------------------------------------------------------
import java.util.Scanner;
public class StudentScore{
public static void main(String [] args){
Scanner input = new Scanner(System.in);
input.useDelimiter(":");
System.out.print("Please enter your name and score in format: Ben : 50" );
String name = input.next();
int score = input.nextInt();
while(input.hasNext() || input.hasNextInt());{
System.out.println(name + ", " + score);
}
input.close();
}
}
this keeps creeating a new scanner and no print out.

After researching and asking several people , i found out the String class actually has a function that takes in string and then splits it into several primitive values" long", " int" and so on. You need to convert your input into an array, make sure it is spitted by a delimiter of choice .e.g "," or ":" in my own case. Then the array will be your parameter for the .split method from the String class. I posted my complete program below. The programs takes in three names and score and outputs the grade letter and then tells the best score among the three students.
import java.util.Scanner;
public class ThreeNamesAndScore {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter your name and score in this format, Name : Score");
String input1 = input.nextLine();
String[] userData1 = input1.split(":");
String firstStudentName = userData1[0];
String firstStudentStrScore = userData1[1];
int firstStudentScore = Integer.parseInt(firstStudentStrScore);
System.out.print("Please enter your name and score in this format, Name : Score");
String input2 = input.nextLine();
String[] userData2 = input2.split(":");
String secondStudentName = userData2[0];
String secondStudentStrScore = userData2[1];
int secondStudentScore = Integer.parseInt(secondStudentStrScore);
System.out.print("Please enter your name and score in this format, Name : Score");
String input3 = input.nextLine();
String[] userData3 = input3.split(":");
String thirdStudentName = userData3[0];
String thirdStudentStrScore = userData3[1];
int thirdStudentScore = Integer.parseInt(thirdStudentStrScore);
System.out.println("The following is the fianl result ");
System.out.println(firstStudentName + ", " + getGradeLetter(firstStudentScore));
System.out.println(secondStudentName + ", " + getGradeLetter(secondStudentScore));
System.out.println(thirdStudentName + ", " + getGradeLetter(thirdStudentScore));
System.out.println("The best score is from " + bestScore(input1, input2, input3));
input.close();
}
public static String getGradeLetter(int score) {
if (score >= 90) {
return "A";
} else if (score >= 80) {
return "B";
} else if (score >= 70) {
return "C";
} else if (score >= 60) {
return "D";
} else
return "F";
}
public static String bestScore(String a, String b, String c) {
String bestStudent;
String[] userInputs = { a, b, c };
String[] user1 = a.split(":");
String aStrScore = user1[1];
int aScore = Integer.parseInt(aStrScore);
String[] user2 = b.split(":");
String bStrScore = user2[1];
int bScore = Integer.parseInt(bStrScore);
String[] user3 = c.split(":");
String cStrScore = user3[1];
int cScore = Integer.parseInt(cStrScore);
if ((aScore > bScore) && (aScore > cScore))
bestStudent = a;
else if ((bScore > aScore) && (bScore > cScore))
bestStudent = b;
else
bestStudent = c;
return bestStudent;
}
}

Related

How to create a function WordSplit(strArr) read the array of strings stored in strArr using dart

I have a simple exercise in Coderbyte, it just want to have a function that's WordSplit(strArr) read the array of strings stored in strArr, For example I have two elements like ["hellocat", "apple,bat,cat,goodbye,hello,yellow,why"]
I just want to to determine if the first element in the input can be split into two words, where both words exist in the dictionary that is provided in the second input.
For example: the first element can be split into two words: hello and cat because both of those words are in the dictionary.
So the program should return the two words that exist in the dictionary separated by a comma, as this result hello,cat .
I've made a recursive solution below. It checks if the string to be split starts with any word in the dictionary. If it exists, the function is called again using a substring with that first word removed.
This function only works up to the first word that isn't in the dictionary since you did not specify the expected behavior when the inputted word is not made up of words in the dictionary. You could make it throw an exception perhaps, but please specify your expectation.
void main() {
print(wordSplit(["hellocat", "apple,bat,cat,goodbye,hello,yellow,why"]));
//hello,cat
}
String wordSplit(List<String> arg) {
String wordToSplit = arg[0];
String dict = arg[1];
List<String> parsedDict = arg[1].split(',');
for(String word in parsedDict) {
if(wordToSplit.startsWith(word)) {
//If the substring would be empty, don't do more recursion
if(word.length == wordToSplit.length) {
return word;
}
return word + ',' + wordSplit([wordToSplit.substring(word.length), dict]);
}
}
return wordToSplit;
}
#include <bits/stdc++.h>
using namespace std;
vector<string> converToWords(string dict) {
vector<string> res;
string s = "";
int n = dict.length();
for(int i=0; i<n; i++) {
if(dict[i] == ',') {
res.push_back(s);
s = "";
}
else s += dict[i];
}
res.push_back(s);
s = "";
return res;
}
string solve(string str[]) {
string result = "";
string word = str[0], dict = str[1];
int n = word.length();
vector<string> vs = converToWords(dict);
unordered_set<string> ust;
for(auto it: vs) ust.insert(it);
// for(auto i=ust.begin(); i!=ust.end(); i++){
// cout<<*i<<endl;
// }
string s = "";
for(int i=0; i<n; i++) {
s += word[i];
// cout<<s<<endl;
string temp = word.substr(i+1, n-(i+1));
// cout<<temp<<endl;
if(ust.find(s) != ust.end() && ust.find(temp) != ust.end()) {
cout<<s<<endl;
cout<<temp<<endl;
result += s+","+temp;
break;
}
temp = "";
}
return result;
}
int main() {
string arr[2];
cin>>arr[0]>>arr[1];
cout << solve(arr);
return 0;
}

dxl findPlainText check does not match string

I have a subroutine that I pass a string value from a skip list. That value is compared to objects in a Doors File. But the comparison does not work.
Skip split (string s, string delim)
{
Skip skp = create
int i = 0
Regexp split = regexp "^(.*?)" delim "(.*)$"
while (split s)
{
string temp_s = s[match 2]
put(skp, i++, s[match 1] "")
s = temp_s
}
put(skp, i++, s "")
return skp
}
string getInfo( string inStr)
{
for currObj in currMod do
{
if ( findPlainText( ( currOBJ.SW_VRC ""), inStr, offsetFromFind, lengthFromFind, false ) )
{
print currOBJ.SW_VRC " matches " inStr "\n";
}
}
}
Skip newLst = split(modname, ",") // this just splits a string input into parameters separated by commas
string inputInfo;
find(newLst, 0, inputInfo)
getInfo(inputInfo)
Now this is a simplified version of what I am doing. But the findPlainText does not match anything. inputInfo is getting the correct string, I checked.
The part that really kills me is if I hardcode in the parameter
i.e. inStr = "21";
It works like it's supposed to.
Now I was assuming a string is a string. Is there a difference between a string from a skip list and a string that's quoted? Is there a hidden character?
What am I missing? Any insight you could provide would be welcome.
Thanks,
DevM
your snippet works, but I had to add some variables to make it work, and I don't have a split function at hand:
Skip split (string s, string delim)
{
Skip skp = create
int i = 0
Regexp split = regexp "^(.*?)" delim "(.*)$"
while (split s)
{
string temp_s = s[match 2]
put(skp, i++, s[match 1] "")
s = temp_s
}
put(skp, i++, s "")
return skp
}
string SW_VRC="Object Text"
Module currMod = current Module
string getInfo( string inStr)
{
int offsetFromFind, lengthFromFind
string resultString = ""
Object currObj
for currObj in currMod do
{
if ( findPlainText( ( currObj.SW_VRC ""), inStr, offsetFromFind, lengthFromFind, false ) )
{
print currObj.SW_VRC " matches " inStr "\n";
resultString = resultString "\n" currObj.SW_VRC ""
}
}
return resultString
}
string modname = "a,b,cc,ccc,d,e,f"
Skip newLst = split (modname,",")
string inputInfo= "";
find(newLst, 0, inputInfo)
getInfo(inputInfo)
Perhaps you removed too much information when preparing this post?
Or you don't have an entry with the key "0" in newLst? What happens if you start your function with
string inputInfo
inputInfo = "21"
getInfo (inputInfo)
?

Flutter/Dart: Split string by first occurrence

Is there a way to split a string by some symbol but only at first occurrence?
Example: date: '2019:04:01' should be split into date and '2019:04:01'
It could also look like this date:'2019:04:01' or this date : '2019:04:01' and should still be split into date and '2019:04:01'
string.split(':');
I tried using the split() method. But it doesn't have a limit attribute or something like that.
You were never going to be able to do all of that, including trimming whitespace, with the split command. You will have to do it yourself. Here's one way:
String s = "date : '2019:04:01'";
int idx = s.indexOf(":");
List parts = [s.substring(0,idx).trim(), s.substring(idx+1).trim()];
You can split the string, skip the first item of the list created and re-join them to a string.
In your case it would be something like:
var str = "date: '2019:04:01'";
var parts = str.split(':');
var prefix = parts[0].trim(); // prefix: "date"
var date = parts.sublist(1).join(':').trim(); // date: "'2019:04:01'"
The trim methods remove any unneccessary whitespaces around the first colon.
Just use the split method on the string. It accepts a delimiter/separator/pattern to split the text by. It returns a list of values separated by the provided delimiter/separator/pattern.
Usage:
const str = 'date: 2019:04:01';
final values = string.split(': '); // Notice the whitespace after colon
Output:
Inspired by python, I've wrote this utility function to support string split with an optionally maximum number of splits. Usage:
split("a=b=c", "="); // ["a", "b", "c"]
split("a=b=c", "=", max: 1); // ["a", "b=c"]
split("",""); // [""] (edge case where separator is empty)
split("a=", "="); // ["a", ""]
split("=", "="); // ["", ""]
split("date: '2019:04:01'", ":", max: 1) // ["date", " '2019:04:01'"] (as asked in question)
Define this function in your code:
List<String> split(String string, String separator, {int max = 0}) {
var result = List<String>();
if (separator.isEmpty) {
result.add(string);
return result;
}
while (true) {
var index = string.indexOf(separator, 0);
if (index == -1 || (max > 0 && result.length >= max)) {
result.add(string);
break;
}
result.add(string.substring(0, index));
string = string.substring(index + separator.length);
}
return result;
}
Online demo: https://dartpad.dev/e9a5a8a5ff803092c76a26d6721bfaf4
I found that very simple by removing the first item and "join" the rest of the List
String date = "date:'2019:04:01'";
List<String> dateParts = date.split(":");
List<String> wantedParts = [dateParts.removeAt(0),dateParts.join(":")];
Use RegExp
string.split(RegExp(r":\s*(?=')"));
Note the use of a raw string (a string prefixed with r)
\s* matches zero or more whitespace character
(?=') matches ' without including itself
You can use extensions and use this one for separating text for the RichText/TextSpan use cases:
extension StringExtension on String {
List<String> controlledSplit(
String separator, {
int max = 1,
bool includeSeparator = false,
}) {
String string = this;
List<String> result = [];
if (separator.isEmpty) {
result.add(string);
return result;
}
while (true) {
var index = string.indexOf(separator, 0);
print(index);
if (index == -1 || (max > 0 && result.length >= max)) {
result.add(string);
break;
}
result.add(string.substring(0, index));
if (includeSeparator) {
result.add(separator);
}
string = string.substring(index + separator.length);
}
return result;
}
}
Then you can just reference this as a method for any string through that extension:
void main() {
String mainString = 'Here was john and john was here';
print(mainString.controlledSplit('john', max:1, includeSeparator:true));
}
Just convert list to string and search
productModel.tagsList.toString().contains(filterText.toLowerCase())

In dart, split string into two parts using length of first string

I have a string hiWorld and
i want to split this string in two parts hi and World by length of first word hi which is of length 2.
This is what i want to do
List<String> list = ("hiWorld").splitFromLength(2);
I'd use the solution you published shortening up the definition:
List<String> splitStringByLength(String str, int length) =>
[str.substring(0, length), str.substring(length)];
or using an extension method to call the function:
extension on String {
List<String> splitByLength(int length) =>
[substring(0, length), substring(length)];
}
'helloWorld'.splitByLength(5); // Returns [hello, World].
My current solution
List<String> splitStringByLength( String str, int length)
{
List<String> data = [];
data.add( str.substring(0, length) );
data.add( str.substring( length) );
return data;
}
This is my solution which is more generic:
List<String> splitByLength(String value, int length) {
List<String> pieces = [];
for (int i = 0; i < value.length; i += length) {
int offset = i + length;
pieces.add(value.substring(i, offset >= value.length ? value.length : offset));
}
return pieces;
}
And the extension method:
extension on String {
List<String> splitByLength(int length, {bool ignoreEmpty = false}) {
List<String> pieces = [];
for (int i = 0; i < this.length; i += length) {
int offset = i + length;
String piece = this.substring(i, offset >= this.length ? this.length : offset);
if (ignoreEmpty) {
piece = piece.replaceAll(RegExp(r'\s+'), '');
}
pieces.add(piece);
}
return pieces;
}
}
You can use it like:
'HELLO WORLD'.splitByLength(5, ignoreEmpty: true)

Need timezone based on the ISO country code and city in Java

My requirement
::: To find the timezone based on the city and country code both. Please share Is there any way to find it? I don't want to go with city only since one city can exist in two or more countries.
And even on city bases - I can find time zone but not for all cities if i am entering Leeds (UK city) , its giving nothing.
Set<String> availableTimeZones = ZoneId.getAvailableZoneIds();
String cityName = Normalizer.normalize(city, Normalizer.Form.NFKD).replaceAll("[^\\p{ASCII}-_ ]", "")
.replace(' ', '_');
List<String> possibleTimeZones = availableTimeZones.stream().filter(zid -> zid.endsWith("/" + cityName))
.collect(Collectors.toList());
Rough way I found to achieve is -
private static String getSourceLocalTimeZone(String countryCode, String city, String sourceLocalTimeZone) {
String[] timeZones = com.ibm.icu.util.TimeZone.getAvailableIDs(countryCode);
for (String timeZone : timeZones) {
String cityFromTimeZone = null;
String[] value = timeZone.split("/");
if (value != null && value.length > 0) {
cityFromTimeZone = value[value.length - 1].replace("_", " ");
}
if (city!=null && city.matches("(.*)" + cityFromTimeZone + "(.*)")) {
sourceLocalTimeZone = timeZone;
break;
}
}
if (sourceLocalTimeZone == null || (sourceLocalTimeZone.isEmpty())) {
if(timeZones.length>0)
sourceLocalTimeZone = timeZones[0];
}
return sourceLocalTimeZone;
}
Dependency -
<dependency>
<groupId>com.ibm.icu</groupId>
<artifactId>icu4j</artifactId>
<version>4.6</version>
</dependency>

Resources