This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 7 years ago.
I would like to create a shopping list program, after entering the name and price of product enters them into the arrays and then print the entire list of what is wrong with this code?
import java.util.Scanner;
import java.util.Arrays;
public class List {
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
String [] name = new String[4];
double [] price = new double[4];
for (int i =0; i<name.length; i++) {
System.out.println("name");
name[i] = sc.nextLine();
System.out.println("price");
price[i] = sc.nextDouble();
}
System.out.println("your product: " + Arrays.toString(name) + Arrays.toString(price));
}
}
You can resolve it by using nextLine() instead of nextDouble(). However, you need to parse it to a double as your value declared as double :
Scanner sc = new Scanner(System.in);
String [] name = new String[4];
double [] price = new double[4];
for (int i =0; i<name.length; i++) {
System.out.println("name");
name[i] = sc.nextLine();
System.out.println("price");
price[i] = Double.parseDouble(sc.nextLine()) ;
}
System.out.println("your product: " + Arrays.toString(name) + Arrays.toString(price));
Scanner#nextLine() reads the whole line.
Scanner#nextDouble() reads the next token and not the whole line.
So for the second iteration of loop nextLine() will read the same line where you placed the token giving you empty in name[1] and error for double[1]=sc.nextDouble().
Docs
The problem can be solved by adding a nextLine() after reading double variable
for (int i =0; i<name.length; i++) {
System.out.println("name");
name[i] = sc.nextLine();
System.out.println("price");
price[i] = sc.nextDouble();
if(i<name.length-1)
sc.nextLine(); //will skip the line
}
Demo
So I was using input.nextDouble() and it was giving me Type mismatch error
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
double[] numbers = new double[4];
String [] name = new String[4];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Please enter product price");
numbers[i] = Double.parseDouble(input.nextLine());
System.out.println("Please enter product name");
name[i] = input.nextLine();
}
System.out.println(Arrays.toString(name));
System.out.println(Arrays.toString(numbers));
}
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
import java.util.Scanner;
public class stringclass {
public static void main(String [] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of friends: ");
int a = input.nextInt();
String [] friends = new String[a];
int count=1;
for(int i=0;i<a;i++){
System.out.println("Enter the name of your friend "+count +":");
friends[i] = input.nextLine();
count++;
}
int count1=1;
for (int j=0;j<a;j++){
System.out.println("Name of your friend "+count1+ "is "+friends[j].toUpperCase());
count1++;
}
}
}
I was writing code to display name of friends using string in java by getting input. But index 0 is not getting a entry
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of friends: ");
int a = Integer.parseInt(input.nextLine());
String[] friends = new String[a];
for (int i = 0; i < a; i++) {
System.out.print("Enter the name of your friend " + (i + 1) + ":");
friends[i] = input.nextLine();
}
for (int j = 0; j < a; j++) {
System.out.println("Name of your friend " + (j + 1) + "is " + friends[j].toUpperCase());
}
}
You need to consume the end of the line that contains the input integer, as explained in comments.
import java.util.Scanner;
public class stringclass {
public static void main(String [] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of friends: ");
int a = input.nextInt();
// This is what you want
input.nextLine();
String [] friends = new String[a];
int count=1;
for(int i=0;i<a;i++){
System.out.println("Enter the name of your friend "+count +":");
friends[i] = input.nextLine();
count++;
}
int count1=1;
for (int j=0;j<a;j++){
System.out.println("Name of your friend "+count1+ "is "+friends[j].toUpperCase());
count1++;
}
}
}
I want get first name when input the name with array and looping
Example :
Enter the name :
1. Alvin Indra
2. Sada Rika
Output :
1. Alvin
2. Sada
Code:
public static void main(String[] args) {
int n;
String teman[],namadepan[];
Scanner sc = new Scanner(System.in);
Scanner x = new Scanner(System.in);
System.out.print("Put how many friends : ");
n = sc.nextInt();
teman = new String[n];
namadepan = new String[n];
for(int i=0;i<n;i++){
System.out.print("Friend Of-"+(i+1)+" : ");
teman[i] = x.nextLine();
}
System.out.print("\n");
System.out.println("First Name : ");
for(int i=0;i<n;i++){
if(teman[i] == ' '){ // this is where I need help
System.out.println((i+1)+". "+teman[i].substring(0,i));
}
}
}
Here you go
String name = "John Smith";
System.out.println(name.split(" ")[0]);
Using this will replace that second for loop, you don't need to cycle through each letter to look for a space you can just use the split method on the string and specifiy the character in which to split the string up and then call the first element.
Updated complete implementation
import java.util.Scanner;
public class testest {
public static void main(String[] args){
int n;
String teman[],namadepan[];
Scanner sc = new Scanner(System.in);
Scanner x = new Scanner(System.in);
System.out.print("Put how many friends : ");
n = sc.nextInt();
teman = new String[n];
namadepan = new String[n];
for(int i=0;i<n;i++){
System.out.print("Friend Of-"+(i+1)+" : ");
teman[i] = x.nextLine();
}
System.out.print("\n");
for(int i=0;i<n;i++){
System.out.println("First Name : ");
System.out.println(teman[i].split(" ")[0]);
System.out.print("\n");
}
}
}
You are probably looking for using contains and indexOf methods of String class in java, to use them as :
if (teman[i].contains(" ")) {
System.out.println((i + 1) + ". " + teman[i].substring(0, teman[i].indexOf(" ")));
}
I am a beginner in Java programming. I am trying to write a simple program to take size of input followed by list of numbers separated by spaces to compute the sum.
The first input is getting in fine for the second one system shows error as it is trying to parse a blank string into integer. Can you please help with the mistake I am making?
import java.util.Scanner;
public class InputStringforarray {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print(" Enter size of input ");
int num = scan.nextInt();
System.out.println("Enter data separated by spaces: ");
String line = scan.nextLine();
String[] str = line.split(" ");
int[] A = new int[num];
int sum = 0;
for (int i = 0; i < num; i++)
A[i] =Integer.parseInt(str[i]);
for (int i = 0; i < num; i++)
sum = sum + A[i];
System.out.println("Sum is " + sum);
}
}
The reason you get an exception in your code is because int num = scan.nextInt(); does not process the newline character after the number.
So when the statement String line = scan.nextLine(); is used, it processes the newline character and hence you get an empty string ""
You can either fetch the entire line and parse it to Integer, like this:
int num = Integer.parseInt(scan.nextLine());
or you can go with using nextInt() and then use a blank scan.nextLine() to process the new line after the number, like this:
int num = scan.nextInt();
scan.nextLine();
Your Program has only one error that you were making only one scan object of scanner class, you have to make two scanner class object one will help in getting array size while another will help in getting array element.
import java.util.Scanner;
public class InputStringforarray {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scan1 = new Scanner(System.in); // change 1
System.out.print(" Enter size of input ");
int num = scan.nextInt();`enter code here`
System.out.println("Enter data separated by spaces: ");
String line = scan1.nextLine();// change 2
String[] str = line.split(" ");
int[] A = new int[num];
int sum = 0;
for (int i = 0; i < num; i++)
A[i] =Integer.parseInt(str[i]);
for (int i = 0; i < num; i++)
sum = sum + A[i];
System.out.println("Sum is " + sum);
}
}
I need to read user inputs line by line (may be included spaces). I had already read Scanner doesn't see after space question. So I used with scanner.nextLine() but this method does not help my program. Below is my sample program ....
public class TestingScanner {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many friends do you have ?");
int size = sc.nextInt();
String[] names = new String[size];
for (int i = 0; i < size; i++) {
System.out.println("Enter your name of friend" + (i + 1));
names[i] = sc.nextLine();
}
System.out.println("*****************************");
System.out.println("Your friends are : ");
for (int i = 0; i < names.length; i++) {
System.out.println(names[i]);
}
System.out.println("*****************************");
}
}
While runnig my program , after inserted no: of friend , my program produces two lines as below. How can I solve it ? Thanks.
After int size = sc.nextInt(); use sc.nextLine() to consume the newline characters, otherwise, they will be consumed by nextLine() in your loop and that is not what you want.
Solution
int size = sc.nextInt();
sc.nextLine();
i write one program that get input from user as "Enter number of students:" then add the student names into it and print it in console. I write one code that run fine but problem is the loop is already ramble one time the code is not properly working i also want to know that how to get inputs using command line argument without Scanner and store it in String Array
Current Output is like that
Here is my code please help and i am in learning phrase of Java
import java.util.Scanner;
public class StringScanner
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.println("Enter The number of students:");
int totalstudents = in.nextInt();
//store into String array
String studentname[] = new String[totalstudents];
for(int i = 0; i < studentname.length;i++)
{
System.out.println(i);
System.out.println("Enter Student Names: ");
studentname[i] = in.nextLine();
}
for(String names:studentname)
{
System.out.println(names);
}
}
}
next(): Finds and returns the next complete token from this scanner.
nextLine(): Advances this scanner past the current line and returns
the input that was skipped.
Try placing a scanner.nextLine(); after each nextInt() if you intend
to ignore the rest of the line.
public class StringScanner
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.println("Enter The number of students:");
int totalstudents = in.nextInt();
in.nextLine();// just to ignore the line
//store into String array
String studentname[] = new String[totalstudents];
for(int i = 0; i < studentname.length;i++)
{
System.out.println("Enter Student Names: "+i);
studentname[i] = in.nextLine();
}
for(String names:studentname)
{
System.out.println(names);
}
}
}
You can use array args[]
Need not pass number of students there.
So what ever name you pass on command prompt after java <className> shall be stored in this array and you can iterate over it.
Add in.nextLine(); after you assign this int totalstudents = in.nextInt();
use ArrayList instead of String Array
declare header file
import java.util.ArrayList;
change your code
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.println("Enter The number of students:");
int totalstudents = in.nextInt();
//store into arraylist
ArrayList<String> al = new ArrayList<String>();
for(int i = 0; i < totalstudents;i++)
{
System.out.println(i);
System.out.println("Enter Student Names: ");
al.add(in.next());
}
for(int i=0; i< al.size(); i++)
{
System.out.println(al.get(i));
}
Try this code:
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.print("Enter The number of students:");
int totalstudents = in.nextInt();
//store into String array
String studentname[] = new String[totalstudents];
for(int i = 0; i < studentname.length;i++)
{
System.out.print("Enter Student " + i + " Name:");
studentname[i] = in.nextLine();
}
for(int i = 0; i < studentname.length;i++)
{
System.out.println(studentname[i]);
}