First i want user to input somethings(name,contact,idnumber),and i will show 2 different file but code are same.The first code problem is "name" input place disappear,and the second but doesn't disappear.Can anyone tell me the problem?Im new in java.
public class Admin {
static Scanner scan= new Scanner(System.in);
static Client client = new Client();
public void admin(){
newClient []nc = new newClient[10];
\\login();
while(true){
System.out.println("Select 1:add Client\n 2:add Account\n 3:login as Client");
try{
int selection = scan.nextInt();
switch(selection)
{
case 1: addClient(nc);
break;
case 2: \\addAccount(nc);
break;
case 3: ;
break;
default: System.out.println("INvalid selection");
}
}
catch(InputMismatchException ex){
System.out.println("Invalid input");
scan.nextLine();
}
}
}
public void addClient(newClient []nc){
for(int i=0;i<nc.length;i++){
System.out.println("Enter name");
String name = scan.nextLine();
System.out.println("Enter contact");
String contact = scan.nextLine();
System.out.println("Enter id number");
String idNumber = scan.nextLine();
nc[i]=new newClient(name,contact,idNumber);
System.out.println(nc[i]);
}
}
Output of the first code is
Enter name
Enter contact
Why the name input place is missing?
There are the second code
public static void main(String[]args){
Scanner scan =new Scanner(System.in);
for(int i=0;i<nc.length;i++){
System.out.println("Enter name");
String name = scan.nextLine();
System.out.println("Enter contact");
String contact = scan.nextLine();
System.out.println("Enter id number");
String idNumber = scan.nextLine();
nc[i]=new newClient(name,contact,idNumber);
System.out.println(nc[i]);
}
}
The second code is working correctly.
Enter name
Enter contact
Enter idNumber
The two pieces of code are in fact different.
In the second code, the scan object is a brand new one. And the only method you call is nextLine(). In the first code, the scan object is created an class level, and has been used before addClient is called.
"Has been used" here is very important. By that I mean you called nextInt on scan and then nextLine:
int selection = scan.nextInt(); <-- You called nextInt here!
switch(selection)
{
case 1: addClient(nc);
break;
case 2: \\addAccount(nc);
break;
case 3: ;
break;
default: System.out.println("INvalid selection");
}
}
catch(InputMismatchException ex){
System.out.println("Invalid input");
scan.nextLine();
}
}
}
public void addClient(newClient []nc){
for(int i=0;i<nc.length;i++){
System.out.println("Enter name");
String name = scan.nextLine(); <-- then you called nextLine here!
System.out.println("Enter contact");
String contact = scan.nextLine();
System.out.println("Enter id number");
String idNumber = scan.nextLine();
nc[i]=new newClient(name,contact,idNumber);
System.out.println(nc[i]);
}
}
This makes the nextLine method return an empty string.
Why?
Let's look at the documentation for both nextInt and nextLine:
nextInt()
Scans the next token of the input as an int.
nextLine()
Advances this scanner past the current line and returns the input that was skipped.
I have created a simpler code that reproduces this situation to explain why calling nextLine immediately after nextInt can cause problems:
Scanner s = new Scanner(System.in);
s.nextInt();
System.out.println(s.nextLine());
I will use a | character to denote where the scanner's current position is.
When the program starts,
|
Then I enter the number 20:
|20
Now the scanner reads the 20, according the documetation, the scanner should be at this position:
20|
Here comes the interesting part, nextLine "Advances this scanner past the current line and returns the input that was skipped."
20
|
So what input has the scanner skipped? Nothing! As a result, an empty string is returned.
as ΦXocę 웃 Пepeúpa ツ says scan.nextInt wouldnt read the enter.
so an alternative solution is before read name contact id information, employ scan.nextLine() to read the enter like this:
public void addClient(newClient []nc){
scan.nextLine();
for(int i=0;i<nc.length;i++){
....// your origin code
}
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I'm trying to make a calculator in java that can multiply subtract and add depending if the user wants that they can choose what they want. For some reason its giving me a weird output
Code
import java.util.Scanner; // Import the Scanner class
public class calculator {
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
//System.in is a standard input stream
System.out.print("Enter first number- ");
int a = sc.nextInt();
System.out.print("Enter second number- ");
int b = sc.nextInt();
System.out.print("Do you want to multiply, add, divide, or subtract? ");
String c = sc.nextLine();
switch(c) {
case "multiply":
System.out.print(a * b);
break;
case "add":
System.out.print(a * b);
break;
default:
System.out.print("Invalid input!");
}
}
}
Output
Enter first number- 2
Enter second number- 2
Do you want to multiply, add, divide, or subtract? Invalid input!
Like I didnt even type Invalid input it just does it by itself for some reason
There can be input left in the scanner before you request a value. In this case, the line break marks the end of the integer, but is not consumed as part of the integer. The call to nextLine() sees there is already an unused line break at the end of the buffer and returns that result. In this case, an empty string is returned. One way to fix this is to consume that unused line break first before requesting the next line or requesting a full line then parsing an integer from it.
Scanner scan = new Scanner(System.in);
// Always request a full line
int firstInt = Integer.parse(scan.nextLine());
int secondInt = Integer.parse(scan.nextLine());
String option = scan.nextLine();
// Use an extra call to nextLine() to remove the line break causing the issues
int firstInt = scan.nextInt();
int secondInt = scan.nextInt();
scan.nextLine(); // Consume the unused line break
String option = scan.nextLine();
sc.nextInt() does not read the enter key that you entered, so sc.nextLine() will read that new line and return it. Use sc.next() instead of sc.nextLine() to avoid this issue. Your code also multiplies the numbers when the user inputs add, so I changed that as well.
import java.util.Scanner; // Import the Scanner class
public class calculator {
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
//System.in is a standard input stream
System.out.print("Enter first number- ");
int a = sc.nextInt();
System.out.print("Enter second number- ");
int b = sc.nextInt();
System.out.print("Do you want to multiply, add, divide, or subtract? ");
String c = sc.next();
switch(c) {
case "multiply":
System.out.print(a * b);
break;
case "add":
System.out.print(a + b);
break;
default:
System.out.print("Invalid input!");
}
}
}
Below is the java program:-
import java.util.Scanner;
public class Program{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
boolean state=true;
while(state){
System.out.println("Welcome");
System.out.println("Press 1 to enter your name ");
System.out.println("Press 2 to exit");
int input =sc.nextInt();
switch(input){
case 1:{
System.out.print("Enter your name : ");
String name=sc.nextLine();
//String name=sc.next();
System.out.println("Your name is\""+name+"\" and it is a beautiful name.");
}
break;
case 2:{
System.out.println("Goodbye");
state=false;
}
break;
default:{
System.out.println("Wrong input");
}
}
}
sc.close();
}
}
I ran this program and when i entered 1 as input i was unable to enter value of name variable and it printed on its own and then continued the execution but when i used next() in place of nextLine() the program worked properly.
Why i am not able to use nextLine() here?
next() places the cursor in the same line after reading the input. nextLine() reads input including space between the words
For a college assessment I'm having to use a Scanner called sc with a class-level scope, and the entirety of the program has to be contained in a single class. The main method calls a menu() method, which uses the Scanner and a for loop to call one of two methods in response to user input.
One of the two methods uses the Scanner to calculate the factorial of an input integer. Once the method is executed, the for loop in menu() continues. To avoid an InputMismatchException due to the user entering a float, I used try/catch. However when the program returns back to the menu() for loop the Scanner causes an InputMismatchException when assigning to choice. How can I get Scanner to prompt the user for input again? Apologies if I'm missing something obvious, this is the first programming language I've ever learned. This should be the stripped down compilable code:
package summativeassessment;
import java.util.InputMismatchException;
import java.util.Scanner;
public class SummativeAssessment {
private static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
menu();
}
public static void menu(){
String fName;
String sName;
System.out.print("Enter your first name: ");
fName = sc.next();
System.out.print("Enter your last name: ");
sName = sc.next();
try{
for(int choice = 1; choice!=0;){
System.out.print("Option 1 to generate username. Option 2 to calculate factorial. Press 0 to quit: ");
choice = sc.nextInt();
switch(choice){
case 2:
System.out.println(fName+" "+sName+", you have selected option 2");
numberFactorial();
break;
case 0:
break;
default:
System.out.println("Invalid option. Please try again.");
}
}
} catch(InputMismatchException ex){
String msg = ex.getMessage();
System.out.println(msg);
}
}
public static void numberFactorial(){
System.out.print("Enter a number: ");
try{
int numIn = sc.nextInt();
long result = numIn;
if(numIn>0){
for(int factor = 1; factor<numIn; factor++){
result *= factor;
if(factor==numIn-1){
System.out.println("The factorial is "+result);
}
}
}
else{
System.out.println("Enter a positive integer greater than 0");
}
}
catch(InputMismatchException ex){
System.out.println("Input invalid");
}
}
}
I debugged your code and got this result:
If you enter a float as input you trigger the InputMismatchException but there is still something in your buffer. So the next time sc.nextInt() is called, it won't wait until you input a value because something is in the buffer already, so it takes the next value out of the buffer and tries to interpret is as an integer. However, it fails to do so, because it is not an integer, so an InputMismatchException is raised again and caught in your menu's catch, now leading to the exit of the program.
The solution is to draw whatever is left in the buffer after the exception was raised the first time.
So the working code will contain a buffer clearing sc.next() inside the exception:
public static void numberFactorial(){
System.out.print("Enter a number: ");
try{
int numIn = sc.nextInt();
long result = numIn;
if(numIn>0){
for(int factor = 1; factor<numIn; factor++){
result *= factor;
if(factor==numIn-1){
System.out.println("The factorial is "+result);
}
}
}
else{
System.out.println("Enter a positive integer greater than 0");
}
}
catch(InputMismatchException ex){
System.out.println("Input invalid");
sc.next();
}
}
I'm trying to make a simple program that asks for the user's age and displays an error when the user inputs a non-integer value.
Here's what I did so far:
import java.util.Scanner;
public class apples {
public static void main(String args[]) {
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name to begin.");
System.out.println("Hello " + nameinput.nextLine() + "!");
Scanner ageinput = new Scanner(System.in);
System.out.println("Please enter your age");
if(!ageinput.hasNextInt()){
System.out.println("Please enter an integer");
}
System.out.println("You've entered a valid age");
nameinput.close();
ageinput.close();
}
}
Here's what I want:
Every time the user inputs a non integer, I want the Please enter an integer error to appear. The user should then be able to input their age again, which will again be checked if it's an integer and so on. This will continue until the user inputs an integer and only then will the message You've entered a valid age be shown. I'm sure about neither which loop to use in this case (for, while, do while) nor how to implement it in the code.
String stringAge;
do {
System.out.println("Please Enter an int");
stringAge = ageinput.next();
} while (!stringAge.matches("^-?\\d+$")); //regex matches for - sign, and then a number
System.out.println("You entered an int");
int age = Integer.parseInt(stringAge);
As you know in Java they're 3 types of loops:
The while and do-while Statements
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once
while is simply a pre-test loop, that is the condition first will be checked before moving on to the body of the loop:
while(condition) # First check, if true or false
{
# Body
}
do-while loop however, checks the condition after executing of the body of the loop at least once, it's a post-test loop:
do{
# Body executed at least once
}while(condition);
The for Statement
The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied
Notice that in your code, asking the user for the age, the proper choice would be do-while, because you need to execute your program at least once to prompt the message and then you have to check the condition, if that's what you intended to do then this will suffice for your purpose. Though, you still can use while.
This is your code edited:
import java.util.Scanner;
public class apples {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name to begin.");
System.out.println("Hello " + input.nextLine() + "!");
System.out.println("Please enter your age");
do{
if(input.hasNextInt()){
System.out.println("You've entered a valid age");
break;
}
else{
System.out.println("Please enter an integer");
input.next();
}
}while(true);
}
}
Since the condition for the loop is the Boolean true it really doesn't matter here if you use while instead of do-while unless if you want to change the condition, that's up to you. For now, this code is very much close to the original code you posted and from my perspective it works, but it may not be the best code out there, there could be other approaches simpler or more complex to the same problem domain.
First of all, there's no need to have multiple Scanner objects wrapping the System.in input stream. (How to use multiple Scanner objects on System.in?)
As for the actual code, here's what came to mind:
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter your name to begin:");
String name = scanner.nextLine();
System.out.println("Hello " + name + "!");
System.out.println("Please enter your age:");
int age;
while (true) {
try { // Try to read in the age.
age = scanner.nextInt();
} catch (InputMismatchException ex) { // The input wasn't a valid integer; parsing the value failed.
System.out.println("Please enter an integer:");
continue; // Attempt reading the age again.
}
break; // The input was a valid integer. Break out of the loop.
}
scanner.close();
System.out.println("You've entered a valid age");
}
}
Hope this is what you wanted. i would suggest that using while is the way to go (my preference)
Using while::
public static void main(String args[]) {
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name to begin.");
System.out.println("Hello " + nameinput.nextLine() + "!");
Scanner ageinput = new Scanner(System.in);
System.out.println("Please enter your age");
while (!ageinput.hasNextInt()) {
System.out.println("Please enter an integer");
ageinput.next();
}
System.out.println("You've entered a valid age");
nameinput.close();
ageinput.close();
}
Using for::
public static void main(String args[]) {
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name to begin.");
System.out.println("Hello " + nameinput.nextLine() + "!");
Scanner ageinput = new Scanner(System.in);
System.out.println("Please enter your age");
for (; !ageinput.hasNextInt();) {
System.out.println("Please enter an integer");
ageinput.next();
}
System.out.println("You've entered a valid age");
nameinput.close();
ageinput.close();
}
Using do while
public static void main(String args[]) {
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name to begin.");
System.out.println("Hello " + nameinput.nextLine() + "!");
Scanner ageinput = new Scanner(System.in);
int i = 0;
do {
if (i == 0) {
System.out.println("Please enter your age");
i++;
} else {
System.out.println("Please enter an integer");
ageinput.next();
}
} while (!ageinput.hasNextInt());
System.out.println("You've entered a valid age");
nameinput.close();
ageinput.close();
}
I want to validate user input using the exception handling mechanism.
For example, let's say that I ask the user to enter integer input and they enter a character. In that case, I'd like to tell them that they entered the incorrect input, and in addition to that, I want them to prompt them to read in an integer again, and keep doing that until they enter an acceptable input.
I have seen some similar questions, but they do not take in the user's input again, they just print out that the input is incorrect.
Using do-while, I'd do something like this:
Scanner reader = new Scanner(System.in);
System.out.println("Please enter an integer: ");
int i = 0;
do {
i = reader.nextInt();
} while ( ((Object) i).getClass().getName() != Integer ) {
System.out.println("You did not enter an int. Please enter an integer: ");
}
System.out.println("Input of type int: " + i);
PROBLEMS:
An InputMismatchException will be raised on the 5th line, before the statement checking the while condition is reached.
I do want to learn to do input validation using the exception handling idioms.
So when the user enters a wrong input, how do I (1) tell them that their input is incorrect and (2) read in their input again (and keep doing that until they enter a correct input), using the try-catch mechanism?
EDIT: #Italhouarne
import java.util.InputMismatchException;
import java.util.Scanner;
public class WhyThisInfiniteLoop {
public static void main (String [] args) {
Scanner reader = new Scanner(System.in);
int i = 0;
System.out.println("Please enter an integer: ");
while(true){
try{
i = reader.nextInt();
break;
}catch(InputMismatchException ex){
System.out.println("You did not enter an int. Please enter an integer:");
}
}
System.out.println("Input of type int: " + i);
}
}
In Java, it is best to use try/catch for only "exceptional" circumstances. I would use the Scanner class to detect if an int or some other invalid character is entered.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean gotInt = false;
while (!gotInt) {
System.out.print("Enter int: ");
if (scan.hasNextInt()){
gotInt = true;
}
else {
scan.next(); //clear current input
System.out.println("Not an integer");
}
}
int theInt = scan.nextInt();
}
}
Here you go :
Scanner sc = new Scanner(System.in);
boolean validInput = false;
int value;
do{
System.out.println("Please enter an integer");
try{
value = Integer.parseInt(sc.nextLine());
validInput = true;
}catch(IllegalArgumentException e){
System.out.println("Invalid value");
}
}while(!validInput);
You can try the following:
Scanner reader = new Scanner(System.in);
System.out.println("Please enter an integer: ");
int i = 0;
while(true){
try{
i = reader.nextInt();
break;
}catch(InputMismatchException ex){
System.out.println("You did not enter an int. Please enter an integer:");
}
}
System.out.println("Input of type int: " + i);