Java scanner input if statement [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This line does not work: input=scan.nextLine();
You should give the program the input for the while loop, but it ignores completely this line. I don't know the problem and I am just a beginner. Could you help?
import java.util.*;
public class Fantasy2
{
public static void main ( String[] args )
{
String name;
String input="y";
int strength;
int health;
int luck;
int stats;
Scanner scan = new Scanner(System.in);
System.out.println("Welcome!");
System.out.println("Please enter the name of your character:");
name=scan.nextLine();
while(input.equals("y"))
{
System.out.println("Strength (1-10):");
strength=scan.nextInt();
System.out.println("Health (1-10):");
health=scan.nextInt();
System.out.println("Luck (1-10):");
luck=scan.nextInt();
stats=strength+health+luck;
if(stats>15)
{
System.out.println("You gave your character too much points! Do you want to change that?");
input=scan.nextLine();
}
else
{
System.out.println(name + " has these stats now: Strength:" + strength + ", Health: " + health + ", Luck: " + luck);
input="n";
}
}
System.out.println("Congratulation! You created successful your character!");
}
}

Sorry the statement posted below does not help your original problem but is another problem the line input = scan.nextLine(); works for me fine.
When using Scanner you must call another scan.nextLine(); after you scan.nextInt(); to get the line feed that the method scan.nextInt(); does not get
do this
System.out.println("Strength (1-10):");
strength=scan.nextInt();
System.out.println("Health (1-10):");
health=scan.nextInt();
System.out.println("Luck (1-10):");
luck=scan.nextInt();
stats=strength+health+luck;
scan.nextLine(); <--------- added code

You have to consume the extra new line that nextInt does not consume. Your options are to call another newLine after the last call to nextInt or better yet, read the integer input through nextLine and parse it:
private int readInteger()
{
int option = 0;
try
{
option = Integer.parseInt(input.nextLine());
}
catch (NumberFormatException e)
{
e.printStackTrace();
}
return option;
}
...
System.out.println("Strength (1-10):");
strength = readInteger();
System.out.println("Health (1-10):");
health = readInteger();
System.out.println("Luck (1-10):");
luck = readInteger();

With the Scanner
Scanner scan = new Scanner(System.in);
and the methods ( read API for detail)
next() - would read next characters until it found space ( or the delimiter used. by default space) and return String.
nextInt() - would read next characters until it found space ( or the delimiter used. by default space) and convert it into int and return.
Note** if you give input as 'xyz' you will get exception and your program would terminate.
if you give 5 7 for answer (Strength (1-10):) as per your program it would read 5 as strength and 7 as health. and will ask for luck.
nextLine() would read all characters until the end of line found ( while you enter in keyboard).
So the ideal implementation to avoid issues .
You can use nextLine and convert into int if not say as error and ask to enter correct value.
System.out.println("Strength (1-10):");
String str=scan.nextLine();
while (!isNumeric(str)){
System.out.println("Enter Valid Number Strength (1-10):");
str=scan.nextLine();
}
strength = Integer.parseInt(str);
public static boolean isNumeric(String str)
{
return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
}
For example , when you call luck=scan.nextInt(); users enters 6 and enter key . 6 will capture by nextInt() and the enter key would capture by input=scan.nextLine(); .
So in order to get next input you have to ask scan.nextLIne() again like
luck=scan.nextInt();
scan.nextLIne();

Try to use this code instead of your while cycle:
boolean flag=true;
while(flag)
{
System.out.println("Strength (1-10):");
int strength=Integer.parseInt(scan.nextLine());
System.out.println("Health (1-10):");
int health=Integer.parseInt(scan.nextLine());
System.out.println("Luck (1-10):");
int luck=Integer.parseInt(scan.nextLine());
int stats=strength+health+luck;
if(stats>15)
{
System.out.println("You gave your character too much points! Do you want to change that?");
input=scan.nextLine();
}
else
{
System.out.println("has these stats now: Strength:" + strength + ", Health: " + health + ", Luck: " + luck);
input="n";
}
if(input.equals("n"))
flag = false;
}
System.out.println("Congratulation! You created successful your character!");
I don't know if this is a better way of doing it but give it a try.
Hope this helps.

Related

How do I get the Scanner in java to read a string? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How would I get my program to quit when the user enters q?
Is there something wrong with the scanner?
My code
import java.util.*;
public class Main{
public static void main(String []args){
int age;
Scanner scan = new Scanner(System.in);
System.out.println("Enter your age, or enter 'q' to quit the program.");
age = scan.nextInt();
if(age.equals("q") || age.equals("Q")){
return 0;
}
System.out.println("Your age is " + age);
}
}
I can see mainly two problems in your code:
It lacks a loop to repeat asking for age again. There can be many ways (for, while, do-while) to write a loop but I find do-while most appropriate for such a case as it always executes the statements within the do block at least once.
age is of type, int and therefore it can not be compared with a string e.g. your code, age.equals("q") is not correct. A good way to handle such a situation is to get the input into a variable of type, String and check the value if it should allow/disallow processing it (e.g. trying to parse it into an int).
Note that when you try to parse a string which can not be parsed into an int (e.g. "a"), you get a NumberFormatException which you need to handle (e.g. show an error message, change some state etc.).
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int age;
String input;
Scanner scan = new Scanner(System.in);
boolean valid;
do {
// Start with the assumption that input will be valid
valid = true;
System.out.print("Enter your age, or enter 'q' to quit the program: ");
input = scan.nextLine();
if (!(input.equals("q") || input.equals("Q"))) {
try {
// Try to parse input into an int
age = Integer.parseInt(input);
System.out.println("Your age is " + age);
} catch (NumberFormatException e) {
System.out.println("Invalid input");
// Change the value of valid to false
valid = false;
}
}
} while (!valid || !(input.equals("q") || input.equals("Q")));
}
}
A sample run:
Enter your age, or enter 'q' to quit the program: a
Invalid input
Enter your age, or enter 'q' to quit the program: 12.5
Invalid input
Enter your age, or enter 'q' to quit the program: 14
Your age is 14
Enter your age, or enter 'q' to quit the program: 56
Your age is 56
Enter your age, or enter 'q' to quit the program: q

