Reading data from keyboard to store in string array - java

String s[];
System.out.println("Enter loop value");
int t = s.nextInt();
for(int i=0;i<t;i++)
{
str[i]=s.nextLine();
}
while it reading it gives null pointer exception

What you need is something like this:
Scanner s = new Scanner(System.in);
System.out.println("Enter loop value");
int t = s.nextInt(); // read number of element
s.nextLine(); // consume new line
String str[] = new String[t];
for(int i=0;i<t;i++)
{
str[i]=s.nextLine();
}
System.out.println(Arrays.toString(str));
Hope this helps.

I changed the typos and missing declarations in your code:
package snippet;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class Snippet {
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(System.in);
String str[] = new String[10];
System.out.println("Enter loop value (maximum 9)");
int t = s.nextInt();
for (int i = 0; i <= t; i++) {
str[i] = s.nextLine();
}
System.out.println("your entered lines:");
System.out.println(Arrays.toString(str));
}
}
However, I would recommend to store the values in a List instead of an Array. I also prefer using a BufferedReader to using a Scanner.

Try something like this:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter loop value");
String a[] = new String[Integer.parseInt(br.readLine())];
for (int i = 0; i < a.length; i++) {
a[i] = br.readLine();
}

//After modifying my code works well
import java.io.*;
import java.util.Scanner;
class Sample
{
public static void main(String[] args) throws Exception
{
bufferedReader();
scanner();
}
static void bufferedReader()throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Number of Strings");
int len = Integer.parseInt(br.readLine());
String a[] = new String[len];
for(int i=0; i<len; i++){
System.out.println("Enter String"+ (i+1));
a[i] = br.readLine();
}
for(String str : a)
System.out.println(str);
}
static void scanner(){
Scanner s = new Scanner(System.in);
System.out.println("Enter Number of Strings");
int len = Integer.parseInt(s.nextLine());
String a[] = new String[len];
for(int i=0; i<len; i++){
System.out.println("Enter String"+ (i+1));
a[i] = s.nextLine();
}
for(String str : a)
System.out.println(str);
}
}
But when using Scanner nextLine() skips the data when read
if any one knows please post description with example

Related

How do I reverse a number in Java using String?

I have used the below logic, but getting an exception "java.lang.StringIndexOutOfBoundsException". Help will be appreciated. Thank you!!
import java.util.Scanner;
public class Demo{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number:- ");
String number = sc.next();
for (int i = number.length(); i >= 0; i--) {
System.out.println(number.charAt(i));
}
}
}
You only need to iterate across the string halfway, swapping the characters as the indices go towards the middle. This works for even or odd length strings.
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number:- ");
char[] chars = sc.next().toCharArray();
int len = chars.length;
for (int i = 0; i < len/2; i++) {
char c1 = chars[i];
char c2 = chars[len-i-1];
chars[i] = c2;
chars[len-i-1] = c1;
}
String s = new String(chars);
System.out.println(s);
Or just use the reverse() method included in the StringBuilder class.
import java.util.Scanner;
public class Demo{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number:- ");
String number = sc.next();
for (int i = number.length() -1 ; i >= 0; i--) { // correct answer: number.lenght() -1 as array start with 0.
System.out.print(number.charAt(i)); //using print instead of println so that it display in same line
}
}
}

How do I access the String value inside a for loop?

