How to read a number and a sentence using Java Scanner - java

I want to understand why using Scanner.nextInt() to read a number and then using Scanner.nextLine() to read a sentence does not work as expected. I have the following code where I input a number but it skips listening to the sentence and my program terminates. Could someone explain why this is and what are alternate solutions?
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number: ");
int x = scanner.nextInt();
System.out.println("Enter a sentence");
System.out.println(x);
String line = scanner.nextLine();
System.out.println(line);

In your code, you have to write scanner.nextLine() after int x = scanner.nextInt();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number: ");
int x = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter a sentence");
System.out.println(x);/*be careful,
here you write the result of x and below you are going to write the sentence.
I think you better write
System.out.println(x);
above
System.out.println("Enter a sentence");*/
String line = scanner.nextLine();
System.out.println(line);

You need a different Scanner instance for String receiving and another for Integer
Scanner scanNumbers = new Scanner(System.in);
Scanner scanString = new Scanner(System.in);
System.out.println("Enter a number: ");
int x = scanNumbers.nextInt();
System.out.println(x);
System.out.println("Enter a sentence");
String line = scanString.nextLine();
System.out.println(line);

Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number: ");
int x = scanner.nextInt();
System.out.println(x);
scanner.nextLine(); // skip the newline character
System.out.println("Enter name");
String name1 = scanner.nextLine();
System.out.println(name1);

Related

Last String Input (y/n) is overlooked by the Program. While loop is not breaking

Here is a basic while loop program, where the program at the end should ask the user if you want to keep going or not. The bug is that the program doesn't let me input (y/n) which is the last String Input.
This does not happen when the last input is an integer value.
import java.util.Scanner;
public class lol {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int age;
String name = "";
String height = "";
String userOption = "";
while (!userOption.equals("n"))
{
System.out.println();
System.out.print("Enter your name: ");
name = sc.nextLine();
System.out.println();
System.out.print("Enter your age: ");
age = sc.nextInt();
System.out.println();
System.out.print("Enter your height: ");
height = sc.nextLine();
System.out.println();
System.out.println("Do you want to keep going? (y/n)");
// The program over looks this line of code
userOption = sc.nextLine();
if(userOption.equals("y"))
{
System.out.println("Breaking");
break;
}
else
{
continue;
}
}
}
}
See this topic, additional nextLine() call could be a workaround
Scanner is skipping nextLine() after using next() or nextFoo()?
Minor adjustments to the code will fix its behaviour ;)
Scanner sc = new Scanner(System.in);
int age;
String name = "";
String height = "";
String userOption = "";
while (true) {
System.out.print("Enter your name: ");
name = sc.nextLine();
System.out.println();
System.out.print("Enter your age: ");
age = sc.nextInt();
System.out.println();
System.out.print("Enter your height: ");
height = sc.nextLine();
System.out.println();
System.out.println("Do you want to keep going? (y/n)");
// The program over looks this line of code
userOption = sc.nextLine();
if (userOption.equals("y")) {
// nothing
System.out.println("Continuing");
} else {
System.out.println("Stopping");
break;
}
}
System.exit(0);
I would however agree that you should take a look at Scanner is skipping nextLine() after using next() or nextFoo()?

How to make loop run as many times as user inputs?

I have a for loop and the method to call it is printMe() and I want the user to be able to determine how many times it runs with their input. This is along the lines of what I think it should be:
System.out.println("Enter a number: ");
loop = input.nextInt();
This should work:
Scanner input = new Scanner(System.in);
int loop = input.nextInt();
for(int i = 0; i<loop;i++){
//do the thing
}
Read the user input thanks to a scanner
Scanner sc = new Scanner(System.in);
int loopNum = sc.nextInt();
for (int i=); i<loopNum; i++){
printMe();
}
Should be something like:
for (int i=0; i<loopNum; i++)
printMe();
Cheers
yes it is correct if your variable input from class Scanner. You can declare variable sc like this and call it many times if you want to read more input from users.
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
loopNum = sc.nextInt();

