Whats the difference between two multiple user input programs? [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
import java.util.Scanner;
public class HelloWorld{
public static void main(String args[]){
Scanner dd = new Scanner(System.in);
System.out.println("Enter name");
String b = dd.nextLine();
System.out.println("Enter num");
int num = dd.nextInt();
}
}
And
import java.util.Scanner;
public class HelloWorld{
public static void main(String args[]){
Scanner dd = new Scanner(System.in);
System.out.println("Enter num");
int num = dd.nextInt();
System.out.println("Enter name");
String b = dd.nextLine();
}
}
Why the latter doesn't work peoperly(doesn't let me enter name), while the first one does?
I have made up a new version without that annoying "Scanner scan = new Scanner".
And what about this solution? What cons may it have?
import java.util.Scanner;
public class HelloWorld{
public static void main(String args[]){
System.out.println("Enter num");
int i = new Scanner(System.in).nextInt();
System.out.println("Enter name");
String b = new Scanner(System.in).nextLine();
}
}

The second program expects an Int first and then a name. And hence might be erroring out when a name is entered.

In the second case, nextInt() does not scan over the newline character that the user inputs when pressing the Return key.
In the first case, nextLine() is encountered first so the problem doesn't manifest itself.
The moral of the story is to always use nextLine() and parse the resulting string accordingly. Use something like Integer#parseInt to convert a string to an integer.

Related

Scanner next methods in Java [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I'm new to Java and still confused on how the scanner next methods actually work. I have an example program right here:
import java.util.Scanner;
public class HelloJava{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int varInt;
String varString;
String varStringTwo;
System.out.print("Insert int value: ");
varInt = sc.nextInt();
System.out.print("Insert string value: ");
varString = sc.nextLine();
System.out.print("Insert another string value: ");
varStringTwo = sc.nextLine();
sc.close();
}
}
When i executed the program and entered an integer on the first prompt, the terminal looked like this:
Insert int value: 15
Insert string value: Insert another string value: // i can input any value here //
// ^ but the program doesn't allow me to input anything here
I know that one of the solution is to put "sc.nextLine();" between varInt = "sc.nextInt();" and "System.out.print("Insert a string value: ");", but I don't understand why or how.
When you scan a String values with spaces the scanner.next() method will get you the string up to space.
For example,
your input is This is a String
so when the first time you run scanner.next() it will return the value This. If you run it a second time it will return you is and so on.

how to take multiple input using NextLine() in java [duplicate]