Currency Exchanger

I am trying to write a code that will exchange between AED,MYR,USD. I got to the following code and I cant fix the error.
It looked like the system.in isn't closing so I wrote the inclose(). But I still get the same results.
My problem might be something else and am not seeing it.
EDIT: this is the current code with changes.
import java.util.Scanner;
public class CurrencyConverter
{
protected static long amount;
static long Namount ;
static int commesion;
static String to;
public static void main( String[] args )
{
CurrencyConverterM MSg=new CurrencyConverterM();
CurrencyConverterM account1 = new CurrencyConverterM( );
String from ;
for(int i=0 ;i<3; i++)
{
System.out.println("Please enter your currency (USD, AED, or MYR only): ");
Scanner in = new Scanner( System.in );
from = in.nextLine();
System.out.println("What currency do you want?: ");
String to = in.nextLine();
System.out.println("How much you want to convert?: ");
amount= in.nextLong();
//in.close();
if ("USD".equals(from)) {
amount=((long) (amount*0.27));
amount=account1.converter(to, amount);
}
else if ("MYR".equals(from)) {
amount=((long) (amount * 1.14));
amount =account1.converter(to, amount);
}
else {
if(mmount >= 900) {
Namount = (amount-50);
commesion =50;
}
else
{
Namount = (amount - 10);
commesion = 10;
}
}
System.out.println(MSg.getMsg());
}
}
}
the output should be as follows.
asking for current currency:
asking to what currency u want it:
asking about the amount.
am converting any amount to AED so I make it the main unit, then converting to the wished unit.
EDIT
public class CurrencyConverterM extends CurrencyConverter
{
long am;
#SuppressWarnings("static-access")
long converter (String to,long amount)
{
if ("MYR".equals(to)) {
am=(super.amount*=0.88);
}
else if ("MYR".equals(to)) {
am=(super.amount*=3.7);
}
return am ;
}
#SuppressWarnings("static-access")
public String getMsg()
{
return ("Thank you. The converted amount is "+(super.amount) + ". We will take" +super.commesion + " commission, and you will get "+ super.Namount);
}
}
before it didn't read the user's input, now its not converting the values.
I tried to print out my vales after each calculation but it looks like that the variable am is not being calculated correctly and its being multiplied by a 0 or divided by one ( the last result is always 0 ) but the amount that is in the main class is not 0 and its not converted to AED as well.
So I am getting this :Thank you. The converted amount is 0.0 1000.0. We will take50 commission, and you will get 0.0
String comparison is wrong.
from=="MYR" should be from.equals("MYR") rather I would recommend equalsIgnoreCase which is not case sensitive.
You should call scanner.nextLine() (in.nextLine()) and not in.toString()
Also you can use the same scanner and not to create 3 different scanners.
See the following part of your code updated with one Scanner (in):
System.out.println("Please enter your currency (USD, AED, or MYR only): ");
Scanner in = new Scanner( System.in );
from = in.nextLine();
System.out.println("What currency do you want?: ");
String to = in.nextLine();
System.out.println("How much you want to convert?: ");
amount= in.nextLong();
System.out.println(from + " " + to);
in.close();
by doing in.nextLine() you read the next line of user input.
From java 8 javadocs:
nextLine
public String nextLine()
Advances this scanner past the current line and returns the input that
was skipped. This method returns the rest of the current line,
excluding any line separator at the end. The position is set to the
beginning of the next line.
Since this method continues to search through the input looking for a
line separator, it may buffer all of the input searching for the line
to skip if no line separators are present.
The above will solve the issue that no input is read by your code.
Later you will have issues comparing the String user entered:
from=="USD" should be changed to "USD".equals(from)
Tip: Prefer to use "String".equals(variable) to avoid null pointer exceptions when variable is null.

