Right now I'm working on taking an equation, in "infix" notation and remove any spaces within that string prior to performing the rest of my program. Right now, without any spaces in the string, I receive the correct "Postfix" equation in return. But for some reason I can't seem to remove the spaces of a string that was entered using new Scanner(System.in); prior to performing my "Postfix" method(s). Here is the main method of my file:
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the equation you'd like to evaluate: ");
InfixToPostFix postFixString = new InfixToPostFix();
String infix = keyboard.next();
String newInfix = infix;
//String newInfix = "9 * 5.3";
//String deleteSpaceInInfix = newInfix.replace(" ", "");
//System.out.println("deleteSpaceInInfix: " + deleteSpaceInInfix);
System.out.println("Postfix representation: " + postFixString.InfixToPostfix(infix));
}
Now I've noted out three lines that I tried to test while noting out the lines using the scanner information. In doing so, the result of the lines commented out is: 9*5.3 as expected. So I believe that it is something with the Scanner String object.
The way that you see this method now, when 9 * 5.3 is entered produces only 9. Everything after the first space is dropped.
I've tried to look up possible causes for this problem I'm not understanding and looked it up in the API documentation but haven't seen anything.
I'd appreciate any information in helping me better understand why my Scanner object (String infix = keyboard.next(); in this instance) is being treated differently than a normal String newInfix = "9 * 5.3; object is?
The default delimiter of Scanner is whitespace. Use nextLine() if you want to read an entire line:
Scanner keyboard = new Scanner(System.in);
String infix = keyboard.nextLine();
infix = infix.replace(" ", "");
System.out.println(infix);
Note: There's also hasNextLine() to check if there is another line in the input.
Related
I was taking a coding challenge in which I was to take an integer, a double, and a string from stdin and have this print in stdout. The String had to be a String in which had to include more than a singular word, separated by spaces.
When I inputted the code with only a singular nextLine method below the line with nextDouble, it worked on the challenge website, but didn't work in my editor. Both the site and my editor were using Java 8. I tried to switch between different Java 8 packages in my editor, but it didn't make a difference. What gives?
Normally, from what I gather, you only have to put one dummy nextLine in order to resolve the Java nextInt method not reading newline characters created by hitting "Enter". But in this case, I have to do this twice.
import java.util.*;
public class Solution {
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
// Write your code here.
scan.nextLine();
double d = scan.nextDouble();
scan.nextLine();
scan.nextLine(); //why do I have to include this line in order for spaces to print on my string in stdout?
String s = scan.nextLine();
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
}
I am writing a program where I have to get a user input, saved as a double. The user must be able to put it using both ',' and '.' as a delimiter - however they want. I tried using useDelimiter which works only partially - it does indeed accept both values (e.g 4.5 and 4,5) but when I later use the entered value in a mathematical equation, I get wrong results - it seems to round the user input down to the closest integer and as an effect no matter whether I enter, 4 or 4.5 or 4,5 or 4.8 etc., I get the same result, which is actually only true to 4.
Does anyone happen to know why it doesn't work?
double protectiveResistor=0; //must be a double, required by my teacher
double voltage= 5;
System.out.println("Please provide the resistance.");
Scanner sc= new Scanner(System.in);
sc.useDelimiter("(\\p{javaWhitespace}|\\.|,)");
try
{
protectiveResistor=sc.nextDouble();
}
catch(InputMismatchException exception)
{
System.out.println("Wrong input!");
System.exit(1);
}
if (protectiveResistor<0){
System.err.println("Wrong input!");
System.exit(1);
}
double current = (double)voltage/protectiveResistor;
double power = (double)current*current*protectiveResistor;
Thank you!
The useDelimiter method is for telling the Scanner what character will separate the numbers from each other. It's not for specifying what character will be the decimal point. So with your code, if the user enters either 4.5 or 4,5, the Scanner will see that as two separate inputs, 4 and 5.
Unfortunately, the Scanner doesn't have the facility to let you specify two different characters as decimal separators. The only thing you can really do is scan the two numbers separately, then join them together into a decimal number afterwards. You will want to scan them as String values, so that you don't lose any zeroes after the decimal point.
What useDelimiter() does is split the input on the specified delimiter.
As an example, if you have the input of 4,5, the following code will print "4".
Scanner sc= new Scanner(System.in);
sc.useDelimiter(",");
System.out.println(sc.next())
If you also want to print the second part, after the ',', you need to add another line to get the next value, which would in this example print
"4
5":
Scanner sc= new Scanner(System.in);
sc.useDelimiter(",");
System.out.println(sc.next())
System.out.println(sc.next())
In your code you can do it like this:
Scanner sc= new Scanner(System.in);
sc.useDelimiter("(\\p{javaWhitespace}|\\.|,)");
try
{
String firstPart = "0";
String secondPart = "0";
if (sc.hasNext()) {
firstPart = sc.next();
}
if (sc.hasNext()) {
secondPart = sc.next();
}
protectiveResistor = Double.parseDouble(firstPart + "." + secondPart)
}
// Rest of your code here
What this code does is split the input on whitespace, '.' and ','. For a floating point value you expect one part before the decimal point and one after it. Therefore, you expect the scanner to have split the input in two parts. These two parts are assigned to two variables, firstPart and secondPart. In the last step, the two parts are brought together with the '.' as decimal point, as expected by Java and parsed back into a variable of type Double.
I need to take input in a single line of String which is a combination of String and integers.
I have tried to take the input like this
Scanner in = new Scanner(System.in);
String stringWithoutSpaces=in.nextLine();
But, scanner reads only the first character.
Input String:A 10,B 10,C 10,D 10
Required String:A10,B10,C10,D10
I need this input in a one single line using scanner class.
From what I understand, you are trying to receive the string from the user without storing all the white spaces. If your goal is to remove all the white spaces from the user input string, you can use replaceAll.
Code:
Scanner in = new Scanner(System.in);
System.out.print("Enter input: ");
String input = in.nextLine();
String noWhiteSpaces = input.replaceAll(" ", "");
System.out.println(noWhiteSpaces);
Console:
Enter input: A 10,B 10,C 10,D 10
A10,B10,C10,D10
import java.util.*;
public class Solution {
public static void main(String args[]) {
System.out.println("Hello world");
Scanner scanner=new Scanner(System.in);
String aItems = scanner.nextLine();
System.out.println(aItems);
}
}
This is working fine. I have Provided same input as mentioned by you and it is taking it as one string.Share your complete code or match from this one.
I'm trying to print a string in reverse. i.e.
hello world
should come out as:
dlrow olleh
But the outcome only shows the reverse of the first word. i.e.
olleh
Any thoughts?
import java.util.Scanner;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("Input a string:");
String s;
s = input.next();
String original, reverse = "";
original = s;
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
System.out.println("Reverse of entered string is: "+reverse);
input.close();
}
}
Using input.next() only stores the next word in the variable (only "hello"). Try this:
System.out.println("Input a string:");
String s;
s = input.nextLine();
System.out.println("entered: " + s);
The line
s=input.next()
will only take one word.
So to get the whole line 'hello world', you've to use the nextLine() function.
s = input.nextLine();
Your scanner object returns only the next complete token through the input.next() method. A token is considered complete when there is a whitespace character. Use the nextLine() method of the scanner to get the complete input if you are using multiple words.
new StringBuilder("hello world").reverse().toString();
Maybe much more simpler.
use s.nextline() instead of s.next() as s.next() read only first token string
Scanner sc= new Scanner(System.in);
String s = sc.nextLine();
System.out.println(new StringBuilder(s).reverse().toString());
From Scanner javadoc:
public String next()
Finds and returns the next complete token from this scanner. A
complete token is preceded and followed by input that matches the
delimiter pattern. This method may block while waiting for input to
scan, even if a previous invocation of hasNext() returned true.
What happens is that the token delimiter may not be what you're expecting (newline, for instance).
If you wish your program to read the entire line input by the user, you might want to use Scanner.nextLine(), which will read the entire line input by the user, or maybe Scanner.next(String delimiter), which will allow you to enter the desired token delimiter.
Change s = input.next() to s = input.nextLine()
I can't really write some source code but maybe try using two different inputs. After that add each string to it's own variable. After that, reverse them both and add them together as an output.
I ran into an issue. Below is my code, which asks user for input and prints out what the user inputs one word at a time.
The problem is that the program never ends, and from my limited understanding, it seem to get stuck inside the while loop. Could anyone help me a little?
import java.util.Scanner;
public class Test{
public static void main(String args[]){
System.out.print("Enter your sentence: ");
Scanner sc = new Scanner (System.in);
while (sc.hasNext() == true ) {
String s1 = sc.next();
System.out.println(s1);
}
System.out.println("The loop has been ended"); // This somehow never get printed.
}
}
You keep on getting new a new string and continue the loop if it's not empty. Simply insert a control in the loop for an exit string.
while(!s1.equals("exit") && sc.hasNext()) {
// operate
}
If you want to declare the string inside the loop and not to do the operations in the loop body if the string is "exit":
while(sc.hasNext()) {
String s1 = sc.next();
if(s1.equals("exit")) {
break;
}
//operate
}
The Scanner will continue to read until it finds an "end of file" condition.
As you're reading from stdin, that'll either be when you send an EOF character (usually ^d on Unix), or at the end of the file if you use < style redirection.
When you use scanner, as mentioned by Alnitak, you only get 'false' for hasNext() when you have a EOF character, basically... You cannot easily send and EOF character using the keyboard, therefore in situations like this, it's common to have a special character or word which you can send to stop execution, for example:
String s1 = sc.next();
if (s1.equals("exit")) {
break;
}
Break will get you out of the loop.
Your condition is right (though you should drop the == true). What is happening is that the scanner will keep going until it reaches the end of the input. Try Ctrl+D, or pipe the input from a file (java myclass < input.txt).
it doesn't work because you have not programmed a fail-safe into the code. java sees that the scanner can still collect input while there is input to be collected and if possible, while that is true, it keeps doing so. having a scanner test to see if a certain word, like EXIT for example, is fine, but you could also have it loop a certain number of times, like ten or so. but the most efficient approach is to ask the user of your program how many strings they wish to enter, and while the number of strings they enter is less than the number they put in, the program shall execute. an added option could be if they type EXIT, when they see they need less spaces than they put in and don't want to fill the next cells up with nothing but whitespace. and you could have the program ask if they want to enter more input, in case they realize they need to enter more data into the computer.
the program would be quite simplistic to make, as well because there are a plethera of ways you could do it. feel free to ask me for these ways, i'm running out of room though. XD
If you don't want to use an EOF character for this, you can use StringTokenizer :
import java.util.*;
public class Test{
public static void main(){
Scanner sc = new Scanner (System.in);
System.out.print("Enter your sentence: ");
String s=sc.nextLine();
StringTokenizer st=new StringTokenizer(s," ");//" " is the delimiter here.
while (st.hasMoreTokens() ) {
String s1 = st.nextToken();
System.out.println(s1);
}
System.out.println("The loop has been ended");
}
}
I had the same problem and I solved it by reading the full line from the console with one scanner object, and then parsing the resulting string using a second scanner object.
Scanner console = new Scanner(System.in);
System.out.println("Enter input here:");
String inputLine = console.nextLine();
Scanner input = new Scanner(inputLine);
List<String> arg = new ArrayList<>();
while (input.hasNext()) {
arg.add(input.next().toLowerCase());
}
You can simply use one of the system dependent end-of-file indicators ( d for Unix/Linux/Ubuntu, z for windows) to make the while statement false. This should get you out of the loop nicely. :)
Modify the while loop as below. Declare s1 as String s1; one time outside the loop. To end the loop, simply use ctrl+z.
while (sc.hasNext())
{
s1 = sc.next();
System.out.println(s1);
System.out.print("Enter your sentence: ");
}