Two inputs before the if statement - java

For the following code I have to put 2 inputs before I get to the ifstatement. Java is quiet new for me so I don't understand what I did wrong. Can anyone help me with solving this problem?
package oefenen;
import java.util.Scanner;
public class oefenen {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String name;
System.out.println("Adin ne?");
// TODO Auto-generated method stub
name = scan.next();
if (scan.next().equals("samet")); {
System.out.println("Merhaba memetin oglu");
}
}
}

You ignore the value of name
And your if statement is actually being ignored as well due to the semicolon at the end
Try this
if (name.equals("samet")) { // remove semicolon

scan.next() will wait for new input each time you call it.
Try using name.equals("samet") instead of scan.next().equals("samet")

From the Scanner.next() doc :
Finds and returns the next complete token from this scanner.
A complete token is preceded and followed by input that matches
the delimiter pattern. This method may block while waiting for input
to scan, even if a previous invocation of hasNext returned
true.
Every time you call next() method, it tries to read an input, in your example you called the method twice that's why you have to enter two inputs before you get to your print statement

Related

Explanation for Java (palindrom string) and method next();

I want to know more about how next method work and Java utill scanner if someone can help me...
Scanner s = new Scanner(System.in);
System.out.println("Unesite string za proveru: ");
if(palindrom(s.next()))
System.out.println("String je palindrom");
else
System.out.println("String nije palindrom");
s.close();
what does next do? and how exactly scanner working also what means method close(); ??
next
public String next()
Finds and returns the next complete token from this scanner.A complete token is preceded and followed by input that matchesthe delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.
Specified by:next in interface IteratorReturns:the next tokenThrows:NoSuchElementException
1 - if no more tokens are availableIllegalStateException
2- if this scanner is closedSee Also:Iterator
example :-
sc = "hello world"
1st time sc.next() output will be "hello"
2nd time sc.next() output will be "world"
close
public void close()
Closes this scanner.
If this scanner has not yet been closed then if its underlying readable also implements the Closeable interface then the readable's close methodwill be invoked. If this scanner is already closed then invoking thismethod will have no effect.
Attempting to perform search operations after a scanner hasbeen closed will result in an IllegalStateException.
Specified by:close in interface CloseableSpecified by:close in interface AutoCloseable
Scanner is a class that parses, and in some cases converts inputs. It uses whitespace as its default delimiter between tokens.
Scanner.next is a method that finds and returns the next token, if there is one.
Scanner.close is a method that releases the resource that the Scanner object is holding, such as an open file.

If statement skips to else

I'm pretty new to Java coming from Python so please pardon my retardedness. I'm trying to make a simple if statement and it won't work :(. It ignores the if statement and goes straight else.
I've tried to use .contains and .equalsIgnoreCase in the if statement.
package me.johnminton;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String species_animal;
System.out.println("Please enter your species: ");
species_animal = user_input.next();
if (species_animal.contains("Erectus")) {
System.out.println("random input statement");
}
else
{
System.out.println("okay");
}
}
}
I'm hoping for it output "random input statement" if I input Erectus in the first input. But instead, it goes straight to the else and outputs "okay".
The next() method just fetches a single word from the scanner, although you can change that behaviour by specifying a delimiter for the scanner.
In your case, if you type Eructussian or something similar, you'll get the result you want, but if you type Home Erectus, you won't.
I suspect you meant to use nextLine() instead of next(), which fetches an entire line of text.
The problem is that your scanner isn’t finishing without getting a return key. Try ‘user_input.nextLine()’ instead of ‘user_input.next()’

while (sc.hasNext) loop java

public class Test1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
System.out.println("First name: ");
String fname =sc.next();
System.out.print("Last name: ");
Lname = sc.next();
}
}
I'm just a beginner at java, hope someone can help me out please. Ignore the last print line i used it so i could understand what exactly i can ouptut.
without the while loop i get the correct output i expect of the code, but once i add the while(sc.hasnext)
a scanner comes before the first name and ignores the scanner that used to input the first name. Does the hasNext() skip scanner?
From the documentation of Scanner.hasNext():
Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.
This means that the while loop which you add will wait until you write something. After you write something, it will be read for first name and it will continue on. When you fill all the data it will wait again to write something and basically loop for ever.
You need other condition for the loop. For example you can use do while and after last data is written, you can ask the user additional question whether he wants to add something else. E.g:
do {
// gather data
System.out.println("Continue ?");
String c = scanner.next();
} while("yes".equals(c))
It's not actually ignoring or skipping the scanner for first name (variable fname), but in your case, when the hasNext() function runs, it puts the input in the buffer and transfers it to the immediate sc.next() or sc.nextLine() (if any of them exists).

Checking hasNextInt() in if and then receive an input

So a simple program would be:
import java.util.*;
public class practice {
static Scanner reader = new Scanner(System.in);
public static void main(String[] args) {
if(reader.hasNextInt()){
int numberEntered = reader.nextInt();
}
}
}
So I have a misunderstanding. hasNextInt() is supposed to check if the next input will be an int or not. I saw this program and I don't understand how the number can be inputed. Because already for getting an input the reader.hasNextInt() needs to be true and the program hasn't got an input. So how will the program get inside the if statement?
The method Scanner#hasNextInt(), in your case, is a blocking method. This means, it is a method which waits and does only return if some conditions are met. It looks something like this:
public boolean hasNextInt() {
...
boolean condition = false;
while(!condition) {
...
}
...
return stuff;
}
To be more precise, the blocking method is Scanner#hasNext(). It is described in its documentation.
If the method blocks or not depends on the Scanners source. If it is, for example System.in, it will wait. If it is just a File, it will read the whole file until its end and then return, no blocking.
So, what happens? The hasNextInt in your if-condition waits for you to enter some input (until you send it by typing Enter). Then the Scanner saves the input inside a buffer. hasNextInt checks the internal buffer but does not delete stuff from the buffer.
Now comes nextInt which reads from the internal buffer and also deletes the stuff inside it. It advances past read input.
You can read it in detail inside the documentation mentioned above.
Things short: Scanner#hasNextInt() waits for input before it returns true or false.

Java String replaceAll method having unusual affect on looping?

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.

Categories

Resources