Error in Scanner [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
Below is a program for palindrome. If it is palindrome it will print YES else NO.
I am unable to understand what's the difference in calling:
> int n=Integer.parseInt(in.nextLine());
> or int n=in.nextInt();
because both is doing the same work.
1st one is taking Stringas input then converting it into int
2nd one is taking directly int.
when the 1st one is taken there is no error.
But when 2nd one is taken it gets stored in n then it prints YES.(when debugged i found out that it gets stored in n but it skips the input string str and then it compares with str and s and prints YES).
So can anyone explain the logic behind this.
public class Test1 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
//int n=Integer.parseInt(in.nextLine());
int n=in.nextInt();
while(n!=0){
String s="";
String str=in.nextLine();
for(int i=str.length()-1;i>=0;i--){
s=s+str.charAt(i);
}
if(str.equals(s) ){
System.out.println("YES");
}
else{
System.out.println("NO");
}
n--;
}
}
}

I guess that with Scanner you expect the String to be verified... in that case this line int n=in.nextInt(); will throw a java.util.InputMismatchException exception if the input is not a number.
The verification would be easier to achieve by using StringBuilder, like this:
Scanner in=new Scanner(System.in);
String original = in.nextLine();
StringBuilder reversa = new StringBuilder(original).reverse();
if (reversa.toString().equals(original)) {
System.out.println("YES");;
} else {
System.out.println("NO");;
}

Related

Why does my while loop break after I add one object to the list [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 months ago.
I'm doing the Java MOOC fi course. I'm supposed to make a list of show names and durations, and print the ones that are shorten than certain duration.
I want the while loop to end after I enter a blank name but it ends after the first object I add to the list.
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// implement here your program that uses the TelevisionProgram class
ArrayList<TelevisionProgram> programs = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Name: ");
String programName = scanner.nextLine();
if (programName.isEmpty()) {
break;
}
System.out.print("Duration: ");
int durationOfProgram = scanner.nextInt();
programs.add(new TelevisionProgram(programName, durationOfProgram));
}
System.out.println();
System.out.print("Program's maximum duration? ");
int maxDuration = scanner.nextInt();
for (TelevisionProgram show : programs) {
if (show.getDuration() <= maxDuration) {
System.out.println(show);
}
}
}
}
replaced
int durationOfProgram = scanner.nextInt();
with
int durationOfProgram = Integer.valueOf(scanner.nextLine());
and now it works but i still don't get why

Exception in thread "main" java.lang.NumberFormatException: For input string: "" Why is it showing null? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
What is a NumberFormatException and how can I fix it?
(9 answers)
Closed 7 months ago.
Here is the code, it's giving me an error in line 18 where I'm trying to convert a string into an Integer.
import java.util.*;
public class matrix_1 {
public static void main(String[] args){
Scanner SC=new Scanner(System.in);
System.out.println("Enter the dimenssion");
int a=SC.nextInt();
Integer[][] matrix=new Integer[a][a];
for (int i=0;i<a;i++){
String[] m1=new String[a];
System.out.print("Enter digits with spaces in between:");
String num=SC.nextLine();
m1=num.split(" ");
for (int j=0;j<m1.length;j++){
matrix[i][j]=Integer.parseInt(m1[j]);
}
}
for (int i=0;i<a;i++){
for (int j=0;j<a;j++){
System.out.print(matrix[i][j]+ " ");
}
System.out.print("\n");
}
SC.close();
}
}
I've tried checking what is happening, so I wrote the same code Jshell piece by piece. To my surprise, it worked there!!
I'm really clueless and I'm kinda new to java.
What I don't understand is why it is saying that the elements in m1 array are null.

How Do I Use A Do-While Loop In This Specific Instance (Program completes before y/n) Java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 4 years ago.
I'm doing a lab that requires a continuation question, but no matter what I do, the program always stops before accepting an answer. Here is my main method:
import java.util.Scanner;
import static java.lang.System.*;
public class Lab03b
{
public static void main( String args[] )
{
Scanner scan = new Scanner(in);
boolean ans = true;
do{
out.println("Enter the word to display:: ");
String word = scan.nextLine();
out.println("Enter the number of times to display:: ");
int times = scan.nextInt();
out.println("Do you wish to continue? (y/n):: ");
String choice = scan.nextLine();
WordPrinter.printWord(word,times);
if (choice == "y" || choice == "Y")
{ ans = true;
}
else
{
ans = false;
}
} while(ans == true);
}
}
It references another class that goes through a basic loop to print out a word x amount of times. Any help is appreciated.

