So I have two classes:
class ConcatTesting{
public static void main(String args[]) throws java.io.IOException{
char inLetter;
String input="";
//This loops takes line of cmd and makes the input variable into that string
for(;;){
inLetter=(char) System.in.read(); //get next char
//if the line hasn't ended then add that char to input
if(inLetter!='\n'){
input+=String.valueOf(inLetter);
}else{
//other wise line has ended so input is finished
break;
}
}
//removes extra white-spaces
input.trim();
//test what input is to make sure it is working correctly
System.out.println(input);
//test concat function
UseConcat.ask(input);
UseConcat.ask("pie");
}
}
class UseConcat{
public static void ask(String str){
System.out.println("What does " + str +" mean?");
}
}
In the program I call the static method UseConcat.ask(String str) twice.
When the argument in the UseConcat.ask(String str) is the input variable, the concatenation seems to fail. However, when I call UseConcat.ask(String str) with the argument being a random string, the concatenation works.
The input variable is the first written line of the cmd converted to a string.
Here is an example image.
As shown in the image, the input variable is set to WOA.
However UseConcat.ask(input); prints out mean?oes WOA intsead of What does WOA mean?
When input is printed: System.out.println(input); it prints WOA as normal.
On the other hand when I call UseConcat.ask("pie"); It works and prints: What does pie mean?
Text lines on Windows (usually for files but always for console window) end with two characters CR (Carriage Return) and LF (Linefeed), which are (most easily) written \r and \n in Java. You remove only the LF and then output "What does WOA{CR} mean?" and the {CR} character moves the cursor to the left margin and causes the " mean?" part to overwrite the "What d" part. Your input.trim() would have fixed this if you hadn't discarded the result. Other platforms are different; Unix uses only LF, and AIUI MacOSX uses only CR.
The Java methods designed to deal with text like Scanner or more basically BufferedReader.readLine() handle any combination of CR and LF for you, with much less code in your application, and more efficiently; repeatedly doing String += letter is horrendously inefficient for long input -- although if you run this program only in a console window that will limit the input line to some not absurdly huge amount.
Related
I'm doing a java project on codeZinger where I need to take in a character value from the scanner and print the ASCII value. So far the code I have works for everything besides the "/n" character. In that case, codezinger returns the error "Exception in thread "main" java.lang.NullPointerException scanner".
I have attached my code below, I've tried everything and it won't work. I'm new to java from c++.
I tried even manually testing for /n using an if statement and that didn't work
public class Solution {
public static void main(String[] args) {
//creating input stream
Scanner input = new Scanner(System.in);
// allows character input from input stream
char charIn = input.findInLine(".").charAt(0);
if(input.equals("\\n"))
{
System.out.print("10");
}
// casts character to type int to get ascii value
int intVal = (int)charIn;
System.out.print(intVal);
}
}
input.equals() method in java never takes its parameter in apostrophe.
Please go through this once :
https://www.jquery-az.com/learn-java-equals-method-5-examples/
Moreover /n doesn't exist in java. If you have to print a line(Give a break) then you have to use System.out.println() , simply, and it will be printed in next line.
Also go through this for printing ASCII value
https://www.javatpoint.com/how-to-print-ascii-value-in-java
int code;
while ((code = System.in.read()) != -1) {
System.out.format("0x%02X ", code);
}
I am using .contains() to check standard input, but it seems not to work for me. For example even if I put hi there as standard input I get:
hi there
nobody likes to eat peas is true
I am expecting to get in addition:
hi there is true
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
String inp = sc.next();
String fixed = "nobody likes to eat peas";
if (inp.contains("hi there")){
System.out.println(inp + " is " + true);
}
if (fixed.contains(" to eat ")){
System.out.println(fixed + " is " + true);
}
}
My Question is: does standard input not work with the .contains() method even though the standard input should match the input using .contains() or is my code wrong?
Scanners work by treating the input as if it is split into chunks, where in between each chunk (called a 'token') is the delimiter.
Out of the box, 'any sequence of whitespace' is the delimiter. So, inp couldn't possibly contain hi there - after all, if you fed that input straight to the program, the first token is hi. That's all that inp would contain. A second call to next() would then return there.
It sounds like you intend for the scanner to treat entire lines as the chunks, and newline symbols as the delimiter.
All you have to do, is tell scanner about it, and all will be well:
Scanner sc = new Scanner(System.in);
sc.useDelimiter("\r?\n");
// rest of your code as normal
NB: \r?\n is regexp for 'an optional CR followed by a required LF'. This catches both unix/macosx style newlines (\n) as well as windows style newlines (\r\n).
I have a question based on character arrays. At the moment I have an input variable that takes the first letter of the word.
char input = scanner.nextLine().charAt(0);
What I want to do is for every enter, I want to put it in an array so that I can keep a log of all the letters that have been retrievied. I am assuming this is using char[] but I am having trouble implementing added each input into the array.
char input = scanner.nextLine().charAt(0);
First thing that's unclear is what Object type is scanner?
But for now I'll assume scanner is the Scanner object from Java.util.Scanner
If that's the case scanner.nextLine() actually returns a String.
String has a charAt() method that will allow you to pick out a character anywhere in the string.
However scanner.nextLine() is getting the entire line, not just one word. So really scanner.nextLine().charAt(0) is getting the first character in the line.
scanner.next() will give you the next word in the line.
If the line contained "Hello World"
scanner.next().charAt(0) would return the character 'H'.
the next call of scanner.next().charAt(0) would then return the character 'W'
public static void main(String[] args) {
boolean finished = false;
ArrayList<Character> firstLetters = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (!finished) {
firstLetters.add(scanner.next().charAt(0));
}
}
The above code sample might give you the behavior you're looking for.
Please note that the while loop will run forever until finished becomes true.
Your program will have to decide when to set finished to true.
AND here's a couple of links about Java's Scanner class
tutorials point
Java Docs
I'm convinced this is a product of how the string.replaceAll() method works, but for some odd reason its making my loop run twice when you type anything with a space in it?
public class TestCode{
public static void main(String[] args) throws IOException{
Scanner scan = new Scanner(System.in);
String input = "";
while(!input.equals("X")){
System.out.println("Prompt user for input");
input = scan.next().toUpperCase();
calculatePolynomial(input);
}
}
public static void calculatePolynomial(String input){
//Clean up entry removing spaces and extracting polynomial names
String calculation = input.replaceAll("\\s", "");
System.out.println(calculation);
}
}
The idea was to have the code run... printing out the message, prompting input. Then process the input and do some stuff. Repeat the process over and over until the sentinel value 'x' is entered.
But when you type input that contains a space it, for some reason, runs the loop as if each word was now separate input. So if you enter three words, it just runs the loop three times instead of once.
I just want the user's input to be without spaces and without a nightmare of logical errors.
When using a Scanner, by default, next() tokenizes the input by whitespace. So if the user enters two words separated by whitespace, your loop will run twice.
To get the entire input in the user's input line, try using the nextLine() method instead.
Sorry if this sounds too simple. I'm very new to Java.
Here is some simple code I was using to examine hasNextLine(). When I run it, I can't make it stop. I thought if you didn't write any input and pressed Enter, you would escape the while loop.
Can someone explain to me how hasNextLine() works in this situation?
import java.util.*;
public class StringRaw {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()) {
String str = sc.nextLine();
}
System.out.print("YOU'VE GOT THROUGH");
}
}
When reading from System.in, you are reading from the keyboard, by default, and that is an infinite input stream... it has as many lines as the user cares to type. I think sending the control sequence for EOF might work, such as CTL-Z (or is it CTL-D?).
Looking at my good-ol' ASCII chart... CTL-C is an ETX and CTL-D is an EOT; either of those should work to terminate a text stream. CTL-Z is a SUB which should not work (but it might, since controls are historically interpreted highly subjectively).
CTRL-D is the end of character or byte stream for UNIX/Linux and CTRL-Z is the end of character or byte stream for Windows (a historical artifact from the earliest days of Microsoft DOS).
With the question code as written, an empty line won't exit the loop because hasNextLine() won't evaluate to false. It will have a line terminator in the input byte stream.
System.in is a byte stream from standard input, normally the console. Ending the byte stream will therefore stop the loop. Although nextLine() doesn't block waiting for input, hasNextLine() does. The only way the code terminates, as designed, is with CTRL-Z in Windows or CTRL-D in UNIX/Linux, which ends the byte stream, causes hasNextLine() not to block waiting for input and to return a boolean false which terminates the while loop.
If you want it to terminate with an empty line input you can check for non-empty lines as part of the loop continuation condition. The following code demonstrates how to change the basic question design that uses hasNextLine() and nextLine() to one that terminates if it gets an empty line or an end of input character (i.e. CTRL-Z in Windows or CTRL-D in UNIX/Linux). The additional code in the while condition uses a feature of assignment operators wherein they can be evaluated like an expression to return the value that was assigned. Since it is a String object, the String.equals() method can be used with the evaluation.
Other additional code just adds some printed output to make what is going on obvious.
// HasNextLineEndDemo.java
import java.util.*;
public class HasNextLineEndDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// this code is a bit gee-whiz
// the assignment expression gets assigned sc.nextLine()
// only if there is one because of the &&
// if hasNextLine() is false, everything after the &&
// gets ignored
// in addition, the assignment operator itself, if
// executed, returns, just like a method return,
// whatever was assigned to str which,
// as a String object, can be tested to see if it is empty
// using the String.equals() method
int i = 1; // input line counter
String str = " "; // have to seed this to other than ""
System.out.printf("Input line %d: ", i); // prompt user
while (sc.hasNextLine() && !(str = sc.nextLine()).equals("")) {
System.out.printf("Line %d: ", i);
System.out.println("'" + str + "'");
System.out.printf("Input line %d: ", ++i);
} // end while
System.out.println("\nYOU'VE GOT THROUGH");
} // end main
} // end class HasNextLineEndDemo
Hit Ctrl + D to terminate input from stdin. (Windows: Ctrl + Z) or provide input from a command:
echo -e "abc\ndef" | java Program
I had a similar problem with a socket input stream. Most solutions I found would still block the execution. It turns out there is a not-blocking check you can do with InputStream.available().
So in this case the following should work:
int x = System.in.available();
if (x!=0) {
//Your code
}
As per my understanding , if you take an example of result set object from JDBC or any iterator then in these cases you have a finite set of things and the iterators each time check whether end of the set has been reached.
However in the above case , their is no way of knowing the end of user input i.e. hasNextLine() has no way of knowing when user wants to terminate, and hence it goes on infinitely.
Best way is to put additional condition on the for loop that checks for some condition inside for loop that fails in the future.
In the above post #Jim 's answer illustrates this.
In fact using hasNextLine() as loop terminator for console input should be discouraged because it will never return false.