String Parse java - java

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.

Related

Splitting a String by two things?

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.

Prevent going to next line after input in console

I have problem with my Java program. I am running the program on the console (CMD).
I would like, after I entered input, that the console stays on the same line (currently it goes to the next line automatically).
This is my current program:
int data[];
Scanner in = new Scanner(System.in);
data = new int[10];
System.out.println("Please Insert Numbers : ");
for(int i=0;i<5;i++)
{
data[i] = in.nextInt();
System.out.print("/t");
}
How can I return to the start of the line instead of going to the next?
Scanner in = new Scanner(System.in);
System.out.println("Please Insert Numbers Separated By Comma: ");
String input = in.nextLine();
input = input.replaceAll("\\s",""); //remove whitespaces
String[] numbers= input.split(","); //build string array using ',' as delimiter between numbers
int data[]= Arrays.asList(numbers).stream().mapToInt(Integer::parseInt).toArray(); //Available since Java8
Like Oscar Martinez said, you could read a string of numbers delimited by white space and build your integer array like this example (before parsing the string to int, I verify if the string can be converted to int or not using a regex ) :
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
int data[];
Scanner in = new Scanner(System.in);
data = new int[10];
System.out.println("Please Insert Numbers : ");
String line = in.nextLine();
String[] stringsNumber = line.split("\\s");
for(int i=0;i<stringsNumber.length;i++){
if(stringsNumber[i].matches("^\\d+$") && i<10){// \\d is a regex to verify if s is a number
data[i]= Integer.parseInt(stringsNumber[i]);
}
}
System.out.println(Arrays.toString(data));
}
}

I need help on my java program

import java.util.Scanner;
public class WordLines {
public static void main(String [] args) {
Scanner sca = new Scanner(System.in);
System.out.println("Enter a sentence");
String s = sca.nextLine();
int count = 0;
for(int j=0; j<s.length(); j++)
System.out.println(s.charAt(j));
}
}
I am trying to write a program that reads certain line from user input and then displays only one word from than sentence to new line at a time.
For example
Input: The hill is very-steep!!
It would print out
The
hill
is
very-steep!!
So far I have done this much!!
You should use method String::split(String) by regular expression "\s+"
String s = sca.nextLine();
System.out.println("Print out:");
for(final String word : s.split("\\s+"))
{
System.out.println(word);
}
Regular expression \\s+ means "One or more whitespaces in sequence"
Read more about regular expressions you can here

Create a new string by Concatenating the last letter of the given set of strings in Java

I need to get a number of words from user, and then output a final word which is formed by the concatenation of the last letters of the words that the user has input.
Here is the code. But how do I bring these letters from the loop and concatenate them?
import java.util.Scanner;
public class newWord {
public static void main(String args[]) {
System.out.println("How many words are you going to enter?");
Scanner num = new Scanner(System.in);
int number = num.nextInt();
System.out.println("Please Enter the "+number+" words:");
for(int n=1;n<=number;n++)
{
Scanner words = new Scanner(System.in);
String thisword = words.nextLine();
char str2 = thisword.charAt(thisword.length()-1);
System.out.println(str2);
}
}
}
Hints only ... since this is obviously a learning exercise of some kind.
But how do I bring these letters from the loop and concatenate them?
You don't. You concatenate them within the loop.
String concatenation can be done using the String + operator or StringBuilder.
The rest is up to you. (Please ignore the dingbats who posted complete solutions and work it out for yourself. It will do you good!)
You can use StringBuilder class to concatenate latest characters in strings with append method.
I believe (correct me if I'm wrong) you are asking to take the last letter of each word and make that into one final word. All you need to do is take each of the final letters and add them to a String to hold them all. After the entire for loop, the variable appended should be your requested word.
public static void main(String args[]) {
System.out.println("How many words are you going to enter?");
Scanner num = new Scanner(System.in);
int number = num.nextInt();
System.out.println("Please Enter the "+number+" words:");
String appended = ""; // Added this
for(int n=1;n<=number;n++)
{
Scanner words = new Scanner(System.in);
String thisword = words.nextLine();
char str2 = thisword.charAt(thisword.length()-1);
appended +=str2; // Added this
System.out.println(str2);
}
}
Just you miss things to keep final value in a place and finally print
public static void main(String args[]) {
System.out.println("How many words are you going to enter?");
Scanner num = new Scanner(System.in);
int number = num.nextInt();
System.out.println("Please Enter the "+number+" words:");
StringBuffer sb = new StringBuffer();
for(int n=1;n<=number;n++)
{
Scanner words = new Scanner(System.in);
String thisword = words.nextLine();
char str2 = thisword.charAt(thisword.length()-1);
sb.append(str2);
}
System.out.println(sb.toString());
}
go through StringBuilder and StringBuffer classes you will get your answer..

compare character with single space java

i'm trying to test a program that will print "space" if the user enters a single space.
but nothings displayed when i hit space then enter. my aim was really to count the number of spaces but i guess i'll just start with this. help me guys, thanks for any help
here's my code
import java.util.Scanner;
public class The
{
public static void main(String args[])throws Exception
{
Scanner scanner = new Scanner(System.in);
String input;
System.out.println("Enter string input: ");
input = scanner.next();
char[] charArray;
charArray = input.toCharArray();
for(char c : charArray)
{
if(c == ' ')
{
System.out.println("space");
}
else
{
System.out.println(" not space");
}
}
}
}
Scanner ignores spaces by default. Use BufferedReader to read input.
By default, Scanner will ignore all whitespace, which includes new lines, spaces, and tabs. However, you can easily change how it divides your input:
scanner.useDelimiter("\\n");
This will make your Scanner only divide Strings at new line, so it will "read" all the space characters up until you press enter. Find more customization options for the delimiters here.
public class CountSpace {
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String word=null;
System.out.println("Enter string input: ");
word = br.readLine();
String data[] ;
int k=0;
data=word.split("");
for(int i=0;i<data.length;i++){
if(data[i].equals(" "))
k++;
}
if(k!=0)
System.out.println(k);
else
System.out.println("not have space");
}
}

Categories