I'm trying to take user input and modify it a bit, but ran into an issue when the user inputted multiple lines. To fix this I tried:
public static String getInput() {
Scanner sc = new Scanner(System.in);
String input = "";
System.out.println("Awaiting input...");
if(sc.hasNextLine()) {
System.out.println("Combining Input to One Line...");
while(sc.hasNextLine()) {
//System.out.println(sc.hasNextLine());
//System.out.println("check");
input.concat(sc.nextLine() + " ");
//System.out.println(sc.hasNextLine());
//System.out.println("check2");
//System.out.println("check3");
}
}
sc.close();
return input;
}
It seemed to work until it got to the last line of input, where(after debugging a little) it got stuck trying to read sc.hasNextLine(). However, this is very strange, because I put this exact same code in an online compiler, where it works just fine, except for the fact that the input needs to be beforehand. It doesn't wait until there is any input. I'm not very experienced in Java so I could use some help.
If the infinite loop is your problem, than it can be solved by sending a special EOF marker (Ctrl-D on Unix, usually Ctrl-Z on Windows).
I wrote a simple program to loop and find max of a set of numbers input by the user as:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int currMax, currEl;
currMax = sc.nextInt();
while (sc.hasNext()) {
currEl = sc.nextInt();
currMax = (currEl > currMax ? currEl : currMax);
}
sc.close();
System.out.println(currMax);
} // end function main
}
I am using Eclipse on Windows.
When I run it the first time it runs fine, and considers Ctrl-Z as EOF and exits the loop. But second time onwards, it does not seem to read the EOF. I am unable to explain this, or fix this behavior.. what do you think is going on, and how do I fix it??
Follow-up: The problem happens with Eclipse, and not when I use cmd line. I suspect this is what is happening -- if I use cmd line, I can do Ctrl-Z and then hit Enter, but if I use Eclipse, I believe as soon as I hit Ctrl-Z, s.hasNext() evaluates to false and the above program terminates.
I have a program that is supposed to take inputs from the commandline and direct them to standard input and direct the output to standard output. The code supposed to be entered into the commandline is meant to look as follows:
java package.sub.Calc < input-file > output-file
or
echo some inputs to the calculator | java
package.sub.Calc
But I can't seem to get it to work correctly. The goal is to be able to pass a text file into the program or write your math problems right there on the command line and pipe it in.
The program runs correctly for
java -cp . package.sub.Calc
and then having the user type in their problem and hitting enter.
If I have a file named input.txt and want to call it from the command line and have the answers print out in the commandline (program is designed to System.out.println) how would I be entering this information in?
My current code implements a Scanner for System.in. Would I have to use anything else to get this to work? I am new to running anything in the command prompt and can't seem to get it to work.
Any help is greatly appreciated.
My code:
public static void main(String[] args) {
Calc calc = new Calc();
Scanner sc = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
String input = "";
List<String> strs = new ArrayList<>();
ArrayList<String> tokens;
while (sc.hasNextLine()) {
String line = sc.nextLine().trim();
if (line.isEmpty()) {
for (String s : strs) {
sb.append(s);
input = sb.toString();
}
tokens = new ArrayList<>(Arrays.asList(input.split(" ")));
//call calculate and reset
calc.calculate(tokens);
strs.clear();
tokens.clear();
sb.setLength(0);
input = "";
} else if (line.length() == 1) {
strs.add(" ");
strs.add(line);
strs.add(" ");
//manual user exit case
} else if (line.equals("EXIT")){
System.exit(0);
}else {
strs.add(line);
}
}
}
You seem to have 2 problems.
1) You're including the -cp commandline option when you run the program manually, but not when you try and read from the input. You need it in both cases - that's telling java where to find your class file.
2) The way you are handling your input doesn't match the input you're passing in.
You only call calculate when you receive an empty line ( if(line.isEmpty()) ), but something like
echo some inputs to the calculator | java -cp . package.sub.Calc
doesn't ever produce a blank line.
You either need to do:
printf "%s\n\n" "some inputs to the calculator" | java -cp . package.sub.Calc
or change the condition that triggers a calculate (probably by invoking it outside of the while loop).
your input is received in your main method. public static void main (String[] args). The args array is the array which will receive your input parameters IF you have ran your program as java -cp . <main_class_pat> <arg0> <arg1> ...
Make sure your args array has desired length ... and if so, your input file would be at arg[0]
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.
I am playing with Java and want to do a simple while loop that keeps going until the user presses ctrl+z.
I have something like this:
public static void main(String[] args) {
//declare vars
boolean isEvenResult;
int num;
//create objects
Scanner input = new Scanner(System.in);
EvenTester app = new EvenTester();
//input user number
System.out.print("Please enter a number: ");
num = input.nextInt();
while() {
//call methods
isEvenResult = app.isEven(num);
if(isEvenResult) {
System.out.printf("%d is even", num);
} else {
System.out.printf("%d is odd", num);
}
}//end while loop
}//end main
I tried while( input.hasNext() ) { ... but the code inside the while loop wouldn't execute.
//input user number
System.out.print("Please enter a number: ");
do {
try {
num = input.nextInt();
} catch (Exception e) {
break;
}
// call methods
isEvenResult = app.isEven(num);
if (isEvenResult) {
System.out.printf("%d is even", num);
} else {
System.out.printf("%d is odd", num);
}
} while (true);
When the user writes something non-numeric, the loop breaks.
while (num != 'z')
Although if you are expecting a 'z' why are doing input.getInt()?
You may want to check out the Console class too.
If you want to loop until the user has to force break via Ctrl+Z, then just do while(true). But you want your nextInt() to be inside the loop, and maybe also your prompting statement.
TrueSoft's solution is dead on. The reasons it may not be working for the asker is are kinda outside the scope of the program.
The program works for me: I'm running it under Linux and enter Ctrl-D as the first thing on a line. Ctrl-D is end-of-file for Linux the same way that Ctrl-Z is for Windows. Program stops dead in its tracks, perfectly.
The Windows console (the black DOS box, whatever you want to call it) has a wrinkle: It reads input line-by-line. It won't see the Ctrl-Z until it's read the line, so it needs an Enter keyin before it will see the Ctrl-Z.
I'm unwilling to fire up Windows just to try this, but my guess is that CTRL-Z followed by the Enter key (just like after the number entries) should cause the program to stop cleanly.
There are system-y ways to make a Java program work on a character-by-character basis so you can handle any characters directly and respond immediately to Ctrl-Z. But that's advanced stuff and doesn't belong in a simple programming exercise like this. I think Ctrl-Z / Enter is an acceptable way to have the program end.
You need to implement KeyBindings. Then you can make the determination to exit based off of what keys were pressed.
you are doing the input outside the loop,and it will run for only once.
System.out.print("Please enter a number: ");
num = input.nextInt();
Put your above code inside the loop.
Since you are having a system out inside the loop you will also come to know whether the control went inside the loop, obviously it should.
Also, try
while(true)
I wonder if while() alone is working.
This looks like Exercise 6.16 out of Deitel's book Java How to Program, 9th Edition.
The CTRL-Z charcter does, indeed, end input on a Windows platform just as CTRL-D ends input on most any UNIX or Linux platform.
Also, there are logic errors in the construction of the program that indicate Scanner methods and the System.in byte stream (i.e. the standard input from the console) are not well understood.
In your posted program, the statement:
num = input.nextInt();
executes unconditionally. It will block execution until some kind of input is received. If the input is not an integer, it will throw an exception. If the input received is an integer, then num will be assigned the integer value and the integer in the input stream (input) will be discarded from the input stream. There may be remainaing stuff on the input line up to the end of line, depending on what the user typed in before hitting the enter key that ended the input line and placed it into the System.in byte stream that Scanner is scanning.
If you were to leave your program as written except for putting input.hasNext() into the while statement's test condition, it would block until more input was in the input stream after the integer that nextInt() processed.
Some answer(s) suggest using KeyBindings as a solution. Whilst that may work, it gets into waiting for keypress events at nearly the hardware level and is NOT friendly to platform independence. It is a potential rabbit-hole into Alice's Wonderland for having to figure out all kinds of event processing and the code having to know what platform it is running on. Using the hasNext() boolean false return to indicate the end of the input stream should work on any platform and will avoid potentially non-portable gee-whiz code for processing the keyboard and key presses at nearly the hardware event level.
The following program is one that does what you (and the exercise) intended and will end the input if the user presses CTRL-Z on a Windows platform or a CTRL-D on a UNIX/Linux platform without you having to determine the platform on which the code is executing.
// Exercise 6.16: EvenOrOddTest.java
// Write a method isEven that uses the remainder operator (%)
// to determine whether an integer is even. The method should
// take an integer argument and return true if the integer is
// even and false otherwise. Incorporate this method into an
// application that inputs a sequence of integers (one at a time)
// and determines whether each is even or odd.
import java.util.Scanner;
public class EvenOrOddTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int integer;
System.out.println("Odd even integer test.");
System.out.printf("Input CTRL-Z on Windows or CTRL-D on UNIX/Linux to end input\n"
+ "or an integer between values\n"
+ "%d and %d\n"
+ "to test whether it is odd or even: ",
Integer.MIN_VALUE, Integer.MAX_VALUE);
// the input.hasNext() will block until
// some kind of input, even a CTRL-Z,
// arrives in the stream
// the body of the while loop will execute
// every time input appears for as long as the input
// is not a CTRL-Z
while (input.hasNext()) { // repeat until end of input
// prompt user
// now see if the input we did get is an integer
if (input.hasNextInt()) { // we got an integer...
integer = input.nextInt();
System.out.printf("\n%d is "
+ (EvenOrOdd.isEven(integer) ? "even.\n\n" : "odd.\n\n"), integer);
} else { // we got a non-integer one too large for int
System.out.printf("\nInput %s invalid! Try again...\n\n", input.next());
} // end if...else
// white space (i.e. spaces and tabs) are separators
// next and nextInt get only to the first separator
// so it is possible for the user to enter an integer
// followed by tabs and/or spaces followed by more
// input, integer or not up to the end of the input line
// input.nextLine() flushes everything not processed
// by the nextInt() or next() to the input line end
// won't block execution waiting for input
// if there is nothing left on the input line
input.nextLine();
// prompt for user input again
System.out.printf("Input CTRL-Z to end input\n"
+ "or an integer between values\n"
+ "%d and %d\n"
+ "to test whether it is odd or even: ",
Integer.MIN_VALUE, Integer.MAX_VALUE);
} // end while
} // end main
static boolean isEven(int integer) {
// integer modulus 2 is zero when integer is even
return ((integer % 2) == 0);
} // end isEven
} // end class EvenOrOddTest