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()’
Related
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).
This is the basic setup for a little console-based quiz game. The answers are numbered. I want the player to give the answer number. If the input is not a number, then my program should give a warning, and wait for proper input.
Instead, what I get (after inserting something that is not a number) is an infinite loop of asking the question and presenting the answers again.
public static void main(String[] args) {
boolean quizActive = true;
while(quizActive) {
presentQuestion();
presentAnswers();
Scanner s = new Scanner(System.in);
if (s.hasNext()) {
String choice = s.next();
if (!NumberUtils.isNumber(choice)) {
presentText("Please insert the answer number.");
} else {
System.out.println("You made a choice!");
checkAnswer(choice);
quizActive = false;
}
s.close();
}
}
}
What am I doing wrong here?
If you do not want to question and answers be presented each time move presentQuestion() and presentAnswers() outside the loop.
But main problem is that you closing Scanner.
Remove s.close(); and move Scanner s = new Scanner(System.in); outside of the loop.
I really don't get the point in using scanner for acquiring user input.
The scanner class is perfect to process structured input from a flat file with known structure like an CSV.
But user input need to deal with all the human imperfection. After all the only advantage you get is not needing to call Integer.parseInt() your yourself at the cost to deal with the not cleared input when scanne.nextInt() fails...
So why not using InputStreamReader aside with a loop suggested by others?
Here an Example :
public class Application {
public static void main(String [] args) {
System.out.println("Please insert the answer number. ");
while (true) {
try {
Scanner in = new Scanner(System.in);
int choice = in.nextInt();
System.out.println("You made a choice!");
checkAnswer(choice);
break;
} catch (Exception e) {
System.out.println("Invalid Number, Please insert the answer number ");
}
}
}
}
You started your Quiz in a loop which is regulated by your quizActive boolean. That means that your methods presentQuestion() and presentAnswers() get called every time the loop starts again.
If you don't input a number but a character for example, your program will run the presentText("Please insert the answer number.") and start the loop again. As it starts the loop again, it will call the methods presentQuestion() and presentAnswers().
To stop that, you can do another loop around the input-sequence. Also your Scanner s = new Scanner(System.in) should be outside the loop. And you shouldn't close your Scanner right after the first input and then open it again!
if you want a code example, please tell me :)
I started doing the CodeAbbey problems last night, they mentioned using stdIn since some the input data is long so copy/paste is much easier than by hand. I had never used the Scanner before so it looked easy enough. I got it working for single line inputs then I got a problem where the input was:
867955 303061
977729 180367
844485 843725
393481 604154
399571 278744
723807 596408
142116 475355
I assumed that nextLine would read each couple, xxxx yyyyy. I put the code in a while loop based on if nextLine is not empty. It runs, but I get weird output, and only after I hit return a few times.
package com.secryption;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Input: ");
Scanner scanner = new Scanner(System.in);
String input = "";
while(!(scanner.nextLine().isEmpty())) {
input = input + scanner.nextLine();
}
String[] resultSet = input.split("\\s+");
for(String s : resultSet) {
System.out.println(s);
}
}
}
I thought I might need something after adding scanner.nextLine() to input. I tried a space and that didn't help. I tried a newline and that didn't make it better.
This "should" put all the numbers in a single array, nothing special. What am I missing with scanner?
EDIT: Ok so #Luiggi Mendoza is right. I found this How to terminate Scanner when input is complete? post. So basically it it working, I just expected it to do something.
The problem is here:
while(!(scanner.nextLine().isEmpty())) {
input = input + scanner.nextLine();
}
Scanner#nextLine reads the line and will continue reading. You're reading two lines and not storing the result of the first line read, just reading and storing the results of the second.
Just change the code above to:
StringBuilder sb = new StringBuilder();
while(scanner.hasNextLine()) {
sb.append(scanner.nextLine()).append(" ");
}
hasNext() is an end of file indicator that terminates by combining keys control d on Mac ox and control z on windows pressing enter won't send the right message
to JVM
I have this code in Eclipse:
package test;
import java.util.Scanner;
class test{
public static void main(String args[]){
Scanner Input = new Scanner(System.in);
if (Input.equals("payday2")){
System.out.println(Input);
}
}
}
Now when I try to start the code/aplication, it terminates itself.
Any ideas why that happens?
You instantiate the Scanner as a variable named Input but never try to read.
Your condition
if (Input.equals("payday2")){
will only check if the Scanner object is equals to the string "payday2" which will always be false, hence the program terminate.
If you want to read, you need to do Input.nextLine().
I dont know about eclipse, but Netbeans would give a warning "equals on incompatible type" with this line.
Also, you should not name your variable with a capital letter as by convention, only class name should start with a capital.
So your fixed program would be
Scanner input = new Scanner(System.in);
String value = input.nextLine();
if ("payday2".equals(value)) {
System.out.println(value);
}
Notice that I kept the string in a variable to display it as displaying input would call toString of the Scanner object which is probably not what you expected.
Notice that I also compared the string in reverse order which is a good practice to avoid NPE even if not really needed here.
You never read input from the Scanner instance so the application doesnt block
String text = input.nextLine();
if ("payday2".equals(text)) {
...
I think you mean to do:
String in = Input.nextLine();
if(in.equals("payday2"))
{
System.out.println(in);
}
Note: in Java 7 you can do the following:
String in = Input.nextLine();
switch(in)
{
case "payday2":
System.out.println(in)
break;
case "payday the heist":
//...
break;
}
Which makes it much easier to manage different input cases.
I'm doing a simple program regarding methods.
But I have one problem. Everything is already working except when looping.
When I choose to loop again. The program skips on inputting the name. And proceeds directly to the year and section.
Here's the code:
public static void main(String[] args) {
do{
System.out.println("Input info:");
name=stringGetter("Name: ");
yearandsec=stringGetter("Year and section: ");
sex_code=charGetter("Sex code: " + "\n" + "[M]" + "\n" + "[F]:");
scode=intGetter("Scholarship code: ");
ccode=intGetter("Course code: ");
units=intGetter("Units: ");
fee_per_unit=doubleGetter("Fee per unit: ");
misc=doubleGetter("Miscellaneous: ");
display();
switches(scode, units, fee_per_unit, misc);
System.out.println("Another?");
dec=rew.nextInt();
}while(dec==1);
}
Here's the method getting the value for name together with the year and section:
public static String stringGetter(String ny){
String sget;
System.out.println(ny);
sget=rew.nextLine();
return sget;
}
I'm really annoyed with this problem, and I don't have any idea on how to fix this. Please help. thanks
Here is a simpler and more complete program that reproduces the error:
public static Scanner rew = new Scanner(System.in);
public static void main(String[] args) {
int dec;
do {
System.out.println("Input info:");
String name=stringGetter("Name: ");
String yearandsec=stringGetter("Year and section: ");
dec=rew.nextInt();
} while(dec==1);
}
public static String stringGetter(String ny){
System.out.println(ny);
return rew.nextLine();
}
The problem is that after calling nextInt() the call to nextLine() reads up to the new line after the int (giving a blank line), not up to the next new line.
If you change dec to a String and change dec=rew.nextInt(); to dec=rew.nextLine(); then it will work fine. Here is a complete example that you can copy and paste into a blank file to see that it works correctly:
import java.util.*;
public class Program
{
public static Scanner rew = new Scanner(System.in);
public static void main(String[] args) {
String dec;
do {
System.out.println("Input info:");
String name = stringGetter("Name: ");
String yearandsec = stringGetter("Year and section: ");
dec = stringGetter("Enter 1 to continue: ");
} while(dec.equals("1"));
}
public static String stringGetter(String ny){
System.out.println(ny);
return rew.nextLine();
}
}
You may also want to consider adding proper parsing and validation to your program. Currently your program will behave in an undesirable way if the user enters invalid data.
The line:
dec = rew.nextInt();
Is reading an int value from the input stream and is not processing the newline character, then when you come back to point where you get the name at which point a new line is still in the Reader's buffer and gets consumed by the stringGetter returning an empty value for name.
Change the line to do something like:
do {
//....
s = stringGetter("Another (y/n)? ");
} while ("y".equals(s));
Well you haven't told us what "rew" is, nor what rew.nextInt() does. Is it possible that rew.nextInt() is waiting for the user to hit return, but only actually consuming one character of the input - so that the next call to rew.nextLine() (for the name) just immediately takes the rest of that line? I suspect that's what's happening because you're using System.in - usually reading from System.in only gives any input when you hit return.
(It's possible that this is also only a problem on Windows - I wonder whether it consumes the "\r" from System.in as the delimiter, leaving "\n" still in the buffer. Not sure.)
To test this, try typing in "1 Jon" when you're being asked whether or not to continue - I think it will then use "Jon" as the next name.
Essentially, I think using Scanner.nextInt() is going to have issues when the next call is to Scanner.nextString(). You might be better off using a BufferedReader and calling readLine() repeatedly, then parsing the data yourself.