I have to make a simple array program - java

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();
}
}

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
}
}
}

I am trying to print a pattern but its not print it properly

import java.util.Scanner;
public class Pattern{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
String d = sc.nextLine();
System.out.println(d);
String[] ds = d.split(",");
for(int i=0;i<ds.length;i++){
for(int j=i+1;j<=Integer.parseInt(ds[i]);j++) {
System.out.print("*");
}
System.out.println();
}
}
}
it print 3 stars in second line but i pass the value 1,4 so it print the output in first line print 1 star and in second line print 4 stars but in output it shows 3 stars in second line not 4 stars how i solve this problem.
j should start at 0 (and condition be strictly <, or 1 and <=):
for(int j=0;j<Integer.parseInt(ds[i]);j++)
Try this code:
import java.util.Scanner;
public class Main
{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
String d = sc.nextLine();
System.out.println(d);
String[] ds = d.split(",");
for(int i=0;i<ds.length;i++){
for(int j=0;j<Integer.parseInt(ds[i]);j++)
{
System.out.print("*");
}
System.out.println();
}
}
}
You need to change your inner loop, the value of j should start from 0 and not from i+1 and the condition of the loop should be j<Integer.parseInt(ds[i])
import java.util.Scanner;
public class Pattern
{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
String d = sc.nextLine();
System.out.println(d);
String[] ds = d.split(",");
for(int i=0;i<ds.length;i++){
for(int j=1;j<=Integer.parseInt(ds[i]);j++)
{
System.out.print("*");
}
System.out.println();
}
}
}
Update the variable j to 1 instead of i+1.

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);
}
}
}

Scanning multiple lines using single scanner object

I a newbie to java so please don't rate down if this sounds absolute dumb to you
ok how do I enter this using a single scanner object
5
hello how do you do
welcome to my world
6 7
for those of you who suggest
scannerobj.nextInt->nextLine->nextLine->nextInt->nextInt,,,
check it out, it does not work!!!
thanks
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.printf("Please specify how many lines you want to enter: ");
String[] input = new String[in.nextInt()];
in.nextLine(); //consuming the <enter> from input above
for (int i = 0; i < input.length; i++) {
input[i] = in.nextLine();
}
System.out.printf("\nYour input:\n");
for (String s : input) {
System.out.println(s);
}
}
Sample execution:
Please specify how many lines you want to enter: 3
Line1
Line2
Line3
Your input:
Line1
Line2
Line3
public class Sol{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
}
}
By default, the scanner uses space as a delimiter. In order to scan by lines using forEachRemaining, change the scanner delimiter to line as below.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("\n");
scanner.forEachRemaining(System.out::println);
}
try this code
Scanner in = new Scanner(System.in);
System.out.printf("xxxxxxxxxxxxxxx ");
String[] input = new String[in.nextInt()];
for (int i = 0; i < input.length; i++) {
input[i] = in.nextLine();
}
for (String s : input) {
System.out.println(s);
}
You can try only with lambda too:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
scanner.forEachRemaining(input -> System.out.println(input));
}
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int first = console.nextInt();
String second = console.nextLine();
String third = console.nextLine();
int fourth = console.nextInt();
System.out.println(first);
System.out.println(second);
System.out.println(third);
System.out.println(fourth);
}
so you get them in line by line
may be we can use this approach:
for(int i = 0; i < n; i++)
{
Scanner sc1 = new Scanner(System.in);
str0[i] = sc1.nextLine();
System.out.println(str0[i]);
}
that is we create the scanner object every time before we read the nextLine. :)

Reading data from keyboard to store in string array

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

Categories