How to validate for a non-integer being entered in an integer data type? [duplicate]

This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 3 years ago.
I have to make a store that has items for purchase. After choosing an item, I prompt the user to enter the quantity of the item they would like to buy.
// 'input' is my Scanner object
int quantity;
quantity = input.nextInt();
If the user enters a non-integer (i.e. decimal, char...), it breaks the program.
Is there a way I can validate for this non-integer input?
Thank you
Sure, accept a String value instead of an int, check to see if you can parse that String value to an int, if you can, then do so. If not, sent a message stating that then entered value must be an number.
This could be done in a while loop.
import java.util.Scanner;
public class ScannerInputInt {
public static void main(String... args) {
Scanner in = new Scanner(System.in);
Integer input = null;
do {
System.out.println("Please enter number: ");
String s = in.nextLine();
try {
input = Integer.parseInt(s);
} catch (NumberFormatException e) {
System.out.println("ERROR: " + s + " is not a number.");
}
} while (input == null);
}
}
If you don't wanna use Exceptions method. You can try this.
This piece of code will continue to ask user input until user has entered correct input.
System.out.print("Enter quantity: ");
Scanner input = new Scanner(System.in);
boolean isInt = input.hasNextInt(); // Check if input is int
while (isInt == false) { // If it is not int
input.nextLine(); // Discarding the line with wrong input
System.out.print("Please Enter correct input: "); // Asking user again
isInt = input.hasNextInt(); // If this is true it exits the loop otherwise it loops again
}
int quantity = input.nextInt(); // If it is int. It reads the input
System.out.println("Quantity: " + quantity);
input.close();
Output:
Enter quantity: 12.2
Please Enter correct input: 12.6
Please Enter correct input: s
Please Enter correct input: s6
Please Enter correct input: as
Please Enter correct input: 2
Quantity: 2
I think it is slightly better approach because I think controlling flow of your program with Exceptions is bad practice and should be avoiding when there are other things that you can use.