Here I am not able to access the value of the name outside of the string even if I use other string the value is not initializing.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("\n\tWelcome to the Store");
System.out.print("\nPls enter the number of items you want to bill ");
int n = sc.nextInt();
String name;
for(int i = 1;i<=100;i++) {
System.out.print("Enter the name of the item no "+i+" ");
name = sc.next();
if (i == n) {
break;
}
}
System.out.println();
for(int m=1;m<=n;m++) {
//System.out.println(name);
}
}
You need to change name to be an array since it should contain several values.
String[] names = new String[n];
I also think you should use a while loop instead. Something like
Scanner sc = new Scanner(System.in);
System.out.println("\n\tWelcome to the Store");
System.out.print("\nPls enter the number of items you want to bill ");
int n = sc.nextInt();
String[] names = new String[n];
int i = 0;
while (i < n) {
System.out.print("Enter the name of the item no " + i + " ");
names[i] = sc.next();
i++;
}
System.out.println();
for (int m = 0; m < n; m++) {
System.out.println(names[m]);
}
Your question is not clear. But I hope this will fix it. Be sure to initialize variable n with a value that you want.
import java.util.*;
class example{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String[] name = new String[100];
int n=3; // make sure to change this one
for(int i = 1;i<=3;i++){
System.out.print("Enter the name of the item no "+i+" ");
name[i] = sc.next();
}
for(int i = 1;i<=n;i++){
System.out.print(name[i]+"\n");
}
}
}

How to read and use the String array using scanner class or other in java

How to read and use the String array using scanner class or other in java
i could read the String into array like that below
arr[0]="apple";
arr[1]="mango";
arr[2]="banana";
.
.
.
and soon
but in by using scanner class how it possible pls tell me
and any help full "for each" in java String arrays...
To read into string array and then read the populated array you could use:
public static void main(String [] args){
// to populate string array`enter code here`
Scanner sc = new Scanner(System.in);
int length = 10, pos = -1;
String arr[] = new String[length];
while(++pos < length){
System.out.print("Enter string : ");
arr[pos] = sc.nextLine();
}
// to read the already populated string array1
for(String s: arr){
System.out.println(s);
}
}
Program to read specific number of elements from the console and write them on the console.
public class Test {
public static void main(String args[]) {
System.out.println("Enter string array size");
Scanner in = new Scanner(System.in);
int i = in.nextInt();
String[] arr = new String[i];
for (int j = 0; j < i; j++) {
System.out.println("Enter next element");
arr[j] = in.next();
}
for (String s : arr) {
System.out.println("Next element[" + s+"]");
}
}
}
import java.util.Scanner;
public class StringRWrite {
public static void main(String[] args) {
Scanner sc1=new Scanner(System.in);
System.out.println("enter the length of String array");
int n=sc1.nextInt();
String[] larray=new String[n];
for(int i=0;i<n;i++){
System.out.println("enter the "+(i+1)+" String :");
larray[i]=sc1.next();
}
System.out.println("Strings Entered by user:");
for(String s:larray){
System.out.println(s);
}
}
}
import java.util.Scanner;
public class StringReadAndWrite {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("enter the length of String array");
int n=sc.nextInt();
String[] sarray=new String[n];
for(int i=0;i<n;i++){
System.out.println("enter the "+(i+1)+" String :");
sarray[i]=sc.next();
}
System.out.println("Strings Entered by user:");
for(String s:sarray){
System.out.println(s);
}
}
}
import java.util.Scanner;
public class BasketballPlayers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter the number of basketball players");
int numberOfPlayers = input.nextInt();
String[] playersArray =new String[numberOfPlayers];
for(int i=0;i< numberOfPlayers;i++){
System.out.println("enter the "+(i+1)+" String :");
playersArray[i]= input.next();
}
System.out.println("BasketBall Player names:");
for(String s:playersArray){
System.out.println(s);
}
}
}

I have to make a simple array program

