Scanner method 'nextLine()' skips an input [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
OK, So I have this code:
import java.util.Scanner;
public class Library
{
int Acc_Num;
String Title;
String Author;
public void input()
{
Scanner s = new Scanner (System.in);
System.out.println("Enter Your Accession Number");
Acc_Num = s.nextInt();
System.out.println("Enter The Title Of The Book");
Title = s.nextLine();
System.out.println("Enter The Author Of The Book");
Author = s.next();
}
public void compute()
{
Scanner s = new Scanner (System.in);
System.out.println("Enter Number Of Days Late");
int Day_Late = s.nextInt();
int Fine = 2 * Day_Late;
System.out.println("Fine: " + Fine);
}
public void display()
{
System.out.println("Accession Number\t\tTitle\t\tAuthor");
System.out.println(Acc_Num + "\t\t" + Title + "\t\t" + Author);
}
public static void main(String[] args)
{
Library Mem1 = new Library();
Mem1.input();
Mem1.compute();
Mem1.display();
}
}
The thing is, when it goes into the function to get input, it take input for Title but not for author. Have attached a screenshot of the program running in cmd.
Would love to have this solved.
Is this a Scanner glitch? Or Am I doing something wrong?

Related

Entering String values into a String Array using Scanner Class [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
I am learning about Arrays and had gotten this assignment. Whenever I run the code, the value which is supposed to go into String array goes into Int. It skips over the name[i]=sc.nextLine(); completely.
Any Help will be appreciated.
import java.util.*;
public class Marks_Remarks {
public static void main(String []Args){
Scanner sc= new Scanner (System.in);
System.out.println("Enter how many students");
int n= sc.nextInt();
String name[]= new String[n];
int roll[]= new int[n];
int sub1[]= new int[n];
int sub2[]= new int[n];
int sub3[]= new int[n];
for (int i=0;i<n;i++){
System.out.println("Enter Name");
name[i]= sc.nextLine();
System.out.println("Enter Roll No.");
roll[i]= sc.nextInt();
System.out.println("Enter marks in Three Subjects");
sub1[i]= sc.nextInt();
sub2[i]= sc.nextInt();
sub3[i]= sc.nextInt();
}
int avg; String remark;
for (int k=0;k<n;k++){
avg= (sub1[k]+ sub2[k]+ sub3[k])/3;
if (avg>=85)
remark= "Excellent";
else if(avg>=75 && avg<=84)
remark= "Distinction";
else if(avg>=60 && avg<=74)
remark= "First Class";
else if(avg>=40 && avg<=59)
remark="Pass";
else
remark="Poor";
System.out.println("Name: "+ name[k]+ "\tRoll No.: "+ roll[k]+ " \tAverage: "+ avg+ " \tRemark: " + remark);
avg=0;
}
}
}
Use name[i]=sc.next(); instead of : name[i]=sc.nextLine();
It may help you.

System.out.println() is not getting executed [duplicate]

This question already has answers here:
How to get out of while loop in java with Scanner method "hasNext" as condition?
(9 answers)
Closed 2 years ago.
import java.util.Scanner;
public class testFixedCapacityStack {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
FixedCapacityStack<String> s;
s = new FixedCapacityStack<String>(100);
while(sc.hasNext()) {
String item = sc.next();
if(!item.equals("-")) {
s.push(item);
} else if (!s.isEmpty()) {
System.out.print(s.pop() + " ");
}
}
System.out.println(s.size());
}
}
I have no idea why the last line is not getting executed. Someone please point out where I did wrong.
Thank you.
Your code is requesting a new string as input and continuing the loop if it's not empty. This is making your while loop a never-ending loop. That is the reason the last line is not executing. You can insert an if-statement in the loop for an exit string.
import java.util.Scanner;
public class testFixedCapacityStack {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
FixedCapacityStack<String> s;
s = new FixedCapacityStack<String>(100);
while(sc.hasNext()) {
String item = sc.next();
if(item.equals("/")) {
break;
}
if(!item.equals("-")) {
s.push(item);
} else if (!s.isEmpty()) {
System.out.print(s.pop() + " ");
}
}
System.out.println(s.size());
}
}
Now when you enter the value "/" as the input, it will get out of the while loop and the last line will execute.

