the method hasNextline() does not work - java

Why doesn't the method hasNextLine() work in Netbeans 8.1? When I press ctrl+z or ctrl+d nothing happens.Thanks
while (kb.hasNextLine()) {
String str = kb.nextLine();//reads the transaction
//isVallid checks if the transaction is valid
if (!isValid(str)) {
throw new IllegalArgumentException("The transaction is not valid");
}
int x, y;//the valuse of x and y
x = getX(str);//recognize and convert the valu of x to integer.
y = getY(str);//recognize and convert the valu of y to integer.
if (buyOrSell(str))//buyOrSell can recongnoize we buy or we sell.
{
justAddToQueueu(myQueue, x, y);// buy
} else {
capitalGain += removeAndCalculate(myQueue, x, y);// sell
}
System.out.println("Please enter the next valid transaction:"
+ "\nor press ctrl+D(ctrl+Z for mac) for exit.");
//for exit you can press ctrl+D (or

Please note that due to the OP creating a moving target question, this answer is no longer applicable.
The reason is once you call the hasNextLine, it passes that and won't go back to it. So the String str=kb.nextLine(); is now looking past that. Also, keep in mind the scope of a variable is inside the brackets it's declared in. So your 'str' isn't accessible in the rest of the program. What you'll have to do is something like this:
String check;
String str = "";
while(true){
check = kb.nextLine();
if (check.matches("^.+"))
str += check;
else
break;
}
Assuming, of course, that the purpose of your while loop was to accumulate all the user input into one String. If not, just remove the + from the +=.
Hope this helps!

I think you cound be use hasNext() rather than hasNextLine(). this is the reason :
You did not specify which version of hasNext() you meant, but basically, as long as there is another token in the data source that the scanner has encapsulated, hasNext() returns true.hasNextLine() on the other hand returns true if there is another line of input available, not just another token.

Related

Recursive java method to parse a string with condition?

Fairly new to java and programming.
Wrote this recursive method, with the objective of asking for a valid string that is both an integer and greater than 0:
private int getDimension(String tableElement){
Integer Input= 0;
System.out.println("Define table rows "+tableElement+"'s."
+"Enter an integer >= 1:");
if( !Reader.hasNextInt() || (Input=Input.parseInt(Reader.nextLine())) <= 0)
return getDimension(tableElement);
return Input;
}
I'd like to stick to using a short and recursive method. It seems to handle the >= 0 logic fine, but blows up when i pass it something other than an integer.
Can someone explain why does that happen to me please?
hasNextInt() doesn't actually consume your input, so you're stuck with the same non-int input on your next call.
Simply spoken, your code doesn't make much (any?) sense.
First of all, there is not really a point in using a recursive method that asks the user for input; and that does not at all do anything about the argument passed to it!
private int getDimension(String tableElement){
Integer Input= 0;
Bad: you keep up mixing int and `Integer. They are not the same. And - read about java coding style guides. Variable names start lower case!
if( !Reader.hasNextInt() || (Input=Input.parseInt(Reader.nextLine())) <= 0)
The first condition gives:
true: when there is NO int ...
false: when there is an int
true leads to: calling your method again without retrieving a value from the reader.
false leads to parsing an int; and checking its value for <= 0.
In one case, you are doing a recursive call; completely ignoring the input you got from the reader; in the other case, you returning 0; or that value in input.
Solution: do something like:
while (true) {
if (reader.hasNextInt()) {
input = reader.nextInt();
break;
}
// there is no number!
read.nextLine(); // consume & throw away non-number!
print "Enter a number"
}
instead.
But seriously: start with throwing away this code.
Final side note: you do Input.parseInt() ... but that is a static method on the Integer class. Just call that as Integer.parseInt() instead! But as said; throw away your code; and learn how to properly use that Scanner class; start reading here.
Because the user can enter anything, you must always read in the line, then compare it:
String num = Reader.nextLine();
return num.matches("[1-9][0-9]*") ? Integer.parseInt(num) : getDimension(tableElement);
Here I've use regex to figure out if it's a positive number; the expression means "a 1-9 char followed by 0 or more of 0-9 chars"

Cannot invoke nextint() on the primitive type int

So I'm learning Java and maybe he didn't explain well enough how scanners work and their limits or maybe I'm looking over something silly... but I'm getting an error on answer = answer.nextInt(); I don't get this error for bomb but it's used pretty much the same way...
Code:
Scanner yesNo = new Scanner(System.in);
Scanner input = new Scanner(System.in);
//
//answer auto set to no. goes to first if, then asks for confirmation,
// then check answer again and go to if, else if or else.
//
int answer = 0;
while (answer != 1)
if (answer == 0) {
System.out.println("In how many seconds should we detonate?");
int bomb = input.nextInt();
//this number will be used later in else if (answer == 1)
System.out.println("Is " + bomb + " seconds correct? 1 for yes, 0 for no");
answer = answer.nextInt();
//error above "Cannot invoke nextint() on the primitive type int"
//Need this to grab a number from user to assign a new value to answer
What do? Thanks.
First of all, you have one Scanner instance with paramether System.in, so it will "record" your keyboard (I assume that yesNo scanner is not used). Then, you have a int variable called "answer" which you assign zero value. Finally you have another variable called "bomb" where you will get your requested value.
As I see in your answers' comments, you're wrong in one thing: "input.nextInt()" is an int value. When you use input.nextInt(), you're sending it a message that says "Hey bro, give me the first int that this stupid human have pressed", but you aren't doing anything more. "input" is only a scanner (as it class name says) that records keystrokes.
So in fact, when you do "input.nextInt()" you'll get an int value, and when you do "bomb = input.nextInt()" or "answer = input.nextInt()" the only thing that you're doing is giving "bomb" or "answer" that int value.
int is a primitive value. It is not an Object and it has no methods.
probably you want to do
answer = input.nextInt();
nextInt() is a function that is part of the object type Scanner. In order to call .nextInt() you must have an object of type Scanner.
So the line "int bomb = input.nextInt();" works fine, since "input" is an object of class Scanner. That function runs and it returns another object, an integer, from input, which is stored in int bomb.
The line "answer = answer.nextInt();" fails to compile because "answer" is an object of class integer. integer does NOT have a function called nextInt().
The appropriate line is "answer = input.nextInt();" using your Scanner object to return another integer to store in "answer".
int answer = 0;
answer = answer.nextInt();
You are calling nextInt() on an int. You need to call it on the scanner:
answer = input.nextInt();

Assigning a String to a String array

I am trying to assign each string a user inputs to a String array. The entire thing is in a for loop and is evaluated by the index of the array. My code is:
String skillAssign[] = new String[100];
for (int i=0; isDone == false; i++)
{
System.out.println(skillAssign[i]);
System.out.println(i);
skillAssign[i] = keyboard.nextLine();
if ((!(skillAssign[i].equalsIgnoreCase("stats"))) && (!(skillAssign[i].equalsIgnoreCase("done"))))
{
assignmentValue = keyboard.nextInt();
if (((skillAssign[i].equalsIgnoreCase("health"))) && (skillPoints - assignmentValue >=0))
{
System.out.println("Added " + assignmentValue + " points to Health!");
skillPoints = (skillPoints - assignmentValue);
newMaxHealth = (assignmentValue + newMaxHealth);
}
//code that evaluates the string located inside the skillAssign[i] for other stats
}
The first string evaluates properly, but when I go to input the second string, I get java.util.InputMisMatchException. How can I get it so it assigns a string to each index of the array inputted by the user, then evaluate it? (I think I got the evaluation part though)
I tried to limit the post to relevant code, so things like isDone are omitted, but isDone is changed to true when done is typed and keyboard is constructed with Scanner keyboard = new Scanner all other variables are set to 0 except for skillPoints
I have tested the abovementioned code, and this is what happens:
We enter the loop.
You are requested to input the first string (through keyboard.nextLine()). I inputted 'health'.
You are requested to input an integer (through keyboard.nextInt()). I inputted '40'.
We re-enter the loop.
You are requested to input an integer (through keyboard.nextInt()).
...
It seems that I'm not asked to input the second string, but instantly the integer.
I do not know why it is, but it looks like nextInt() causes the next nextLine() to be skipped.
Maybe you can replace
assignmentValue = keyboard.nextInt();
with
try {
assignmentValue = Integer.parseInt(keyboard.nextLine());
}
catch (NumberFormatException exc) {
throw new InputMismatchException(exc.getMessage());
}
EDIT
I saw a post on StackOverflow which briefly mentions why nextLine() after nextInt() is skipped.
i believe this is closer to your intention. this way the reference to your keyboard input that nextLine grabs isn't lost on each iteration, but remains preserved in a new String instance. correct?
System.out.println(i);
String getMe = keyboard.nextLine();
skillAssign[i] = new String(getMe);
System.out.println(skillAssign[i]);

Java - appending & passing values

I'm having trouble with passing a string and double to another class because it keeps on crashing at double cost = input.nextDouble();. Also, i was wondering if i am correct with the appending method used in public boolean addPARTDETAILS(String partDESCRIPTION, double partCOST).
For example. If the user enters the parts and cost, i want it to store that in a list and print it out with the cost appended.
Parts used:
brake pads ($50.00)
brake fluids ($25.00)
Note. Assuming that i have declared all variables and the array.
System.out.print("Enter registration number of vehicle");
String inputREGO = input.next();
boolean flag = false;
for(int i=0; i<6; i++){
if(inputREGO.equalsIgnoreCase(services[i].getregoNUMBER())){
System.out.print("Enter Part Description: ");
String parts = input.nextLine();
double cost = input.nextDouble();
services[i].addPARTDETAILS(parts, cost);
//System.out.println(services[i].getregoNUMBER());
flag = true;
}
}if(flag==false);
System.out.println("No registration number were found in the system.");
public boolean addPARTDETAILS(String partDESCRIPTION, double partCOST){
if(partDESCRIPTION == "" || partCOST <= 0){
System.out.println("Invalid input, please try again!");
return false;
}
else{
partCOST=0;
StringBuffer sb = new StringBuffer(40);
String[] parts = new String[50];
for (int i=0;i<parts.length;i++){
partDESCRIPTION = sb.append(partCOST).toString();
}
System.out.println(partDESCRIPTION);
totalPART+=partCOST;
return true;
}
}
it keeps on crashing at double cost = input.nextDouble();.
It is highly unlikely that your JVM is crashing. It is far more likely that you are getting an Exception which you are not reading carefully enough and have forgotten to include in your question.
It is far more likely your code is incorrect as you may have mis-understood how scanner works. And so when you attempt to read a double, there is not a double in the input. I suspect you want to call nextLine() after readDouble() to consume the rest of the the line.
I suggest you step through the code in your debugger to get a better understanding of what it is really doing.
Just to expand a bit on Joop Eggen's and Peter Lawrey's answers because I feel some may not understand.
nextLine doesn't play well with others:
nextDouble is likely throwing a NumberFormatException because:
next, nextInt, nextDouble, etc. won't read the following end-of-line character, so nextLine will read the rest of the line and nextDouble will read the wrong thing.
Example: (| indicates current position)
Start:
|abc
123
def
456
After nextLine:
abc
|123
def
456
After nextDouble:
abc
123|
def
456
After nextLine (which reads the rest of the line, which contains nothing):
abc
123
|def
456
Now nextDouble tries to read "def", which won't work.
If-statement issues:
if(flag==false);
or, rewritten:
if(flag==false)
;
is an if statement with an empty body. Thus the statement following will always execute. And no need to do == false, !flag means the same. What you want:
if (!flag)
System.out.println("No registration number were found in the system.");
String comparison with ==:
partDESCRIPTION == ""
should be:
partDESCRIPTION.equals("")
or better:
partDESCRIPTION.isEmpty()
because == check whether the strings actually point to the exact same object (which won't happen unless you assign the one to the other with = at some point, either directly or indirectly), not just whether the have the same text (which is what equals is for).
Data dependent error.
if(flag==false);
System.out.println("No registration number were found in the system.");
should be (because of the ;):
if (!flag) {
System.out.println("No registration number was found in the system.");
}
And
partDESCRIPTION == ""
should be:
partDESCRIPTION.isEmpty()

Java - how to take undetermined amount of input from user

Java Question:
I want to take an undetermined number of lines of input from a user. For instance, I want the user to continue entering names of people as strings until the user has no other names to enter. I want a user-friendly way to easily indicate that the user has no more input. The loop may look like the following. Any good ideas? Any tips on improving the snippet of code is appreciated as well.
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
while( <user still has more input> ) {
System.out.println("Enter name: ");
String s = read.readLine();
...
<do something with s>;
...
}
thank you!
You need a value that isn't a name but indicates no more data. An empty line would be good. You also want to query if they really want to quit, so in case they accidentally hit return they haven't lost all their data.
name = read.readLine();
Pattern p = Pattern.compile("^\\s$"); //empty line or one of just space chareacters
if (p.matcher(name).matches()) {
System.out.println("Are you done?[y/n]");
if (Pattern.matches("[yY]", read.readLine()) {
//quit your loop
}
}
You could have a boolean variable, such as finished, and check if the user enters 'Q' or another item to indicate that they are finished. If so, set finished to true and you will exit your loop on the next iteration.
Here is a quick example,
boolean finished = false;
String name = null; // initialized to a default value.
System.out.println("Enter 'Q' to quit");
while(!finished) {
System.out.println("Enter name: ");
name = read.readLine(); // moved declaration outside of loop
if(name.equals("Q")) {
finished = true;
}
// do work with name
}
I have also modified your code a bit,
I have added a message to the user to indicate what terminates the input.
I have renamed your variable s to something more meaningful, because you are storing the user's name it seemed reasonable to change it to name.
As a force of habit, I have also initialized my variables with default values, so I assigned the name variable to null. Not totally necessary, but I consider it good practice.
Since I have assigned name a default value, I have moved it outside of your loop.
A simple way is to have users enter an empty line when they are done. You'd just check if line.equals("") or maybe trim it before.

Categories

Resources