Program ends before scanner input object can be executed [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
My program is not working as it should.
Purpose of the code: ask user name, gender, age - if age over 18, ask user if married. if user says yes, output Mr or Mrs in front of already given name.
I'm practicing nested if statements and getter/setter methods to return private variables.
I have tried: nesting the if statement that tests the gender and age status, then i tried using a switch statement instead of an if statement to test the marital status, then i tried nesting an if statement within the switch to test the gender and age. I have tried giving each of the if, else if clauses their own scanner input thinking that would just get it to function, but it did not.
I originally had the marital status as a getter/setter method, but took it out to simplify the problem.
I have looked for an answer, but it seems like the code is right, it just will not take the input!
The code I have is as follows:
package agemessage;
import java.util.Scanner;
public class AgeMessage {
public static void main(String[] args) {
info infoObject = new info(); //setter getter class to house input from user
Scanner in = new Scanner(System.in);
System.out.println("what is your name again?");
String input = in.nextLine();
infoObject.getName(input);
System.out.println("thanks, " + infoObject.setName() + " is that a boys name or a girls name?");
String gender = in.nextLine();
infoObject.getGender(gender);
System.out.println("How old are you " + infoObject.setName() + "?");
int ageInput = in.nextInt();
//infoObject.getAge(ageInput);
if (ageInput < 18) {
System.out.print("I shall just call you " + infoObject.setName() + ".");
System.exit(0);
} else if (ageInput >= 18) {
System.out.println("Are you married yet?");
}
//PROGRAM STOPS HERE -- DOES NOT EXECUTE INPUT
String status = in.nextLine();
if (status.equalsIgnoreCase("Y") && infoObject.setGender().equalsIgnoreCase("Girl")) {
System.out.println("I will have to call you Mrs. " + infoObject.setName() + ".");
} else if (status.equalsIgnoreCase("Y") && infoObject.setGender().equalsIgnoreCase("Boy")) {
System.out.println("I will have to call you Mr. " + infoObject.setName() + ".");
System.exit(0);
} else if (status.equalsIgnoreCase("N")) {
System.out.println("I will just call you " + infoObject.setName() + ".");
}
}// main end
}//class end
OUTPUT:
run:
what is your name again?
Carrie Ann Moss
thanks, Carrie Ann Moss is that a boy's name or a girls name?
girl
How old are you Carrie Ann Moss?
40
Are you married yet?
BUILD SUCCESSFUL (total time: 16 seconds)
Right now you don't have a proper setter, add one and see if it works.
Please try putting in.nextLine(); after int ageInput = in.nextInt();
In this way the scanner will not ignore the next line after Integer.
A possible duplicate would be Using scanner.nextLine()
There are a few things that need to be addressed before we solve your problem.
Code conventions. These help others read your code. Not required, but it does help.
Getters and setters: A getter gets the object. A setter sets the object. You're using them in reverse. Example below.
class Person{
int age;
public void setAge(int a){
age = a;
}
public int getAge(){
return age;
}
}
So in a program, let's say we have a Person object, called annie, who is 22 years old.
Person annie = new Person();
annie.setAge(22);
Later in the program, we want to say how old she is...
System.out.println("Annie is " + annie.getAge() +" years old.");
The getter gets the value of the age variable on the Person object called annie.
Now for the actual problem in your program, when nextInt is called, it does not parse the newline character. So what is happening is this:
int ageInput = in.nextInt();
Here, when you enter "40" and then press Enter, you're giving the program this:
"40\n"
nextInt only reads to the end of the integer, so it only reads the 40, not the newline character.
if (ageInput < 18) {
System.out.print("I shall just call you " + infoObject.setName() + ".");
System.exit(0);
} else if (ageInput >= 18) {
System.out.println("Are you married yet?");
}
This works correctly, printing out the "Are you married yet?" string.
However, it doesn't stop executing.
String status = in.nextLine();
Here's the problem. Your Scanner object, it hasn't passed beyond the previous newline character. So it immediately accepts the rest of the line, which is simply this:
"\n"
So the String status is then set to "\n".
if (status.equalsIgnoreCase("Y") && infoObject.setGender().equalsIgnoreCase("Girl")) {
System.out.println("I will have to call you Mrs. " + infoObject.setName() + ".");
} else if (status.equalsIgnoreCase("Y") && infoObject.setGender().equalsIgnoreCase("Boy")) {
System.out.println("I will have to call you Mr. " + infoObject.setName() + ".");
System.exit(0);
} else if (status.equalsIgnoreCase("N")) {
System.out.println("I will just call you " + infoObject.setName() + ".");
}
Since status is set to "\n", nothing else is printed, and the end of the main function is reached, terminating the program.
To fix this, put a in.nextLine() directly after in.nextInt(). This skips the rest of the line, allowing your program to continue into the previously skipped sections.

How to get the type of a variable [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm pretty new to Java so please forgive my noob question.
How can I make the error checking logic syntactically correct and what built in methods might I use?
public static void initialize(HighScores[] scores) {
Scanner input = new Scanner(System.in);
// capture input
for (int i = 0; i < 5; i++) {
System.out.println("Enter the name for score #" + i + ": ");
String name = input.next(); // Alex
System.out.println();
System.out.println("Enter the score for score #" + i + ": ");
int score = input.nextInt();
// Error checking
// if the 'input' is NOT of type 'int'
if (score.getClass().getSimpleName() != int) {
// Ask to input a numeric value
System.out.println("Please enter a numeric value! :)");
score = input.nextInt(); // inputting a value in again
}
System.out.println();
HighScores object = new HighScores(name, score);
scores[i] = object;
}
}
What it would look like if correct:
Enter the name for score #0:
Alex
Enter the score for score #0:
s
Please enter a numeric value! :)
5
Enter the name for score #0:
John
Enter the score for score #0:
3
.... etc...
You seem to be confused,
try {
int score = input.nextInt();
} catch (InputMismatchException ime) {
ime.printStackTrace();
}
Will always be of type int (or you'll get an Exception), per the Scanner#nextInt()
Scans the next token of the input as an int.
and note that the throws says
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
It is also possible to call Scanner#hasNextInt() first,
if (input.hasNextInt()) {
int score = input.nextInt();
} else {
System.out.println(input.next() + " isn't an int");
}
First, as guys already mentioned in their comments you do not need this. If your variable is defined as int it is int and you do not have to check this.
Second, int is a primitive, so you cannot say score.getClass().
However in some cases (if you write some generic code that must care about several, yet certain types) you probably want to fix your if statement as following:
Integer score = .....
.........
if (Integer.class.equals(score.getClass())) {
// your code here
}

Categories