InputMismatchException when using Sacnner nextLine for String [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
This is my code
import java.io.*;
import java.util.*;
class student
{
String name;
int age;
float cgpa;
}
public class getdata
{
public static void main(String args[]) throws IOException
{
Scanner in=new Scanner(System.in);
int n;
n=in.nextInt();
student[] s=new student[n];
for(int i=0;i<n;i++)
{
try
{
s[i]=new student();
s[i].name=in.nextLine();
in.nextLine();
s[i].age=in.nextInt();
s[i].cgpa=in.nextFloat();
}
catch(InputMismatchException e)
{
System.out.println(e.getMessage());
}
}
System.out.println();
System.out.println("Name\tAge\tCGPA\n");
for(int i=0;i<n;i++)
{
System.out.println(s[i].name+"\t"+s[i].age+"\t"+s[i].cgpa+"\n");
}
}
}
compiling the program gave no problem. but when executing and i try to input a string space , it takes the string as two separate strings and assigns all other values of one to be null. for eg if i enter
mike hannigan
5
6.5
The output is
mike 0 0.0
hannigan 5 6.5
i tried getting the string with only a single in.nextLine(); but that causes the string to be taken as null(Throws InputMismatchException). with try and catch block
and without the try block, this is the output i get
My suggestion is to always scan the entire line as String and convert it to required data types using parse methods. Please see below:
public static void main(String args[]) throws IOException
{
Scanner in=new Scanner(System.in);
int n;
n=Integer.parseInt(in.nextLine());
student[] s=new student[n];
for(int i=0;i<n;i++)
{
s[i]=new student();
s[i].name=in.nextLine();
s[i].age=Integer.parseInt(in.nextLine());
s[i].cgpa=Float.parseFloat(in.nextLine());
}
System.out.println();
System.out.println("Name\tAge\tCGPA\n");
for(int i=0;i<n;i++)
{
System.out.println(s[i].name+"\t"+s[i].age+"\t"+s[i].cgpa+"\n");
}
}
Your problem is the very common mistake in understanding Scanner.
Calling nextInt(), nextFloat(), or most other nextXxx() methods will leave the newline following the number unprocessed.
A subsequent call to any of the nextXxx() methods, other than nextLine(), will automatically skip that newline, as being whitespace between tokens.
However, nextLine() does not skip leading whitespace, so calling nextLine() after any other nextXxx() method, will return an empty string (or rather whatever is on the rest of the line following the last token).
So, when mixing nextXxx() calls with nextLine() calls, you have to flush (discard) the end of the previous line by calling nextLine() first.
This means your code should be:
Scanner in = new Scanner(System.in);
int n = in.nextInt();
in.nextLine(); // Ignore rest of line after int
student[] s = new student[n];
for (int i = 0; i < n; i++) {
s[i] = new student();
s[i].name = in.nextLine();
s[i].age = in.nextInt();
s[i].cgpa = in.nextFloat();
in.nextLine(); // Ignore rest of line after float
}
System.out.println();
System.out.println("Name\tAge\tCGPA");
for (int i = 0; i < n; i++) {
System.out.println(s[i].name + "\t" + s[i].age + "\t" + s[i].cgpa);
}
Better yet, do what the answer by #JaganathanNanthakumar says: Always use nextLine() and parse the number yourself.

Finding minimum number from user input [duplicate]

This question already has answers here:
Why won't this print any integers?
(5 answers)
Closed 7 years ago.
I'm very confused as to why this isn't working, would appreciate some help:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int min = Integer.MAX_VALUE;
System.out.println("Enter a number");
int input = in.nextInt();
while(in.hasNextInt()){
if(input < min){
min=input;
}
}
in.close();
System.out.println(min);
}
}
The loop isn't ending for some reason when I enter something other than an int.
Because it's waiting for the next integer, and will keep reading forever. One solution is to use getline() and parse the returned string as an integer. If conversion fails, you'll have to handle it. If 0-length string is returned, then exit.
A solution would be to take .next() and use a try-catch to parse an int out of it:
while (in.hasNext() {
String input = in.next();
try {
int printInt = Integer.parseInt(input);
System.out.println(printInt);
} catch () {}
}
Additionally, I think you're forgetting to call in.nextInt() inside your while loop.

Categories