String From User Not Removing Spaces

Apr 6, 2014

I'm not sure why but my infix string isn't removing the spaces. Here is the part of the code:

Scanner s = new Scanner(System.in);
System.out.println("Enter Infix express: ");
String infix = s.nextLine();
infix.replaceAll("\s", "").trim();
System.out.println(infix);
InfixtoPostfix convert = new InfixtoPostfix(infix);
String postfix = convert.toPostFix();
System.out.println("Converted Express: " + postfix);

Is there something I'm doing wrong? Here is the output when I run it:

Enter Infix expression:
(7 + x) * (8 – 2) / 4 + (x + 2)
(7 + x) * (8 – 2) / 4 + (x + 2)
Converted Expression: 7 x+ 8 – 2* /4 x 2++

View Replies


ADVERTISEMENT

How To Delimit Spaces In User Input Separating Two Data Types

Jan 17, 2015

I am creating a calculator in which a user will directly input the numbers and the operator...

Here is my code:

int answer = 0;
int num1, num2;
char operator;
System.out.print("Enter calculation: ");
num1 = kb.nextInt();
operator = kb.next().charAt(0);
num2 = kb.nextInt();

The code above will accept the user input when there are spaces like this: 1 + 1

So the program will give an answer which is 2...BUT

if i input 1+1 it will give an error...Exception in thread "main" java.util.InputMismatchException

How can i do that it will separate integer to character? because i set the operator as character....

So that it will accept one digit to several digit numbers... like 500+84 or 1520+872??

View Replies View Related

Splitting A String While Keeping Some Spaces

Jan 21, 2014

I am trying to split a string into a String[] tokens array to declare variables for an object; however, I'm having an issue getting the string to tokenize correctly. Here's an example of the input:

a : 100 : John Smith : 20 Main St.
a : 101 : Mary Jones : 32 Brook Rd.

Here is the basic code I have now, to properly sort each line of text, etc. (without the split() method):

Java Code:

while (scanner.hasNextLine()) {
currentLine = scanner.nextLine();
lineScan = new Scanner(currentLine);
if (currentLine.startsWith("/") || currentLine.trim().isEmpty())
continue;

[Code] ....

I was able to eliminate the comments and identifiers from the text by trimming the first two characters of the string. For the split, I tried String[] tempArray = currentLine.split("s+"); however, that also took the spaces out of the addresses and names...so the results looked like this:

100
John
Smith
20
Main
St.

As you can see, it splits via space regardless, including where I replaced all the :'s with spaces. Is there any way to do this?

View Replies View Related

Dealing With Spaces During Input String Conversion?

Oct 5, 2014

I am working on a small brain teaser project where I am taking a string input from a Scanner, and turning into ascii. The problem comes into play when the string has a space in it, so if the question is what's your name? and you say Michael Jackson, Michael gets converted then Jackson becomes the answer to the next question, rather then the second portion of the current string.

This is an older version of what I'm doing currently, but it had the same basic problem with spaces.I will say I did my current version entirely different.

nner user_input = new Scanner (System.in);
//Creates a string
String favoriteFlick;
System.out.println("Enter the title of your favorite film?");
favoriteFlick = user_input.next();

[Code] .....

View Replies View Related

Removing Whitespace From String?

Mar 25, 2015

For some reason the following code is not removing whitespace from my string:

temp = sb.toString().trim().replace("s+", " ");

I have printed the string before and after the implementation of the methods above and there is not change in the whitespace of the string.

View Replies View Related

Removing A Character From String?

Sep 26, 2014

I am trying to remove a character from string as below

public String reomveChar(String str, int n) {
if(0<=n & n<=(str.length()-1)){
//str.charAt(n)
char o=str.charAt(n);
return str.replace("o","");
//a.replace("o","");
}
return null;
}'

what is the best way to remove it.

If i call like

removeChar("hello", 1) i should see hllo.

When there are more than one way to do a challenge in java which one to choose as best way.

What is the criteria to decide one particular way of writing code is best among say 'n' different number of ways.

View Replies View Related

Quiz Program - Removing Enter Key Space After User Input

Oct 20, 2014

I am writing a short quiz program, and when the user inputs their answer they hit the enter key (the are int). But the last question on my quiz is asking the user to they want to repeat the quiz, but when I run the program, it won't allow me to input any information. I can briefly remember my lecturer saying something about entering in a code after each int the user inputs but I can't remember what it was.

Here is a snippet of my code:

//Question 3
do{
System.out.println("Question 3- What Hollywood actor did Mila Kunis have a baby with recently?");
System.out.println( question3 + ".Ashton Kutcher 2.Bradly Cooper 3.Leonardo Dicaperio h.Get a hint");
answer3 = stdIn.nextInt();
if(answer3 != question3)

[Code] ....

View Replies View Related

String Formatting - Enter Three Positive Integers Separated By Spaces

Sep 18, 2014

double a = scan.nextInt();
double b = scan.nextInt();
double c = scan.nextInt();

//**********************************Equations**********************************
System.out.println ();

double sum = a + b + c;
System.out.printf("Sum = %d", sum);

Heres the error I'm getting

Enter three positive integers separated by spaces, then press enter:
15 20 9

Sum = Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.Double
at java.util.Formatter$FormatSpecifier.failConversion(Unknown Source)
at java.util.Formatter$FormatSpecifier.printInteger(Unknown Source)
at java.util.Formatter$FormatSpecifier.print(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.io.PrintStream.format(Unknown Source)
at java.io.PrintStream.printf(Unknown Source)
at project2.main(project2.java:52)

View Replies View Related

Removing Newline And Tabs From A String

Feb 28, 2007

I have a string from which I need to remove all of the newlines, tabs, and spaces. Here is the code I wrote:

inputString = inputString.replaceAll(" ", "");
inputString = inputString.replaceAll("
", "");
inputString = inputString.replaceAll(" ", "");

It removes the spaces just fine but not the newlines or tabs. How can I do this?

View Replies View Related

Removing Specific Characters From A String

May 7, 2014

I just need to write a simple program/function that replaces certain letters from a string (i.e. censor( "college", "aeiou" ) returns "cllg"). I'm trying to get the code right first, and then write a function for it.I basically just thought that I would iterate over the first string, and once I had the first character, I would then iterate over the second string, to see if the character exists. I'm getting a "dead code" error on my second loop because I put the second "break."

public class ap {
public static void main(String [] args){
String s = "Hello";
String s2 = "aeiou";

[code]....

View Replies View Related

Removing Numeric In String Text

Mar 23, 2015

I want to remove all numeric number in String text
 
String text = She was born in 1964,and now her age is 55;
String delim = ",";
StringTokenizer stringTok = new StringTokenizer(text, delim);
String f1 = "%-40s";
String h1 = String.format(f1, "Token list");
 
[Code] .....

View Replies View Related

Write A String Name Variable To Store Letters / Dotes And Spaces Only In Java?

Apr 5, 2014

I am trying to write a program and the name variable can only store letters,dotes and spaces. But whenever I enter a space, the program doesn't work. Following is my code.

import java.util.Scanner;
import java.util.*;
public class Space {
public static void main(String []args) {
Scanner reader = new Scanner(System.in);

[Code] ....

View Replies View Related

Tokenize A String - Removing Numeric From A TreeSet

Nov 23, 2014

I am using a TreeSet to tokenize a string. The output is sorted with numeric first followed by words

E.g. 13 26 45 and before etc.....................

Is there a tidy way to remove the numeric?

Last bit of my code is :-

// print the words separating them with a space
for(String word : words) {
System.out.print(word + " ");
}
} catch (FileNotFoundException fnfe) {
System.err.println("Cannot read the input file - pass a valid file name");
}

View Replies View Related

Removing Specific Line From Text File That Contains Certain String?

Mar 8, 2014

So basically, if a line in a text file contains a certain string, that specific line will be deleted. It should probably be similair to this method?

Java Code:

/**
* Replace text.
* @param replace
* The text to replace.
* @param replaceWith
* The text to replace with.
*/
public static void replaceSelected(String replace, String replaceWith) {
try {
BufferedReader file = new BufferedReader(new FileReader("data/replacer.txt"));

[code]....

View Replies View Related

Removing Item From String Array - Null Pointer Exception Error

Jun 8, 2014

Question 1: I am working on an assignment where I have to remove an item from a String array (see code below). When I try to remove an item after entering it I get the following error "java.lang.NullPointerException." I am not sure how to correct this error.

Question 2: In addition, I am having trouble figuring out how to count the number of occurrences of each string in the array and print the counts. I've been looking at other posts but they are more advanced and I have not yet learned how to use some of the tools they are referring to.

private void removeFlower(String flowerPack[]) {
// TODO: Remove a flower that is specified by the user
Scanner input=new Scanner(System.in);
System.out.println();
System.out.println("Please enter the name of the flower you would like to remove:

[Code] ....

View Replies View Related

Take Replacement String Entered By User And Print Out New String

May 22, 2014

I'm having trouble with the last few lines of the code. It's supposed to take a replacement string entered by the user and print out the new string. For some reason it's now allowing me to enter a replacement string

import java.util.Scanner;
public class Project02 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a long string: ");
String lString = keyboard.nextLine();

[Code] ....

Output:

Enter a long string: the quick brown fox jumped over the lazy dog
Enter a substring: jumped
Length of your string: 44
Length of your substring: 6
Starting position of your substring in string: 20
String before your substring: the quick brown fox
String after your substring: over the lazy dog
Enter a position between 0 and 43: 18
The character at position 18 is x

Enter a replacement string: Your new string is: the quick brown fox over the lazy dog <------ isn't taking user input

View Replies View Related

How To Add Spaces To A Pattern

Apr 21, 2015

I have created this program that outputs

1
12
123
1234
12345
123456

I tried looking up some ways to create spaces in between each number, but I failed miserably. Here is what I have right now.

public class Iterations {
public static void main(String[] args){
for(int i=1;i<=6;i++)
{
for(int j=1;j<=i;j++)
System.out.print(j);

[Code] ....

View Replies View Related

How To Read A Name Which Has Spaces In Java

May 2, 2014

I do not know how to read a name which has spaces in Java and I wish to learn. The following is my code

import java.util.*;
public class Asking {
public static void main(String []args) {
Scanner reader = new Scanner(System.in);
String [] names = new String[20];
int [] marks = new int[20];

[code]....

View Replies View Related

Digit Separation By Three Spaces Each

Oct 14, 2014

I am having a problem of how to write a program dat will input one number consisting of five digit,separate the number and print the digits separated from one another by three spaces each.. I tried to use divisional and remainder operation but it didn't work.

View Replies View Related

Trim Spaces Between Words

Feb 4, 2014

How can i make sure that when user enter value there is no space between words example :

NEW  YORK MUST BE NEW YORK

View Replies View Related

Get A String From User Input?

Apr 13, 2014

I trying to get this code to get user input instead of reading from a hardcoded array. I'm getting compile errors while trying to get user input. Here's some of the code:

Java Code: // BubbleSort Java
// compile with: javac BubbleSort.java
// run with: java BubbleSort

[Code]....

View Replies View Related

String Manipulation - Getting User ID?

Apr 17, 2014

I have a string and i need to do some manipulation with that. I have tried couple of things but not sure if those are feasible or not. Here is the situation:

uid=aa,bb,ou=people,cn=administrativeldap,cn=punit.punit.a-12-m020.20,o=ttt

I want the value of uid from this string, actually it's user id.

This particular string i want :: aa,bb

Things which i have tried:

I was trying it in this way string start with uid and ends with ou, but in this case user name itself can have ou, so in that case it breaks. Another approach i was thinking of is splitting the string by = which gives me aa'',bb,ou at first position and then i will again split this string to remove ,ou. but i am not sure if this approach is good or not?

View Replies View Related

Padding Will NOT Work - Adding Spaces?

Apr 22, 2014

Why this will not pad?? It keeps displaying normally, even if i add spaces it will not work.

System.out.printf("%-20s%-20s%-20s%-20s", p.getLastName(),
p.getLastName(), p.getSocialSecurityNumber(),p.getAge());
This is what it is printing:

=================== =================== ====================== ===
lastname, firstname, 123-12-1234, 16

The lastname, firstname, 123-12-1234, 16 should be padded and appear with about 20 spaces between them.

View Replies View Related

Deleting Spaces In Java Code

Mar 1, 2014

My method below works fine to print a matrix but when it prints every row, it is printing extra 4 white spaces which is not required. How can I delete those extra spaces at the end? when I use

System.out.print((matrix[i][j] + " ").replaceAll("^s+", ""));

It trims every thing including the spaces I needed for my matrix. So where should I put replaceAll("^s+", "") ?

Java Code:

private static void printMatrix(int[][] matrix) {
System.out.println();
System.out.println("Matrix:");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
} mh_sh_highlight_all('java');

View Replies View Related

Evaluating User Input For String Or Int

Jan 14, 2015

I have to take a users input. The general gist of the problem is I want to convert a decimal number entered by the user inputs into it's binary equivalent....the conversion part I know how to do.

I'm stuck at the user input phase. If the user inputs a decimal number within the correct range (lets say between 0-5000 for this example) the conversion goes ahead as planned and the program outputs on the screen the binary equivalent.

If on the other hand the user inputs a number outside of this range ... OR a String OR and empty space, an error message is given and the user is asked to try again. I don't know how to handle it if the user enters the different types...int or String.

View Replies View Related

Prompt User To Enter A String

Feb 15, 2015

I am suppose to design a problem the prompts the user to enter a String. Based on the input from the user, have the program prompt with a full description of the playing card entered. Below is a table of the notation and meaning:

Notation Meaning
A Ace
2...10 Card Values
J Jack
Q Queen
K King
D Diamonds
H Hearts
S Spades
C Clubs

Use the .charAt(...) to extract each character from the user's input and build a switch statement to determine the full description.

import java.util.Scanner;
public class PlayingCardIdentifier {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a card notation: ");
String s = input.nextLine();

[code]...

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved