Is it possible to create input scanner between String value Java Console? - java

I try to custom my Java Console Application, but I have a problem when I try to show it in Command Prompt will appear input Scanner between String...
int a;
Scanner scan = new Scanner(System.in);
System.out.println("Input value of a: " + (a = scan.nextInt()) + " !");
Anyone can resolve this problem, help me....
thank you

1. First of all, your code runs as it is coded not as it is expected.
As your output is blank, and you are wandering why the prompt has not come yet for asking the user input, then let me tell you one thing, that it is actually asking you to enter some input right there. As soon as, you will enter, you shall see the next line of your output will be..
Input value of a: (whatEverYouEntered)
So your final output would be, (strictly as per your code..)
F:/SMK/oop>javac Main.java
F:/SMK/oop>5 (assumed you type 5 and press enter)
F:/SMK/oop>Input value of a: 5
2. If you think that your code should print Input value of a: line fist and then you will enter the value, then you'll have to make changes as below.
int a;
Scanner scan = new Scanner(System.in);
System.out.print("Input value of a: ");
a = scan.nextInt();
3. And if you are really curious about the reason why your code was behaving like that..then read this..
I would say, change your code as stated below and then run, you might get a hint, otherwise I'll explain later.
public static void main(String[] s) {
int a = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Input value of a: " + (a = new Main().getVal()) + " !");
System.out.println("A = " + a);
}
public int getVal(){
System.out.println("getVal called first.");
return 5;
}
See the output now, it shall be.
F:/SMK/oop>javac Main.java
F:/SMK/oop>getVal called first.
F:/SMK/oop>Input value of a: 5
The reason is, when JVM interprets System.out.println("Input value of a: " + (a = new Main().getVal()) + " !"); this as a single statement, and to execute it must be complete... so how will it get complete?--> By assigning the value of a. and to do so, it must call getVal() function before printing anything, right?
Exactly the same is happening in your code, as your print statement will be executed after the call of scan.nextInt() and nextInt() immediately asks for user input without showing any message in console. And once the input is provided, it will assign the value to a and now the print statement is actually complete and ready to execute. And hence, you would see the print output after the input prompt.
Hope it gives you good idea about java and programming language as well.
Happy coding :)

Related

i want to know how Scanner code works in Java

it's my first time to ask in this community
first, please excuse my poor english in advance
i want to know how Scanner code works
Scanner scanner = new Scanner(System.in); ------Call it "A" for convenience
System.out.print("first number:");
String strNum1 = scanner.nextLine();
System.out.print("second number:"); -----Call it "B" for convenience
String strNum2=scanner.nextLine();
int num1 = integer.parseInt(strNum1); ---- Call it "C" for convenience
int num2 = integer.parseInt(strNum2);
int result = num1 + num2;
System.out.println("Add result: " + result);
Question is about Process of
in the moment i input some number in Console after [code above] is implemented
how [code above] interact(?) with result in Console
For example , when i input code above, run it
and i input some number in console
(1) input 1 -> output in console - "first number:1"
(2) input 3 -> output in console - "first number:1" "Second number:3" "Result: 4"
i can see this
So,
does it mean, when the process up to (1) is input, Progress to "A" shows up?
if it's right, that 'scanner.nextLine()' is input at first as "1" Is the process of (1)
But, although the variable 'strNum1' is not run by 'System.out.println()'
Why can i see this number "1" ??
And,
Why doesn't System.out.print("first number") appears at first,
unless i input some number like "1"
in connection with String strNum1 = scanner.nextLine();
You dont need to get a string from the user and after that parse it to int If you only want to connect two numbers , you can get a int from the user and use with scanner.nextInt() , This will save you code lines and efficiency.
Scanner scanner = new Scanner(System.in);
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
int result = num1 + num2;
System.out.println(num1 + " + " + num2 + " = "+ result);
When you working with string you need to use with scanner.nextLine(); or if you work with a number that start with 0(like maybe id) string is the right thing , because int cant be start with 0.
Okay, let's dig in it (yes, line by line).
You create the Scanner object which takes as input the common input stream provided by the System.in, in that case the console itself.
Then, you are calling System.out.print which is different from System.out.println
System.out.print will simply append to the current state of the console the value you provided
Scanner gets call in using the nextLine() methods, this block the process until some input is inserted inside the console terminal, this is how usually the console works, you input something, press enter and it gets executed. More or less, it's the same in that case, scanner wait until you provide a line separator (press enter).
The exact same stuff happens for the scanner B
The numbers gets parsed and in the end their output is appended to the terminal with System.out.println()
Let's summarise:
Scanner block the thread until it receives an input, then it gets parsed and the normal flow of the routine goes on. A Scanner breaks its input into tokens using a delimiter pattern, in that case of nextLine() the delimiter pattern is the System.lineSeparator();

Is there a way to show an error message while the user has not entered a valid value, within the condition of a while loop

I pretty new to java programming so i was wondering if there is a way to use the condition of a while loop to stop an invalid value being used.
I am writing a program that prompts the user to enter an identification number as an integer then uses a scanner to store that value.
Just wanted to know if this is possible to put something in the condition of the for loop that prints an error message if the enter something like a string, double or char so i dont get the Input Mismatch Exception.
like this:
identification = userId(in); //scanner
while (identification (is not an integer)){
System.out.println("Invalid Value, Please enter an integer");
identification = userId(in);
Even better, you can write:
while ((identification = userId(in)) < 0) {
System.out.println("blah ...");
}
The assumption is that the userIn method returns some negative value if the input is not an integer. You can make the invalid return value whatever you want as long as it is not something that is a valid input.
Some people don't like this style because it has gone out of fashion and they are not used to it; however, it used to be common in C programming and there is nothing about it that is implicitly unclear or bad.
This should do what you are asking. It is basically a while loop that waits until the next input is an integer before continuing the code. The important part is making sure to use in.next() inside the while loop instead of in.nextInt() because the values could be anything.
Scanner in = new Scanner(System.in);
System.out.print("Enter an integer: ");
while (!(in.hasNextInt()))
{
System.out.print("Integer not entered, please enter an integer: ");
in.next();
}
int value = in.nextInt();
System.out.println("The int was " + value);
in.close();

How to print a line and type input in the same line [duplicate]

This question already has answers here:
How to keep my user input on the same line after an output?
(4 answers)
Closed 3 years ago.
I want to print a line like this:
Result: [the result are input here and after click on Enter to continue]
How can I do that?
EDIT:
This is what I want:
Scanner user1 = new Scanner(System.in);
int x = user1.nextInt();
System.out.println("Result: "+x);
But the last line won't print unless I type my input and press Enter.
Using java, you simply could use System.out.print(); to display it in console and after adding the capture info:
System.out.print("Result: ");
int x = user1.nextInt();
This is a very old thread but since there doesn't seem to be an accepted answer, I am answering. Hope it would help someone else...
Here is what you are looking for
Scanner input = new Scanner (System.in);
System.out.print("Enter a number : ");
int num = input.nextInt();
System.out.println("Hello you entered "+num);
Note that when you use println the cursor moves to next line.
If you use just print the next statement continues on the same line.
Hope this one will work. Please try
Input str =scanner. readLine("Result:" ) ;
Int inp =integer.parseInt(star) ;
The last line will not print unless you type an input and press enter as the code is run line by line. First you have to enter the value. Since it runs on console for the next step to be pressed you have to press enter.
So whatever you said will naturally happen and cannot be avoided.
Based on the code snippet you sent there is nothing wrong with the code and the logic in it and these are basic java steps.

Confusion with Scanners (Big Java Ex 6.3)

Currently reading Chapter 6 in my book. Where we introduce for loops and while loops.
Alright So basically The program example they have wants me to let the user to type in any amount of numbers until the user types in Q. Once the user types in Q, I need to get the max number and average.
I won't put the methods that actually do calculations since I named them pretty nicely, but the main is where my confusion lies.
By the way Heres a simple input output
Input
10
0
-1
Q
Output
Average = 3.0
Max = 10.0
My code
public class DataSet{
public static void main(String [] args)
{
DataAnalyze data = new DataAnalyze();
Scanner input = new Scanner(System.in);
Scanner inputTwo = new Scanner(System.in);
boolean done = false;
while(!done)
{
String result = input.next();
if (result.equalsIgnoreCase("Q"))
{
done = true;
}
else {
double x = inputTwo.nextDouble();
data.add(x);
}
}
System.out.println("Average = " + data.getAverage());
System.out.println("Max num = " + data.getMaximum());
}
}
I'm getting an error at double x = inputTwo.nextDouble();.
Heres my thought process.
Lets make a flag and keep looping asking the user for a number until we hit Q. Now my issue is that of course the number needs to be a double and the Q will be a string. So my attempt was to make two scanners
Heres how my understanding of scanner based on chapter two in my book.
Alright so import Scanner from java.util library so we can use this package. After that we have to create the scanner object. Say Scanner input = new Scanner(System.in);. Now the only thing left to do is actually ASK the user for input so we doing this by setting this to another variable (namely input here). The reason this is nice is that it allows us to set our Scanner to doubles and ints etc, when it comes as a default string ( via .nextDouble(), .nextInt());
So since I set result to a string, I was under the impression that I couldn't use the same Scanner object to get a double, so I made another Scanner Object named inputTwo, so that if the user doesn't put Q (i.e puts numbers) it will get those values.
How should I approach this? I feel like i'm not thinking of something very trivial and easy.
You are on the right path here, however you do not need two scanners to process the input. If the result is a number, cast it to a double using double x = Double.parseDouble(result) and remove the second scanner all together. Good Luck!

How to read NumberFormatException error message?

[NOTE] Add to the answer below for other good tips for reading the stack trace
I am getting an error in a program that I am making and I don't know how to fix it.
The user has to choose options from messageboxes, and I have to use the users input to calculate the tuition they will have and their discount.
If I run it!
run: Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:468)
at java.lang.Integer.parseInt(Integer.java:497)
at cabrera.Main.main(Main.java:26)
Java Result: 1
BUILD SUCCESSFUL (total time: 6 seconds)
Code
package cabrera;
/**
*
* #author Owner
*/
import javax.swing.JOptionPane;
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String tuition1 = "", scholar1 = "";
int tuition = 0, scholar = 0;
double discount = 0.0;
JOptionPane.showInputDialog("Input Your Tuition" + tuition1);
JOptionPane.showInputDialog("Choose A Scholar Discount:" + "\n• 1 = 80% " + "\n• 2 = 50%" + "\n• 3 = 25%" + "\n• 4 = No Discount !" + scholar1);
tuition = Integer.parseInt(tuition1);
scholar = Integer.parseInt(scholar1);
JOptionPane.showMessageDialog(null, "Your Total Tuition is: " + tuition);
// If-elseif-else statements based on scholar variable
}
}
How do I fix this error message?
More Info
I recently came across a question that was badly executed. Bad title, bad code, bad question (actually not question, but it could be assumed after some thought). It was from a new SO user.
I wanted to help out and looked at the code for a while. So I edited the post; fixed the code layout, simplified the code, ask the question the OP wanted to ask, etc.... That question is now above; however, the question was put on hold, and I read that questions can take a long time to get off of On Hold. You need something like 5 votes to reopen after it is put on hold. Something I don't see that will happen given that it has been a while since the question was first asked.
I had the answer complete and don't want to waste a good answer
OK, lets look at how to find the issue first!
(3) run: Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:468)
(2) at java.lang.Integer.parseInt(Integer.java:497)
(1) at cabrera.Main.main(Main.java:26)
Java Result: 1
BUILD SUCCESSFUL (total time: 6 seconds)
Look at...
(1), here you can see in Main.java you have an issue on line 26
(2), here you can see more information on the issue. In fact you know you have an issue with Integer.parseInt.
You Don't have to worry about looking at this code, because you don't have a class called Integer with method parseInt in the package java.lang
You just know there is an issue here, and it deals with Integer.parseInt which you do call in your Main.java code!
So we located a possible area to check for the error!
tuition = Integer.parseInt(tuition1);
scholar = Integer.parseInt(scholar1);
(3), here we can see that a NumberFormatException was throw because you gave it (the Integer.parseInt that is) an input of "" (an empty string)
So How do you fix it?
First, you have to look at the input of Integer.parseInt
You can see you pass in tuition1 and scholar1
Look to see where those 2 variable are changed / created.
You can see the last thing you did was create those two variables and assigned them the empty string ("")
There is the problem!!
So you need to assign them a value from the user. That will be done via the showInputDialog(...).
the showInputDialog(...) returns a value that you can use! See here!
All you have to do is...
tuition1 = JOptionPane.showInputDialog("Input Your Tuition");
scholar1 = JOptionPane.showInputDialog("Choose A Scholar Discount: 1... 2... 3... 4...")
Take note that tuition1 and scholar1 should NOT be placed inside of the dialog box when you want to assign them values from the user. You need to have the user input some text into the dialog box, and that value will be returned when you press the OK button. So you have to assign that return value to tuition1 and scholar1
You are getting this exception because user is free to enter an input which is not a number. Integer.parseInt(String s) will throw a NumberFormatException if the argument passed to this method is not a valid number. You can restrict the user to input only numbers by the use of regular expressions. The code is below:
String tuition1="";
int tuition = 0;
boolean numFound =false;
try{
while(!numFound){
tuition1 = JOptionPane.showInputDialog("Input Your Tuition:");
Pattern p = Pattern.compile("[A-Z,a-z,&%$##!()*^]");
Matcher m = p.matcher(tuition1);
if (m.find()) {
JOptionPane.showMessageDialog(null, "Please enter only numbers");
}
else{
tuition = Integer.parseInt(tuition1);
numFound = true;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
This will show a message to user "Please enter only numbers", if he tries to enter something that cannot be converted to integer.

Categories