import java.util.Scanner;
class testa{
public static void main(String args[]){
char m[ ] = new char[10];
int i,j;
Scanner sc = new Scanner(System.in);
for(i=0;i<5;i++){
m[i]=sc.next();//I can do it via bufferedReader but how to o it with Scanner
}
for(j=0;j<5;j++)
System.out.println(m[j]);
}
}
Now the problem is that i cannot input value and execute it correctly using Scanner class but i can with bufferedreader which i dont want to do.How do i make this program work? Sample input:qwerty
Sample output:
q
w
e
r
t
y
You could try doing :-
char c[] = new char[5];
Scanner sc = new Scanner(System.in);
String line = sc.next();
for(int i=0;i<5;i++){
c[i] = line.charAt(i);
}
This would make a char array out of the entered String.Well, if you want a char array, you could also replace the loop with
char c[] = line.toCharArray();
At the end, just print out the array.
In this line : m[i]=sc.next() it accepts the entire string "qwerty" . You might want to try something like this:
String str= sc.next();
for(int i=0;i<5;i++)
m[i] =str.charAt(i);
import java.util.Scanner; // import Scanner class to input array values from user
public class ArrayExample {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in); //Create an object of Scanner class
int[] arr=new int[10]; //declare an integer array
//input value from array
for(int i=0;i<10;i++){
arr[i]=sc.nextInt();
}
//print array values from array
for(int i=0;i<10;i++){
System.out.println(arr[i]);
}
}
}
import java.util.Scanner;
class testa{
public static void main(String args[]){
char[] m = new char[5];
Scanner sc = new Scanner(System.in);
for(int i=0;i<5;i++){
m[i]=sc.next().charAt(0);
}
for(int j=0;j<5;j++)
System.out.print(m[j] + ' ');
}
}
I believe this should work. I'm on my phone as of writing, so cannot verify.
The important correction being
.charAt(0) and System.out.print(m[j] + ' ');
Though it's not very efficient, this is the only way I can think of using Scanner.
public class testa{
public static void main(String args[]) {
Pattern pattern = Pattern.compile(".");
Scanner sc = new Scanner(System.in);
String str = null;
do {
str = sc.findInLine(pattern);
if(str!= null)
System.out.print(str.charAt(0));
System.out.print(" ");
} while (str != null);
sc.close();
}
}

Reading multiple strings in java

I have to read strings from the user based on a number n and store n strings in n different variables. I'm stuck with how to put them into different strings. Please help me out.
This is my code:
public static void main(String[] args) {
int b;
String s="";
Scanner in = new Scanner(System.in);
System.out.println("Enter verifying number: ");
b = in.nextInt();
for (int i=0; i<=b; i++) {
System.out.println("Enter a string: ");
s = in.nextLine();
}
So if b = 5, i have to input 5 strings from the user and store them in 5 different string variables. I'm able to take it from the user but not able to assign them into different variables. Can u please help me out?
Thanks.
If you know exactly the number of input then use an Array, if not use a ArrayList
With Arrays
String []inpupts = new String[b];
for (int i=0; i< b; i++) {
System.out.println("Enter a string: ");
inputs[i] = in.nextLine();
}
With ArrayList
List<String> inpupts = new ArrayList<String>();
for (int i=0; i< b; i++) {
System.out.println("Enter a string: ");
inputs.add(in.nextLine());
}
From your code (<= b) I am assuming you just started learning Java. Therefore, I edited your solution and am proposing the following, if this is okay?
public static void main(String[] args) {
int b;
Scanner in = new Scanner(System.in);
System.out.println("Enter verifying number: ");
b = in.nextInt();
//necessary to do due to Enter key pressed by user
in.nextLine();
String s[] = new String[b];
for (int i=0; i<b; i++) {
System.out.println("Enter a string: ");
s[i] = in.nextLine();
// You can check at the same time if this is what you entered
System.out.println("I have received this sring: "+s[i]+"\n");
}
Create an array and store it in an array like below:
String s[] = new String[b];//use b+1 if you need b+1 entries
for (int i=0; i<b; i++) {//use <=b is you need b+1 entries
System.out.println("Enter a string: ");
s[i] = in.nextLine();
}
You can then access your values as:
for (int i=0; i<b; i++) //use <=b is you need b+1 entries
System.out.println("Entered string was : " + s[i]);
}
Solution :
You can use something like this.
You can change your code as :
public static void main(String[] args) {
int b;
String s="";
Scanner in = new Scanner(System.in);
System.out.println("Enter verifying number: ");
b = in.nextInt();
in.nextLine(); // To get a new line
for (int i=0; i<b; i++) {
System.out.println("Enter a string: ");
s = in.nextLine();
}

Categories