I would like to split this input: 12132002(177) 012(207.5) 014(184) into two arrays, like this:
num[500] = 12132002,012,014, etc.
and
mark[500] = 177,207.5,184, etc.
The Fact is that I'm accepting values from user like this, where i don't know the total number which he/she will input.
How can I code in Java that kind of splitting? Is it like this?
int number[500];
for(int i=0;i<500;i++) {
number=num.split("//(");
}
To code "that kind of splitting", you will have to:
Declare your variables: String[] number, String[] mark, String num, and String[] numSplit.
Split num by " " (spaces). Assign this to numSplit.
Loop through numSplit from 0 to numSplit.length with i.
Set number[i] to numSplit[i] from the beginning to the first occurrence of a "(".
Set mark[i] to numSplit[i] from one character after the first occurrence of "(" to one character before the end.
Output number and mark
The full code:
String[] number = new String[500]; //1
String[] mark = new String[500];
String num = "12132002(177) 012(207.5) 014(184)";
String[] numSplit = num.split(" "); //2
for(int i = 0; i < numSplit.length; i++) { //3
number[i] = numSplit[i].substring(0, numSplit[i].indexOf("(")); //4
mark[i] = numSplit[i].substring(numSplit[i].indexOf("(") + 1, numSplit[i].length() - 1); //5
}
for(int i = 0; i < number.length; i++) System.out.println(number[i]); //6
for(int i = 0; i < mark.length; i++) System.out.println(mark[i]);
Which outputs:
12132002
012
014
null (x497)
177
207.5
184
null (x497)
Notice that number, mark, and numSplit are String arrays because the leading zeros would be cut off in not otherwise. If you don't mind the leading zeros being cut off then you can change num to an int array and mark to a double array (Because of the decimal in 207.5).
Ok buddy, this could be a solution for your problem. I chose to use the methods I have already created for some other project, but I think those can fit for this purpose as well, instead of using some complex REGEX expression. The output is good, though you have to figure out the way you want to store num and mark variables (I suggest arrays). Hope I helped.
public class Example {
public static void main(String[] args) {
String s = "12132002(177)012(207.5)014(184)";
// output 12132002,012,014 && 177,207.5,184
// it works good with this string as well -> s = "12132002(177)012(207.5)014(184)111(024)";
int numOfParanthesis = numOfParanthesis(s, '(');
String num = "";
String mark = "";
// array which contains positions of (
int[] indexesOpening = indexes(s, '(');
// array which contains positions of )
int[] indexesClosing = indexes(s, ')');
// logic
for(int i = 0; i < numOfParanthesis; i++){
if(i == 0){
num = s.substring(i, indexesOpening[i])+",";
mark = s.substring(indexesOpening[i]+1,indexesClosing[i])+",";
}else if(i!=numOfParanthesis-1){
num += s.substring(indexesClosing[i-1]+1, indexesOpening[i])+",";
mark += s.substring(indexesOpening[i]+1, indexesClosing[i])+",";
}else{
num += s.substring(indexesClosing[i-1]+1, indexesOpening[i]);
mark += s.substring(indexesOpening[i]+1, indexesClosing[i]);
}
}
System.out.println(num);
System.out.println(mark);
}
// returns array of positions for the given character
public static int[] indexes(String s, char c){
int numOfParanthesis = numOfParanthesis(s, c);
int[] indexes = new int[numOfParanthesis];
int delimetar = s.indexOf(c);
for(int i = 0; i < numOfParanthesis; i++){
if(i != -1){
indexes[i] = delimetar;
}
delimetar = s.indexOf(c, delimetar+1);
}
return indexes;
}
// returns how many times a character repeats in a string
public static int numOfParanthesis(String s, char c){
int number = s.indexOf(c);
int i = 0;
while (number >= 0){
number = s.indexOf(c, number+1);
i++;
}
return i;
}
}
Try this:
public class Test {
public static void main(String[] args) {
// Guess this is a string since it is a mix of integers
// and non-integers, characters like '(', ')' and space.
String str = "12132002(177) 012(207.5) 014(184)";
System.out.println("Your string:");
System.out.println("str=\"" + str + "\"");
System.out.println();
// remove all ')' since they will not be used
// using space as a delimiter is enough
String str2 = str.replaceAll("\\)", "");
System.out.println("Your string after removing ')' character:");
System.out.println("str2=\"" + str2 + "\"");
System.out.println();
// Since your input has spaces, we split on spaces
String[] strings = str2.split("\\s+");
System.out.println("Result after splitting str2 by spaces:");
for (String s : strings) {
System.out.println(s);
}
System.out.println();
// Lets make two array
String[] num = new String[500];
String[] mark= new String[500];
// loop strings
int cnt = 0;
for (String s : strings) {
String[] a = s.split("\\("); // a[0]="012", a[1]="207.5"
num[cnt] = a[0];
mark[cnt] = a[1];
cnt++;
}
System.out.println("Result num: ");
System.out.print("num[500] = ");
for(String s : num) {
if(s==null) {break;}
System.out.print(s + ",");
}
System.out.println(" etc.\n");
System.out.println("Result mark: ");
System.out.print("mark[500] = ");
for(String s : mark) {
if(s==null) {break;}
System.out.print(s + ",");
}
System.out.println(" etc.\n");
}
}
Output:
Your string:
str="12132002(177) 012(207.5) 014(184)"
Your string after removing ')' character:
str2="12132002(177 012(207.5 014(184"
Result after splitting str2 by spaces:
12132002(177
012(207.5
014(184
Result num:
num[500] = 12132002,012,014, etc.
Result mark:
mark[500] = 177,207.5,184, etc.
Related
Count vowel in the word for method
public class Methods6 {
public static int countVowel(String words) {
int count = 0;
char[] vowel = {'a', 'e', 'i', 'o', 'u'};
for (int i = 0; i < words.length(); i++) {
char ch = words.charAt(i);
for (char cc : vowel) {
if (ch == cc) {
count++;
}
}
}
return count;
}
**Find max vowel in sentence **
public static String maxVowelWords() {
String sentence = getSentence().toLowerCase();
String words[] = sentence.split(" ");
int maxvowel = CountVowel(words[0]), count;
String maxWord = words[0];
for (int i = 1; i < words.length; i++) {
count = CountVowel(words[i]);
if (count > maxvowel) {
maxvowel = count;
maxWord = words[i] + " ";
}
}
return maxWord;
}}// 2 methods are located in the same Method Class
public class Test {
public static void main(String[] args) {
System.out.println(Methods6.MaxVowelWords());}}
When writing this method, it gives only the first word with the most vowel letters (eg. --------- hello my friend! ----------- just hello, hello and friend -------no!
How can I change the method of this?
Thanks for helps!
The way I interpret this question is that:
Find the word in the supplied String which contains the most vowels
in it.
If one or more words within that very same String contain equal
maximum number of vowels then concatenate the words together
delimited by a whitespace (or whatever).
So, if the String supplied was: "hello my friend" then both words, hello and friend, would be returned from the maxVowelWords() method in the form of (let's say):
hello, friend
Since both hello and friend contain 2 vowels which so happens to be the the max number of vowels in any given word then both words are returned.
If the supplied string however was: "hello my friend - I live on the Mississippi river." then only Mississippi is returned from the method since it is the only word within that String that contains a maximun number of 4 vowels. All other words containing vowels within the string contain a lesser vowel count.
If this is indeed the situation then your method should look something like this:
public static String maxVowelWords() {
String sentence = getSentence();
String words[] = sentence.split(" ");
int maxvowel = 0;
String maxWord = "";
for (int i = 0; i < words.length; i++) {
int count = countVowels(words[i]);
if (count == maxvowel) {
maxvowel = count;
// Ternary Operator is used here to applt the delimiter (", ") if needed,
maxWord += (maxWord.equals("") ? words[i] : ", " + words[i]) + " (" + count + " vowels)";
}
else if(count > maxvowel) {
maxvowel = count;
maxWord = words[i] + " (" + count + " vowels)";;
}
}
return maxWord;
}
Yes, you start your loop from 0 and maxWord String variable should be initialized to hold an empty string (""). Let the for loop do its work. And No, count is not a waste, it's actually a requirement in order to to acquire the maximum vowel count for maxvowel as each string word is placed through the process.
You utilize a method named getSentence() to acquire the String to process and right away you distort that Original String by setting it to all lower case. You really shouldn't do that since the words you return from your maxVowelWords() method will not be the originally supplied words should they happen to have upper case vowels. A small modification to the countVowel() method can take care of that business, for example:
if (Character.toLowerCase(ch) == cc) {
count++;
}
There are few bugs in your code. Try this :
public static String maxVowelWords() {
String sentence = getSentence().toLowerCase();
String words[] = sentence.split(" ");
int maxvowel = 0, count;
String maxWord = "";
for (int i = 0; i < words.length; i++) {
count = countVowel(words[i]);
if (count > maxvowel) {
maxvowel = count;
maxWord = "";
}
if(count == maxvowel){
maxWord = maxWord + words[i]+ " ";
}
}
return maxWord.trim();
}
i am writing a program that must scramble a word. First I read in the word backwards using .reverse. Then I turned the string into a charArray.I am suppose to create a for loop to figure out if the First letter is "A" and if it is then i have to see if the next letter is not an "A". if its not then i am suppose to swap the two letters. If any of the two letters have a;ready been swapped than they cannot be swapped again.
Some examples are
Input: “TAN” Output: “ATN”
Input: “ALACTRIC” Output:“AALCTRIC”
Input: "Fork" Output:"Fork"
Here is my code so far: i cannot figure out what to put in the for loop. Thank you!
import java.util.Scanner;
public class scrambleWordRetry {
public static void main(String[] args)
{
}
public static String scramble( Random random, String inputString)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a word to scramble.");
inputString = scan.nextLine();
char a[] = inputString.toCharArray();
for( int i=0 ; i<a.length-1 ; i++ )
{
}
return inputString;
}
}
I hope this code is useful for you
Scanner x = new Scanner(System.in);
String str = x.next();
System.out.println("Before Swapping" + str);
str = scramble(str);
System.out.println("After Swapping " + str);
}
public static String scramble(String inputString) {
char s[] = inputString.toCharArray();
for (int i = 1; i < s.length; i++) {
if (s[i] == 'A' || s[i] == 'a') {
char temp = s[i - 1];
s[i - 1] = s[i];
s[i] = temp;
}
}
return new String(s);
}
then if you input 'ALACTRIC' the output will be 'AALCTRIC',
'Tan = aTn',
'fork = fork'.
For example, the user enters "1 2 3 4", how do I extract those four numbers and put them into separate spots in an array?
I'm just a beginner so please excuse my lack of knowledge.
for (int i = 0; i < students; i++) {
scanner.nextLine();
tempScores[i] = scanner.nextLine();
tempScores[i] = tempScores[i] + " ";
tempNum = "";
int scoreCount = 0;
for (int a = 0; a < tempScores[i].length(); a++) {
System.out.println("Scorecount " + scoreCount + " a " + a );
if (tempScores[i].charAt(a) != ' ') {
tempNum = tempNum + tempScores[i].charAt(a);
} else if (tempScores[i].charAt(a) == ' ') {
scores[scoreCount] = Integer.valueOf(tempNum);
tempNum = "";
scoreCount ++;
}
}
You can use String.split(String) which takes a regular expression, \\s+ matches one or more white space characters. Then you can use Integer.parseInt(String) to parse the String(s) to int(s). Finally, you can use Arrays.toString(int[]) to display your int[]. Something like
String line = "1 2 3 4";
String[] tokens = line.split("\\s+");
int[] values = new int[tokens.length];
for (int i = 0; i < tokens.length; i++) {
values[i] = Integer.parseInt(tokens[i]);
}
System.out.println(Arrays.toString(values));
Outputs
[1, 2, 3, 4]
If you are very sure that the numbers will be separated by space then you could just use the split() method in String like below and parse individually :
String input = sc.nextLine(); (Use an sc.hasNextLine() check first)
if (input != null || !input.trim().isEmpty()) {
String [] numStrings = input.split(" ");
// convert the numbers as String to actually numbers by using
Integer.parseInt(String num) method.
}
I am supposed to do this :
For an input number print frequency of each number in the order of its occurrence.For eg :
Input:56464
Output:
Number-Frequency
5 -1
6 -2
4 -2
I cannot use any other libraries except java.lang and Scanner to input
So I tried this :
package practice2;
import java.util.Scanner;
public class DigitFrequency2
{
private static Scanner sc;
public static void main(String[] args)
{
sc = new Scanner(System.in);
System.out.println("Enter an integer number");
String sb = sc.nextLine();
System.out.println("Number\tFrequency");
int i,x,c = 0;
for(i=0;i<sb.length();i++)
{
c = 0;
for(x = i+1;x<sb.length();x++)
{
if(sb.charAt(i) == sb.charAt(x) && sb.charAt(i) != '*' && sb.charAt(x) != '*')
{
c++;
sb.replace(sb.charAt(x),'*');
}
}
if(c>0)
{
System.out.println(sb.charAt(i)+" \t"+c);
}
}
}
}
Number Frequency
6 1
4 1
Where am I going wrong please help.
Simple way is this. Won't bother commenting as it is clear whats going on.
Scanner in = new Scanner(System.in);
while (true) {
System.out.print("Input String: ");
String line = in.nextLine();
while (!line.isEmpty()) {
char c = line.charAt(0);
int length = line.length();
line = line.replace(String.valueOf(c), "");
System.out.println(c + " " + (length - line.length()));
}
}
There are few problems with sb.replace(sb.charAt(x),'*');:
replace replaces all characters, not just first one which is why your c can't be grater than 1.
Strings are immutable so since replace can't edit original string, it returns new one with replaced characters which you can store back in sb reference.
Anyway if you would be able to use other Java resources beside java.lang.* or java.util.Scanner simple approach would be using Map which will map character with number of its occurrences. Very helpful here is merge method added in Java 8 allows us to pass key initialValue combination of old and new value
So your code can look like:
String sb = ...
Map<Character, Integer> map = new TreeMap<>();
for (char ch : sb.toCharArray()) {
map.merge(ch, 1, Integer::sum);
}
map.forEach((k, v) -> System.out.println(k + "\t" + v));
Problem is that as mentioned, String is immutable, so String.replace() just returns a new string and it does not (cannot) modify the original. Either you should use StringBuilder, or store the returned value (e.g. sb = sb.replace(sb.charAt(x),'*');).
Going further, since you initialize c with 0, it will stay 0 if there is no other occurrence of the character in question (sb.charAt(i)), so your algorithm won't detect and print digits that occur only once (because later you only print if c > 0).
Counting occurrences (frequency) of characters or digits in a string is a simple operation, it does not require to create new strings and it can be done by looping over the characters only once.
Here is a more efficient solution (one of the fastest). Since digits are in the range '0'..'9', you can create an array in which you count the occurrences, and by looping over the characters only once. No need to replace anything. Order of occurrence is "remembered" in another order char array.
char[] order = new char[10];
int[] counts = new int[10];
for (int i = 0, j = 0; i < sb.length(); i++)
if (counts[sb.charAt(i) - '0']++ == 0)
order[j++] = sb.charAt(i); // First occurrence of the digit
And print in order, until the order array is filled:
System.out.println("Number\tFrequency");
for (int i = 0; order[i] != 0; i++)
System.out.println(order[i] + "\t" + counts[order[i] - '0']);
Example output:
Enter an integer number
56464
Number Frequency
5 1
6 2
4 2
For completeness here's the complete main() method:
public static void main(String[] args) {
System.out.println("Enter an integer number");
String sb = new Scanner(System.in).nextLine();
char[] order = new char[10];
int[] counts = new int[10];
for (int i = 0, j = 0; i < sb.length(); i++)
if (counts[sb.charAt(i) - '0']++ == 0)
order[j++] = sb.charAt(i); // First occurrence of the digit
System.out.println("Number\tFrequency");
for (int i = 0; order[i] != 0; i++)
System.out.println(order[i] + "\t" + counts[order[i] - '0']);
}
Note:
If you would want to make your code safe against invalid inputs (that may contain non-digits), you could use Character.isDigit(). Here is only the for loop which is safe against any input:
for (int i = 0, j = 0; i < sb.length(); i++) {
char ch = sb.charAt(i);
if (Character.isDigit(ch)) {
if (counts[ch - '0']++ == 0)
order[j++] = ch; // First occurrence of ch
}
}
This should be a good code to print frequency using user input:
public static void main(String args[])
{
System.out.println("Please enter numbers ");
String time = in.nextLine(); //USER INPUT
time = time.replace(":", "");
char digit[] = {time.charAt(0), time.charAt(1), time.charAt(2), time.charAt(3)};
int[] count = new int[digit.length];
Arrays.sort(digit);
for (int i = 0; i < digit.length; i++)
{
count[i]++;
if (i + 1 < digit.length)
{
if (digit[i] == digit[i + 1])
{
count[i]++;
i++;
}
}
}
for (int i = 0; i < digit.length; i++)
{
if (count[i] > 0)
{
System.out.println(digit[i] + " appears " + count[i]+" time(s)");
}
}
}
I was asked to create a JOptionPane program which takes as many numbers as the user wants (as a string) and sums them together.
I thought about a pseudo like this:
make int Total = 0
receive input as string X
loop: for (int i = 0; i<=X.length();i++)
create another string S1 which takes the number from the beginning until the first space
convert S1 into a number and add it to Total
subtract S1 from X, and start the loop over
show total
So, my problem is at subtracting the S1 from the X.
My code so far:
public static void main(String[] args) {
int total = 0;
String x = JOptionPane.showInputDialog("enter nums please");
for (int i = 0; i<=x.length();i++){
String s1 = x.substring (0, x.indexOf(' '));
total += Integer.parseInt(s1);
x = x - s1;
}
JOptionPane.showMessageDialog(null, "the sum is" + total); }
If you didn't learn arrays yet, you can implement this like that :
public static void main(String[] args){
int total = 0;
String x = "12 7";
String s1 = x.trim(); //trim the string
while(!s1.isEmpty()){ //loop until s1 is not empty
int index = x.indexOf(' ');//search the index for a whitespace
if(index != -1){ //we found a whitespace in the String !
s1 = s1.substring(0, index); //substract the right number
total += Integer.parseInt(s1);
x = x.substring(index+1).trim(); //update the String x by erasing the number we just added to total
s1 = x; //update s1
} else {
total += Integer.parseInt(s1); //when there is only one integer left in the String
break; //break the loop this is over
}
}
System.out.println(total);
}
This is another interpretation of the method #ZouZou used, but doesn't actually break up your string, it remembers where its already looked, and works its way along the string
int total = 0;
String inputString = "12 7 8 9 52";
int prevIndex = 0;
int index = 0;
while (index > -1) {
index = inputString.indexOf(' ', prevIndex);
if (index > -1) {
total += Integer.parseInt(inputString.substring(prevIndex, index));
prevIndex = index + 1;
} else {
total += Integer.parseInt(inputString.substring(inputString.lastIndexOf(' ')+1));
break;
}
}
System.out.println(total);
Simple solution
int total = 0;
String x = JOptionPane.showInputDialog("enter nums please");
for (String s : x.split("\\s+")){
total += Integer.parseInt(s);
}
System.out.println(total);
Edit: "can't use arrays"- then use a Scanner to scan the String for nextInt()
int total = 0;
String x = JOptionPane.showInputDialog("enter nums please");
Scanner scanner = new Scanner(x); // use scanner to scan the line for nextInt()
while (scanner.hasNext()){
total += scanner.nextInt();
}
System.out.println(total);