I have the following code:
import java.util.Scanner;
public class Chapter11_ProjectPinochle {
public static void main(String[]args) {
Scanner sc=new Scanner(System.in);
String a;
System.out.println("Type in your pinochle deals: ");
a=sc.nextLine();
sc.close();
String[] deals=a.split("");
}
}
I need to split the String I named "a" into a 16 spaced array. But the problem with the splitting is that the input is something like this: ATKQQJ,AKQQ,KQQJN,A. I need to split this into 16 parts and save it to an array I named "deals." I've tried String[] deals=a.split("" && ","); but apparently that isn't valid. I've also tried to split String a into 2 separate arrays and then put them together, but I realized I didn't know how. I want the output to be ["A","T","K","Q","Q","J","A","K","Q","Q","K","Q","Q","J","N","A"] when the input is: ATKQQJ,AKQQ,KQQJN,A. How should I accomplish this?
Try this code
import java.util.Scanner;
public class Chapter11_ProjectPinochle {
public static void main(String[]args) {
Scanner sc = new Scanner(System.in);
String a,b="";
System.out.println("Type in your pinochle deals: ");
a = sc.nextLine();
sc.close();
String[] temp = a.split(",");
for (int i=0; i<temp.length; i++){
for (int j=0; j<temp[i].length(); j++){
b+=temp[i].charAt(j);
}
}
char[] deals=new char[b.length()];
for (int i=0; i<b.length(); i++){
deals[i]=b.charAt(i);
}
}
}
//Split it out into individual characters
System.out.println(Arrays.toString("ATKQQJ,AKQQ,KQQJN,A".replace(",", "").toCharArray()));
//Split it into strings of a single character
System.out.println(Arrays.toString("ATKQQJ,AKQQ,KQQJN,A".replace(",", "").split("")));
Here you go:
String a = "ATKQQJ,AKQQ,KQQJN,A";
// Split the string into comma-separated parts
String[] parts = a.split(",");
//Join those parts into a single string
String whole = String.join("",parts);
//Finally, split it up into individual letters
String[] letters = whole.split("");
Could have also generated whole by removing the commas from a.
Related
I define a token to be one or more consecutive English alphabetic letters. Then, print the number of tokens, followed by each token on a new line.String 's' is composed of English alphabetic letters, blank spaces, and any of the following characters: !,?._'#
Here what I'm doing.
import java.io.*;
import java.util.*;
public class apples {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
scan.close();
String[] splitString = (s.split("[\\s!,?._'#]+"));
System.out.println(splitString.length);
for (String string : splitString) {
System.out.println(string);
}
}
}
When I input a string starting with any of those above characters then my code is counting the character and while printing it gives a empty space, like this.
#dsd sd.sf
4
dsd
sd
sf
What I'm expecting is this.
#dsd sd.sf
3
dsd
sd
sf
Please Help!!
There is no text before the first separator so you get an empty string. I suggest you ignore the first empty string. You could also add a separator at the start so you know there is one you can always ignore. e.g.
String[] split = ("#"+s).split("\\W+");
int words = split.length - 1;
or you can truncate leading non letters
String[] split = s.replaceAll("^\\W+", "").split("\\W+");
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
if (!scan.hasNext())
{
System.out.println(0);
}
else
{
String s = scan.nextLine();
scan.close();
s=s.replaceAll("^\\W+", "");
String[] words = s.split("[\\s',!?._#]+");
int len=words.length;
System.out.println(len);
for(String i:words)
{
System.out.println(i);
}
}
}
}
I have a trouble with my code . I think the problem is about delims=[+,-,*,/]+. when i write if (delims.equals("[+]+")) for ex, it takes only [+]. however delims is not equal just [+]. Ithink you got what i mean. delims is equal [+,-,*,/]+.
public static void main(String[] args) {
System.out.println("Please enter your calculation");
Scanner sc = new Scanner(System.in);
String s=sc.next();
String delims="[+,-,*,/]+";
String[] tokens=s.split(delims);
for(int i=0; i<1; i++){
String s1=tokens[i];
for (int j=1; j<2; j++){
String s2=tokens[j];
double n1=Double.parseDouble(s1);
double n2=Double.parseDouble(s2);
if (delims.equals("[+]+")){
System.out.println(n1+n2);
System.exit(0); }
if (delims.equals("[-]+")){
System.out.println(n1-n2);
System.exit(0);}
if (delims.equals("[*]+")){
System.out.println(n1*n2);
System.exit(0);}
if (delims.equals("[/]+")){
System.out.println(n1/n2);
System.exit(0);
}
}}}}
The delimiter is consumed (thrown away), but you need it.
Try this instead:
String[] tokens = s.replace(" ","").split("\\b");
\b means "word boundary", and digits are considered word characters, so this will work when the number parts of the input are whole numbers.
I added a call to `replace' to remove all spaces.
I'm trying to use Java to solve a simple challenge but I have unsuccessful and I can't find an answer. The idea is that the user enters a string of text, and the program returns the longest word in that string. I can use Scanner to accept the input from the user, and then the .split() method to split the string at the spaces with .split(" ") but I can't figure out how to store the split sentence in an array that I can iterate through to find the longest word. I always get a console output that looks like this:
[Ljava.lang.String;#401a7a05
I have commented out the code that I think should find the longest word so as to focus on the problem of being unable to use Scanner input to create an array of Strings. My code at the moment is:
import java.util.*;
import java.io.*;
class longestWord {
public static void main(String[] args) {
int longest = 0;
String word = null;
Scanner n = new Scanner(System.in);
System.out.println("enter string of text: ");
String b = n.nextLine();
String c[] = b.split(" ");
//for (int i = 0; i <= b.length(); i++) {
// if (longest < b[i].length()) {
// longest = b[i].length();
// word = b[i];
// }
//}
//System.out.println(word);
System.out.println(c);
}
}
That's because you are iterating over the string, not the array, and trying to output the entire array. Change your for loop to use c instead:
for (int i = 0; i < c.length; i++) //In an array, length is a property, not a function
{
if (longest < c[i].length())
{
longest = c[i].length();
word = c[i];
}
}
That should fix your first output. Then you want to change how you output your array, change that to something like this:
System.out.println(Arrays.toString(c));
Which will display the array like so:
[word1, word2, word3, word4]
So you want to get the input as a string and automatically make it an array? You can do that simply by calling the split function after nextLine on the scanner:
String[] wordArray = n.nextLine().split(" ");
there are many mistakes in you code. such a
you were
iterating over string not on array.
if (longest < b[i].length()) as b is your string not array of string
try this it will work it will print the longest word and its size as well.
class Test {
public static void main(String[] args) {
int longest = 0;
String word = null;
Scanner n = new Scanner(System.in);
System.out.println("enter string of text: ");
String b = n.nextLine();
String c[] = b.split(" ");
for (int i = 0; i < c.length; i++) {
if (longest < c[i].length()) {
longest = c[i].length();
word = c[i];
}
}
System.out.println(word);
System.out.println(longest);
}
}
This program should input a dataset of names followed by the name "END". The program should print out the list of names in the dataset in reverse order from which they were entered. What I have works, but if I entered "Bob Joe Sally Sue" it prints "euS yllaS eoJ boB" insead of "Sue Sally Joe Bob". Help!?
import java.util.Scanner;
public class ReverseString {
public static void main(String args[]) {
String original, reverse = "";
Scanner kb = new Scanner(System.in);
System.out.println("Enter a list of names, followed by END:");
original = kb.nextLine();
int length = original.length();
while (!original.equalsIgnoreCase("END") ) {
for ( int i = length - 1; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
original = kb.next();
}
System.out.println("Reverse of entered string is: "+reverse);
}
}
I think that you need to use this simple algorithm. Actually you're not using the proper approach.
Take the whole string which contains all the names separated by spaces;
Split it using as a delimiter the space (use the method split)
After the split operation you will get back an array. Loop through it from the end (index:array.length-1) to the starter element (1) and save those elements in another string
public String reverseLine(String currLine) {
String[] splittedLine = currLine.split(" ");
StringBuilder builder = new StringBuilder("");
for(int i = splittedLine.length-1; i >= 1; i--) {
builder.append(splittedLine[i]).append(" ");
}
return builder.toString();
}
I've supposed that each lines contains all the names separated by spaces and at the end there is a string which is "END"
A quick way, storing the result in the StringBuilder:
StringBuilber reverse = new StringBuilder();
while (!original.equalsIgnoreCase("END")) {
reverse.append(new StringBuilder(original).reverse()).append(" ");
original = kb.next();
}
System.out.println("Reverse: " + reverse.reverse().toString());
Using the approach suggested in the comments above is very simple, and would look something like:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> names = new ArrayList<>();
while (sc.hasNext())
{
String name = sc.next();
if (name.equals("END"))
{
break;
}
names.add(name);
}
Collections.reverse(names);
for (String name: names)
{
System.out.println(name);
}
System.out.println("END");
}
Let the Scanner extract the tokens for you, no need to do it yourself.
I have a question regarding making String arrays in Java. I want to create a String array that will store a specific word in each compartment of the string array. For example, if my program scanned What is your deal? I want the word What and your to be in the array so I can display it later.
How can I code this? Also, how do I display it with System.out.println();?
Okey so, here is my code so far:
import java.util.Scanner;
import java.util.StringTokenizer;
public class OddSentence {
public static void main(String[] args) {
String sentence, word, oddWord;
StringTokenizer st;
Scanner scan = new Scanner (System.in);
System.out.println("Enter sentence: ");
sentence = scan.nextLine();
sentence = sentence.substring(0, sentence.length()-1);
st = new StringTokenizer(sentence);
word = st.nextToken();
while(st.hasMoreTokens()) {
word = st.nextToken();
if(word.length() % 2 != 0)
}
System.out.println();
}
}
I wanted my program to count each word in a sentence. If the word has odd numbers of letter, it will be displayed.
Based on what you've given alone, I would say use #split()
String example = "What is your deal?"
String[] spl = example.split(" ");
/*
args[0] = What
args[1] = is
args[2] = your
args[3] = deal?
*/
To display the array as a whole, use Arrays.toString(Array);
System.out.println(Arrays.toString(spl));
To read and split use String.split()
final String input = "What is your deal?";
final String[] words = input.split(" ");
To print them to e.g. command line, use a loop:
for (String s : words) {
System.out.println(s);
}
or when working with Java 8 use a Stream:
Stream.of(words).forEach(System.out::println);
I agree with what the others have said, you should use String.split(), which separates all elements on the provided character and stores each element in the array.
String str = "This is a string";
String[] strArray = str.split(" "); //splits at all instances of the space & stores in array
for (int i = 0; i < strArray.length(); i++) {
if((strArray[i].length() % 2) == 0) { //if there is an even number of characters in the string
System.out.println(strArray[i]); //print the string
}
}
Output:
This is string
If you want to print the string when it has an odd number of characters, simply change if((strArray[i].length() % 2) == 0) to if((strArray[i].length() % 2) != 0)
This will give you just a as the output (the only word in the string with an odd number of characters).
Let input be your input string. Then:
String[] words = input.split(" ");