I am trying to make a simple code which continously checks the user input on if the number is positive or negative and that it would all be on 2 lines.
First line being the user input and the second line being the output.
I am a beginner in coding and am not such a professional, but I have right now put the Scanner object in a while loop and it checks if the user input is positive. If it's negative then it would stop the program.
import java.util.Scanner;
public class basic {
public static void main(String[] args){
int numb;
Scanner scanner = new Scanner(System.in);
System.out.println("Fill in a random number which ain't negative!");
while((numb = scanner.nextInt()) > 0) {
System.out.println("Again!");
}
{
System.out.println("This is a negative!");
System.exit(1);
}
}
}
What I want to do is that I get this as an output and only on 2 lines:
1 2 3 4 5
Again!
And if I input a negative number on the line that it changes the 'Again!' to 'This is a negative!'
1 2 3 4 5 6 -8
This is a negative!
But with the code I have now I can only get this as an output and would get much more than just 2 lines:
1
Again!
2
Again!
-3
This is a negative!
This is console output so cannot be overwritten.
But if you are really looking to the getting required o/p printed on the console, you can use list and keep pushing digits to it and print all the items of the list.
You could use \r to rewrite the last line. Consider that:
System.out.println("\r"+yourOutput+" > ")
It replaces the last line in the console with this one, that's how loading bars in linux are done by the way :D. Use this method to display your previous inputs/numbers. User input will be in the second line. When user has pressed enter and your program has gotten the user input as string, process it and do the same thing again, this time with yourOutput updated with new info:
System.out.println("\r"+yourOutput+" > ")
Let me welcome you to your first post on StackOverflow!
It is unusual to have java applications clearing the console output. That being said, it is possible, but not without calling OS commands. As mentioned in comments, this is a little beyond beginner material if you do this.
If you want to try it though, as seen here, you can clear the console by executing a native OS command. If you use the below code (copied from the link with a minor edit)
public static void clrscr(){
//Clears Screen in java
try {
if (System.getProperty("os.name").contains("Windows"))
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
else
Runtime.getRuntime().exec("clear");
} catch (Exception e) {}
}
you can call this with clrscr() in your code and you should be able to clear the screen.
Now looking at your code, you won't just be able to slip this in as you will clear the output, thus clearing the past numbers. If you want it the way that you described where you have all the user's output displayed in succession, you'll need to re-print all their entries each time you clear the screen. Thus each time you get a user's input:
You'll want to take that input and add it to a list of numbers
Clear the screen
Output that entire list
Output your evaluation
Let me know if you have questions. :-)
Related
I'm trying to read the Input below but the Scanner doesn't close in Java. From the output, I can see all the inputs are taken inside the string, but the console still shows the program is still running. The red square button is still active. Can you please help?
4
0 3
2 5
4 2
4 0
Scanner scan = new Scanner(System.in);
String input = "";
scan.useDelimiter("\\s*");
while (scan.hasNext()) {
System.out.print(scan.nextInt());
}
The scanner doesn't know when you are going to stop entering data at the console (unlike reading from a file which signals an EOF). So it blocks, waiting for more input. So you have several options.
You can either type Ctrl-D (or what ever your OS requires to signal an EOF).
You can use special input to stop checking (Like a "Done" string) (which means you will need to parse ints if you want integer input too.)
Or you can initially prompt for an integer to indicate how much data to type in via a loop.
You can also do the following:
while (true) {
if (!scan.hasNextInt()) {
// requires a non-empty and non-numeric value.
break;
}
System.out.println(scan.nextInt());
}
But do not close the Scanner after reading from the console. Otherwise you will not be able to reopen it and take input within the same program.
I guess you are new to Java and software development. First, you should check the JavaDoc of the hasNext() method:
https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Scanner.html#hasNext()
Citation: "This method may block while waiting for input to scan."
So you have a continuous loop. If you want to exit your loop, you have to do that explicitly.
to summarise it give me any idea or solution on how I could fix it.
I tried what is given in the code below.
System.out.print("Want to continue Shopping or end your shopping spree and want the bill for your shopping (answer in Y or N)");
String end = sc.next();
if(end =="Y")
System.out.println("hello");
I expect the output hello in the above code, but the actual results are nothing the program just ends.
First of all, I have no idea what your question is about exactly. I can't see any information on which programming language you are using (I suppose Java) or on which operating system you are working.
But I've got an idea what the problem might be: As you are using stdout, I suppose the program happens on a Console or Terminal. And in some environments, the cmd window will close after there program terminated (when working with an IDE like VS Community, which I don't know if you do or not, given no context). If this is the case, "hello" will be printed but you won't see it because the window closes immediately. Try to add some kind of getline at the end and try again.
Supposing sc is a Scanner object.
String comparison must be done with the equal method instead of using == because by doing that you'll compare the object's referer in the memory instead of the String content, try this:
System.out.print("Want to continue Shopping or end your shopping spree and want the bill for your shopping (answer in Y or N)");
String end = sc.next();
if(end.equals("Y")) {
System.out.println("hello");
}
Forgive me if this is not formatted properly, this is my first post. I looked to see if this issue has been found before and I cannot find anyone who has had the same problem I am having.
I am trying to learn Java and cannot for the life of me figure out why my for loops are not outputting the last iteration. I am going through codeabbey's exercises and completed the first two relatively easily. However on the third and fourth problems, I cant get my for loop to output during the last iteration.
I began looking on google and thought I would compare my answer to someone else's. I couldn't see why mine wouldn't work when my code was almost identical to the person I found. So I copied their code and to my surprise I had the same problem when this code also would not output on the last iteration.
So, here is the context.
The website gives you a single number first which is the number of sets of the following numbers. For the third problem, you are to add the sets of two, output the sum followed by a space and loop through the entire batch. For the fourth problem, it is similar where the first number is the number of sets in the batch but you are to compare the two numbers and output the lower number. I will copy my code here for the third problem because the code is simpler.
Here is the code:
import java.util.Scanner;
public class Summation {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for(int i = 0; i < n;i++){
int a = in.nextInt();
int b = in.nextInt();
System.out.println(a + b + " ");
}
}
}
Here is the input you are to copy and paste:
3
100 8
15 245
1945 54
and this is my output:
108 260
So, as you can see we are missing the last output here. I tried changing the for loop to (i < (n+1) ) which still didn't change anything. Any help would be GREATLY appreciated!
Ok so I tested it, and with your numbers, typing them in one by one it works. Copy pasting them, press enter one more time at the end of the copy. If you don't press enter, the scanner thinks you're still adding to the second number so it won't continue until enter is pressed.
I would try using println() as someone else suggested, or calling flush() at the end of the program to make sure something isn't being held in a buffer and not being written.
For a university assignment, from the console I need to be able to read in multiple lines until the user enters Ctrl+Z. That I have no issue with, my problem lies with me being unable to read anything in from System.in after that because it always throws a NoSuchElementException.
The following is the code that I am using for reading in the multiple lines, it was provided by the instructor and so I don't want to change it.
System.out.println("To terminate input, type the correct end-of-file indicator ");
System.out.println("when you are prompted to enter input.");
System.out.println("On UNIX/Linux/Mac OS X type <ctrl> d");
System.out.println("On Windows type <ctrl> z");
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
//Processes input
addFileIntoDirectory(input.nextLine());
}
I understand that this is caused by the Ctrl+Z which equates to an EOF marker, but I don't know how to move past it. No matter how many reads after it I do, regardless of if I have typed more to the console, I just instantly get back another NoSuchElementException.
I have tried having a separate scanner for the menu, closing the scanner above and opening a new one for the menu but neither works.
Is there a way to flush/purge System.in or to reset it?
Please let me know if you would like more details. I have kept the rest of the program vague as it is homework.
EDIT 1: Assignment says "The system provides a textual selection menu as follows, and
runs in loop." Which means the program is not to terminate on Ctrl+Z.
add files from user inputs
display the whole directory
display the size of directory
exit
Please give a selection [0-4]:
The short answer is:
if (!input.hasNext())
input = new Scanner(System.in);
The long answer is:
Below is code, with comments made for removing later, to demonstrate the problem as I understand it and solution.
Note this demo is intended to only work with integer and ^Z inputs.
Copy out the code and save into file HN.java to compile.
Run the program and it will prompt One. Enter integers to your heart's content and exit the loop by entering ^Z.
Two will be displayed followed by the NoSuchElementFound exception in the question. This is because the ^Z remains in the Scanner object input and thereby fails on the nextInt() method.
The first inclination might be to use hasNext() to account for this. So go ahead and uncomment /*Comment1 and recompile and run again.
Now you avoid the exception, but the program blazes through to the end, skipping over the nextInt() originally intended.
So now, uncomment /*Comment2, recompile, and run again. Now the program will wait at the Two prompt as intended. If you enter an integer here, you will proceed to the Three prompt for another entry.
However, if you enter ^Z at Two, again, the program skips the next input. To correct this, uncomment /*Comment3, recompile, and run, and you will see the program works for all combos of integers and ^Z at the various inputs.
Now, you might be wondering why I didn't just reuse the !input.hasNext() solution in /*Comment3. Here's a demo why:
Put back the /*Comment3 and uncomment the /*Comment4, compile and run again. The program works fine and dandy with a ^Z input at the Two prompt, but if you enter an integer there, you'll see the system waiting for input, but there is no prompt Three!
This is because the integer you entered was used in the preceding nextInt() so when the program gets to the hasNext(), it stops and waits for input.
The lesson here is you use the !input.hasNext() when you KNOW you have a ^Z in queue such as when it was used to escape the while loop in this program and the original poster's question. Otherwise the else structure is better suited.
hasNext() is confusing to work with. You have to keep in mind that if nothing is in queue the program will stop and wait for input at that point. This may mess up your prompting if you're not careful.
import java.util.Scanner;
public class HN
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int temp = 0;
System.out.println("One");
while (input.hasNext())
{
temp = input.nextInt();
}
System.out.println("Two");
/*Comment2
if(!input.hasNext()) input = new Scanner(System.in);
Comment2*/
/*Comment1
if (input.hasNext())
Comment1*/
{
temp = input.nextInt();
System.out.printf("%d\n", temp);
}
/*Comment3
else input = new Scanner(System.in);
Comment3*/
/*Comment4
if(!input.hasNext()) input = new Scanner(System.in);
Comment4*/
System.out.println("Three");
if (input.hasNext())
{
temp = input.nextInt();
System.out.printf("%d\n", temp);
}
System.out.println("Four");
}
}
I don't want the answer, I just don't understand how to scan the first number to tell the program how many pairs there are. If you could nudge me in the right direction I would greatly appreciate it.
"Most programs should be able to make some choices and decisions. And we are going to practice conditional programming now.
This is usually done by a kind of if ... else statements which may look like:
IF some_condition THEN
do_something
ELSE
do_other_thing
ENDIF
Depending on your programming language syntax could be different and else part is almost always optional. You can read more in wikipedia article on Conditional statements.
Of two numbers, please, select one with minimum value. Here are several pairs of numbers for thorough testing.
Input data will contain number of test-cases in the first line.
Following lines will contain a pair of numbers to compare each.
For Answer please enter the same amount of minimums separated by space, for example:
data:
3
5 3
2 8
100 15
answer:
3 2 15 "
Firstly, you might want to format your example data a bit. I understood it, but mostly only because I've seen that question format before.
Well, to answer your question but not the question's question (heh), note this:
Following lines will contain a pair of numbers to compare each.
Note the "lines" (plural) and the "each." We're going to need a loop.
We also know each line is a test case.
So modify the instructions:
Loop over the following test cases, comparing each pair
But how many times do we loop?
Input data will contain number of test-cases in the first line
That's the first number.
So here's our code skeleton:
//We can use a Scanner for convenience, it has a readInt() method
Scanner input = new Scanner(/*your input*/);
int numCases = input.readInt();
for(int i = 0; i < numCases; i++) {
int first = input.readInt(); //readInt() will also skip newlines, just a tip.
int second = input.readInt();
/* Compare two inputs, do stuff*/
}
For the record, you could also simply ignore the first input and just loop until there is no more input, but that's sloppy.
First you need to create a Scanner. If you're reading from the console, then this will work:
Scanner scan = new Scanner(System.in);
If you need to read from a file, then you can add this line as well.
System.setIn(new FileInputStream("inputFileName"));
For your specific case, you can do something like:
int numPairs = scan.nextInt();
You can find out more about Scanner and its methods from the Oracle documentation here.