This question already has answers here:
What's the difference between next() and nextLine() methods from Scanner class?
(15 answers)
Closed 5 years ago.
how to take more inputs from user using Nextline() in java
if i use scn.Nextline() after reading one input it will work but giving a null in answer.
public class Mapdemo {
public static void main(String[] args) {
Scanner scn =new Scanner(System.in);
System.out.println("enter the number of phoneaddress you want to store");
int n=scn.nextInt();
int j=0;
System.out.println("enter the phonenumber first and then name of the person phoneaddress");
Map<String, Long> m1=new HashMap<String,Long>();
for(int i=0;i<n;i++)
{
Long l=scn.nextLong();
String s=scn.nextLine();
m1.put(s,l);
}
System.out.println("enter the name to be checked");
String s2=scn.next();
System.out.println(m1.get(s2));
After using .nextInt() for the first time do:
scanner.nextLine();
after that to clear the line, nextLine() stops at the newline character (OS dependant).
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()

Why does the second iteration of this loop skip through the first Scan? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
I'm trying to write a code that asks a user to input their name, stores it in a List, then asks them to input their age, stores it in another list. It then asks the user if they would like to try again [Y/N].
When testing the code, I inputted "Y" and expected the loop to ask me to input another name. Instead, it skips through the name input and jumps to the age input. I can't figure out why.
Here's the code
import java.util.ArrayList;
import java.util.Scanner;
public class PatternDemoPlus {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
ArrayList<String> names = new ArrayList<String>();
ArrayList<Integer> ages = new ArrayList<Integer>();
String repeat = "Y";
while(repeat.equalsIgnoreCase("Y")){
System.out.print("Enter the name: ");
names.add(scan.nextLine());
System.out.print("Enter the age: ");
ages.add(scan.nextInt());
System.out.print("Would you like to try again? [Y/N]");
repeat = scan.next();
//Notice here that if I use "repeat = scan.nextLine(); instead, the code does not allow me to input anything and it would get stuck at "Would you like to try again? [Y/N]
System.out.println(repeat);
//Why is it that after the first iteration, it skips names.add and jumps right to ages.add?
}
}
}
I would appreciate your help. Thank you.
Using next() will only return what comes before a space. nextLine() automatically moves the scanner down after returning the current line.
Try to change your code like below.
public class PatternDemoPlus {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
ArrayList<String> names = new ArrayList<String>();
ArrayList<Integer> ages = new ArrayList<Integer>();
String repeat = "Y";
while(repeat.equalsIgnoreCase("Y")){
System.out.print("Enter the name: ");
String s =scan.nextLine();
names.add(s);
System.out.print("Enter the age: ");
ages.add(scan.nextInt());
scan.nextLine();
System.out.print("Would you like to try again? [Y/N]");
repeat = scan.nextLine();
System.out.println(repeat);
}
}
}

Reading an integer from the command prompt in Java using Scanner

I can't figure out what I'm doing wrong here.
My code:
import java.util.Scanner;
public class test
{
public static void main(String args[])
{
Scanner input_scanner = new Scanner(System.in);
System.out.printf("\nEnter number:");
int num_shapes = input_scanner.nextInt();
System.out.printf("\n%d", num_shapes);
}
}
Each time the program is run, I enter an integer, press the enter key, am taken to a new line, enter a new integer, and hit the enter key again. The first integer is then displayed.
How can I get it to display the first integer directly after it is entered, without having to enter a second integer?
I've tried it with and without
input_scanner.nextLine();
following the line containing 'nextInt()', but get the same thing either way.
Any help in resolving this problem is greatly appreciated.
this works perfectly
import java.util.Scanner;
public class mainclass{
public static void main(String args[])
{
Scanner input_scanner = new Scanner(System.in);
System.out.println("Enter number:");
int num_shapes = input_scanner.nextInt();
System.out.println(num_shapes);
}
}

copyValueOf in Java?

import java.util.Scanner;
public class CourseSplitter {
public static void main(String args[]){
Scanner keyboard = new Scanner(System.in);
char[] course; //course code format: ABCDE##
String code;
//int num;
System.out.println("Input Course: ");
course = keyboard.next();
System.out.println(course);
code = String.copyValueOf(course, 0, 4);
System.out.println(code);
}
}
I don't know how I should let the user input the course when I'm using a character array instead of string. In short, how do I use the "scanner" on character arrays?
The instruction is the user will input a course code in the format: ABCDE##
Then, the program must split it into the course name and the course number. So, I had to use the copyValueOf method but it doesn't seem to work because from all the articles I read online, they used a char[] array but initialized the array with some value. So I was wondering how I could use the scanner on character arrays.
Why not just read a string from the scanner and then call String.toCharArray? It's not even clear why you need a char array here...
Why not just read a string directly with scanner.nextLine?
import java.util.Scanner;
public class CourseSplitter {
public static void main(String args[]){
Scanner keyboard = new Scanner(System.in);
System.out.println("Input Course: ");
String course = keyboard.nextLine();
System.out.println(course);
String code = course.substring(0, 5); //You put 4 but it left out the last letter in the course name. I changed it to 5 and it worked but I'm confused since the index always start with 0.
System.out.println(code);
String num = course.substring(5, 6);
System.out.println(num);
}
}

Categories

Resources