I am very beginner to java could any one explain it please why I am getting "InputmismatchExcetion" here? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 4 years ago.
Here i am trying to Enter and Print some details of employe and everything looks fine but i am getting an Exception why?
import java.util.Scanner;
class EmpDet
{ //here details
int age;
String name;
int ssn;
public EmpDet(int age,String name,int ssn)
{
//assign to constructor
this.age = age;
this. name = name;
this.ssn = ssn;
System.out.println(age+" "+name+" "+ssn); //printing details
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
String name = sc.nextLine(); //InputMismatchException in this line
int ssn = sc.nextInt();
EmpDet det = new EmpDet(age,name,ssn);
}
}
You might want to grab line by line instead. Once you have the line, then you can try to parse the input into an Integer.
Scanner sc = new Scanner(System.in);
int age = Integer.parseInt(sc.nextLine());
String name = sc.nextLine();
int ssn = Integer.parseInt(sc.nextLine());
EmpDet det = new EmpDet(age,name,ssn);
It would be also wise to put a try catch around the parsing in case the input from the user doesn't qualify as being an Integer.
Note, nextInt() only grabs the number and not the new line (enter)

Scanner skipping inputs? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
I've been debugging the following program from hours yet I cannot find why is the sanner not taking the input for the field name
This is my source code:
import java.util.Scanner;
public class Student
{
int rollNo;
String name;
double percentageMarks;
static Scanner input = new Scanner(System.in);
public void accept()
{
System.out.print("Enter roll no: ");
rollNo = input.nextInt();
System.out.print("Enter Name: ");
name = input.nextLine();
System.out.print("Enter percentageMarks: ");
percentageMarks = input.nextDouble();
}
public void display()
{
System.out.println("Name: " +name);
System.out.println("roll no: " +rollNo);
System.out.println("Percentage marks: " +percentageMarks);
}
public static void main(String[] args)
{
Student s1 = new Student(), s2 = new Student();
s1.accept();
s2.accept();
if(s1.percentageMarks>s2.percentageMarks)
s1.display();
else if (s2.percentageMarks>s1.percentageMarks)
s2.display();
else
System.out.println("Both students has same marks");
}
}
This is an output sample:
Enter roll no: 1
Enter Name: Enter percentageMarks:
As seen, without it allowing to enter student name, its prompting to enter student percentage marks.
Any suggestion please?
This is because you first have the input.nextInt() and after it is finished it is not going to the next line. Just parse the whole first line as Integer.parseInt(scanner.nextLine()) and you will get your input for the name after that.

"Java.Util.NoSuchElementException: No Line Found"

//I am not able to figure out what is wrong? Please help me. I was able to use the //scanner .I am not able to input the values.Java.Util.NoSuchElementException: No Line //Found.
//String arrayValue = null;
int Rows= boardsize, Columns=boardsize;
int[][] sudokuArray = new int[Rows][Columns];
String[] sudokuTempArray;
String delimiter = "\\,";
#SuppressWarnings("resource")
Scanner userInput = new Scanner(System.in);
for(int i=0;i<Rows;i++ ){
System.out.println("Enter the value of array separated by ',' for row" + i);
while(userInput.hasNext())
{
String arrayValue = userInput.next();
sudokuTempArray = arrayValue.split(delimiter);
if(sudokuTempArray.length == Rows)
{
for (int j = 0;j<Columns;j++)
{
sudokuArray[i][j] = Integer.parseInt(sudokuTempArray[j]);
System.out.println(sudokuArray[i][j]);
}
}
}
/*
else
{
System.out.println("Try again!");
}*/
}
If you have used a scanner previously reading from System.in and have closed that scanner, you will have closed the System.in InputStream.
Have you previously closed a scanner reading from System.in?
Yes this is a common error. Look at my answer to this question.
java - Scanner class NoSuchElementFoundException
He essentially closed the input in another method, which you are likely doing as well.
Search for .close in your code base.
See this:
java - Scanner class NoSuchElementFoundException
import java.util.*;
import java.util.StringTokenizer;
class shift
{
Scanner sc=new Scanner(System.in);
void test(int x)
{
String s=sc.nextLine();
StringTokenizer st=new StringTokenizer(s);
String wen="";
{
while(st.hasMoreTokens())
{
String temp=st.nextToken();
for(int i=1;i<=x;i++)
{
wen=wen+temp+" ";
}
}
System.out.print(wen);
}
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
shift reff=new shift();
if(n<=0)
{
System.out.print("EMPTY");
}
else
{
reff.test(n);
}
}
}
//output : java.util.NoSuchElementException: No line found

Categories