Error Expected int but given string

I'm getting an error. It's saying that it's expecting an int, but i'm giving it a string. I'm not sure how to fix this.
int DNAstrandlength, strandDNA;
Scanner DNAInfo = new Scanner (System.in);
System.out.println ("Please enter a DNA Strand!");
strandDNA = DNAInfo.next();
DNAstrandlength = strandDNA.length();
You have to declare strandDNA as String.
int DNAstrandlength;
String strandDNA;
Scanner DNAInfo = new Scanner (System.in);
System.out.println ("Please enter a DNA Strand!");
strandDNA = DNAInfo.next();
DNAstrandlength = strandDNA.length();
If you are reading an int then you have nextInt() from scanner.

Getting issues while reading series of lines using scanner

I'm trying to read the input which is in the following format.
2
asdf
asdf
3
asd
df
2
Following is the code:
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
System.out.println(t);
while(t>0){
String a = scanner.next();
String b = scanner.next();
int K = scanner.nextInt();
}
But when I'm scanning, I'm getting empty t=2 , a="" , b=asdf, K=asdf
Can't figure out the issue. There is no space/new line between 2 and asdf.
I have tried using scanner.nextLine() instead of scanner.next() but no change
nextInt() doesn't cosume the newline token, so the following read will get it. You could introduce a nextLine after the nextInt to skip it:
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
scanner.nextLine(); // Skip the newline character
System.out.println(t);
while(t > 0) {
String a = scanner.next();
String b = scanner.next();
int K = scanner.nextInt();
scanner.nextLine(); // Skip the newline character
}
Another approach I prefer:
Scanner scanner = new Scanner(System.in);
int t = Integer.parseInt(scanner.nextLine());
System.out.println(t);
while(t>0){
String a = scanner.nextLine();
String b = scanner.nextLine();
int K = Integer.parseInt(scanner.nextLine());
}
But note it will throw NumberFormatException when input is incorrect.

Java Do-while loop not working?

I honestly have no idea while my do-while loop is not working. Every time I run the program it just skips over it and moves on without even asking for the reply.
import java.util.*;
public class CourseApp {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
ArrayList <Course> courseList = new ArrayList<Course>();
String reply;
//boolean boolVal = true;
do {
System.out.print("Enter new course number: ");
String tempCourseNum = s.nextLine();
System.out.print("Enter course name: ");
String tempCourseName = s.nextLine();
System.out.print("Enter instructor's last name: ");
String tempLastName = s.nextLine();
System.out.print("Enter instructor's first name: ");
String tempFirstName = s.nextLine();
System.out.print("Enter instructor's username: ");
String tempUsername = s.nextLine();
//new Instructor(tempLastName, tempFirstName, tempUsername);
Instructor tempInstruc = new Instructor(tempLastName, tempFirstName, tempUsername);
System.out.print("Enter textbook title: ");
String tempTitle = s.nextLine();
System.out.print("Enter textbook author: ");
String tempAuthor = s.nextLine();
System.out.print("Enter textbook price (no $ sign): ");
double tempPrice = s.nextDouble();
//new TextBook(tempTitle, tempAuthor, tempPrice);
TextBook tempText = new TextBook(tempTitle, tempAuthor, tempPrice);
courseList.add(new Course(tempCourseNum, tempCourseName, tempInstruc, tempText ));
System.out.print("\nEnter another course? (y/n): ");
reply = s.nextLine();
} while (reply.equalsIgnoreCase("Y"));
for (int i =0; i < courseList.size(); i++) {
System.out.println("\n\tCourse #" + (i+1)+":");
System.out.println(courseList.get(i));
}
}
}
If anyone could tell me what the problem is that would be great
Problem is with this line
double tempPrice = s.nextDouble();
It only reads a double value and not the newline after that, and your newline will be read by the nextLine() after the nextDouble(). In order to prevent that add a s.nextLine() after s.nextDouble() to read the newline
double tempPrice = s.nextDouble();
s.nextLine();

Categories

Resources