How to fill an array of characters from user input? - java

I googled it a lot and found nothing!
Could someone help me with filling an array of characters from user input, please?

I googled it a lot and found nothing! Could someone help me with
filling an array of characters from user input, please?
My Google said, try this one..
Option 1 :
import java.io.*;
class array {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String tmp = br.readLine();
int length = tmp.length();
char c[] = new char[length];
tmp.getChars(0, length, c, 0);
CharArrayReader input1 = new CharArrayReader(c);
int i;
System.out.print("input1 is:");
while ((i = input1.read()) != -1) {
System.out.print((char) i);
}
}
}
Option 2:
class array
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Please enter elements...");
char[] a=sc.next().toCharArray();
System.out.println("Array elements are : ");
for (int i=0;i<a.length;i++)
System.out.println(a[i]);
}
}
But, in this case, it won't accept after space character.
Before, start your coding in Java, you must know these terms :
BufferedReader
Exception handling

//more fun ...............
public class test3 {
public static void main(String args[])
{
char crr[]=new char[100];
Scanner inputs=new Scanner(System.in);
System.out.println("enter the string");
for(int i=0;i<10;i++)
{
char c=inputs.next().charAt(0);
crr[i]= c;
}
for(int i=0;i<10;i++)
{
System.out.println(" " +crr[i]);
}
}
}

If you want to be able to read a word and split it into an array of characters you can use.
char[] chars = scanner.next().toCharArray();

/* program below takes an string from user, splits into character and display as array of characters. */
package com.demo.mum;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* #author cyruses
*
*/
public class CharacterArray {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the string:");
String tmp = br.readLine();
int strLen = tmp.length();
char c[] = new char[strLen];
for (int i = 0; i < c.length; i++) {
c[i] = tmp.charAt(i);
}
System.out.println("Displaying character Array");
for (int i = 0; i < c.length; i++) {
System.out.println(c[i]);
}
}

This code is part of my program for linear searching, I fixed the issue I was facing. But I want explanation about why I was getting exception on charAt(x) and not on charAt(0).
System.out.println("Enter Your Data in character");
for(x=0;x<char_array.length;x++)
{
Scanner input_list_char = new Scanner(System.in);
char_array[x]=input_list_char.next().charAt(0); //it works
char_array[x]=input_list_char.next().charAt(x); // give me exception
}

To input a character array from user
import java.io.*;
class CharArrayInput {
public static void main(String args[]) throws IOException {
/*using InputReader and BufferedReader class
to fill array of characters from user input.
*/
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
//Take size of array from user.
System.out.println("Please enter size of array")
int n = Integer.parseInt(br.readLine());
//Declare a character array
char arr[] = new char[n];
//loop to take input of array elements
for(int i=0; i < n; i++){
arr[i] = (char)br.read();
}
}
}

You can't take input directly in charArray using nextChar() because there is no nextChar() in Java. You first have to take input in String then fetch character one by one.
import java.util.*;
class CharArray{
public static void main(String[] args)
{
Scanner scan=new Scanner(System.in);
char ch[]=new char[11];
String s = scan.nextLine();
for(int i=0;i<=10;i++)
ch[i]=s.charAt(i); //Input in CharArray
System.out.println("Output of CharArray: ");
for(int i=0;i<=10;i++)
System.out.print(ch[i]); //Output of CharArray
}
}

this will not work if user print input in form of string like as...
5 8
########
#..#...#
####.#.#
#..#...#
########
in this if we use char c=inputs.next().charAt(0); it will take only first of every string ,
It will be better to use
*Scanner s = new Scanner(System.in);
int n = s.nextInt();
int m = s.nextInt();
char[][] in = new char[m+1][n+1];
for(int i = 0;i<n;i++) {
String st = s.next();
for(int j = 0;j<m;j++) {
in[i][j] = st.charAt(j);
}
}*

class charinarray
{
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
System.out.println("Please enter char elements...");
char[] a=input.next().toCharArray();
System.out.println("Array char elements are : ");
for (int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
}

Related

I must process the sentence by calling the method rather than processing the string directly in my main method! PS i need to use void method

import java.util.Scanner;
public class PrintVertical
{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please enter a sentence: ");
String input = in.nextLine();
int i =0;
System.out.println("Your sentence printed vertically is:");
for(i = 0; i < input.length(); i++) {
char letter = input.charAt(i);
System.out.println(letter);
}
}
}
Solution
Write a new method besides the main-method in your class and mark it with the keyword static.(Class Methods)
Give it a String as Parameter. To call it with your user input.
The Static Function:
public static void doVertic(String inp){
int i =0;
System.out.println("Your sentence printed vertically is:");
for(i = 0; i < input.length(); i++) {
char letter = input.charAt(i);
System.out.println(letter);
}
}
Then call it with your scanned input inside the main method
Call in Main Method:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please enter a sentence: ");
String input = in.nextLine();
<Classname>.doVertic(input);
}
Note: The <Classname> have to be your Classname

Java program for splitting strings with line breaks and stops with no entry not working?

This is the problem I'm trying to solve:
My code is the following:
import java.util.Scanner;
public class LineByLine {
public static void main(String[] args) {
while (true) {
Scanner scanner = new Scanner(System.in);
String sentence = String.valueOf(scanner.nextLine());
String[] pieces = sentence.split(" ");
for (int i = 0; i < pieces.length; i++) {
System.out.println(pieces[i]);
}
if (sentence.equals("")) {
break;
}
}
}
}
My code is showing as wrong and I'm unsure why. Any explanations?
You should arrange your code like:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
String sentence = String.valueOf(scanner.nextLine());
String[] pieces = sentence.split(" ");
for (int i = 0; i < pieces.length; i++) {
System.out.println(pieces[i]);
}
if (sentence.equals("")) {
break;
}
}
scanner.close();
}
Also you could use hasNext method instead of while(true) part:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String sentence = scanner.nextLine();
String[] pieces = sentence.split(" ");
for (int i = 0; i < pieces.length; i++) {
System.out.println(pieces[i]);
}
}
scanner.close();
}
You'll need to place:
Scanner scanner = new Scanner(System.in);
outside of the while loop.
The reason:
You only need to create a single Scanner object. This has to be done before you enter the loop since the instantiation will consume the standard input - this means that after the first iteration of the loop, there will be no standard input left to instantiate the object once again.
You can also think about it more mechanically than that:
If you had a loop that was meant to iterate through numbers, you wouldn't want to be resetting your loop counter each time, right? Its quite a similar thing in this case.

Cant understand why i am getting an infinite loop. Java. How to trigger EoF without typing exit

I am very new to java and this community. I am looking for someone to possibly be able to explain why my code is going into an infinite loop. I believe it has something to do with my while loop. The program compiles but when I enter a phrase i want for my acronym builder to create the program dosent do anything, it just blinks at the next line. When i press ctrl c to exit, it then shows the acronym.
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class Acronym{
public static void main(String[] args) {
String phraseToChange = "";
int wordCounter = 0;
char[] acroynmArray = new char [100];
Scanner input = new Scanner(System.in);
System.out.println("This program builds acronyms");
System.out.println("Enter a phrase:");
while (input.hasNext() )
{
phraseToChange = input.next();
acroynmArray[wordCounter] = phraseToChange.charAt(0);
wordCounter++;
}
for (int i = 0;i < wordCounter ; i++ )
{
System.out.print(acroynmArray[i]);
}
}
}
The problem is not truly caused by your while loop but because the fact that scanner will keep asking user new input (system.in stream will always open) until EOF. Therefore, the problem can be solve using StringTokenizer if it's allowed by your professor. Down here is the code example
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class Acronym{
public static void main(String[] args) {
String phraseToChange = "";
boolean phraseToChange2 = true;
int wordCounter = 0;
char[] acroynmArray = new char [100];
Scanner input = new Scanner(System.in);
System.out.println("This program builds acronyms");
System.out.println("Enter a phrase:");
String nextLine = input.nextLine();
StringTokenizer st = new StringTokenizer(nextLine, " ");
while (st.hasMoreTokens())
{
phraseToChange = st.nextToken();
acroynmArray[wordCounter] = phraseToChange.charAt(0);
wordCounter++;
}
System.out.println("reach here");
for (int i = 0;i < wordCounter ; i++ )
{
System.out.print(acroynmArray[i]);
}
}
}
The reason of why your loop never ends it the fact that System.in stream is always open. You should change the condition to while (!phraseToChange.equals("exit")) or something. Then the user will be able to finish the input by sending "exit" string to your program.
If you don't have to use a while loop with input.hasNext() you can use this. May want to clean up where necessary, but I believe this does what you want.
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class Acronym {
public static void main(String[] args) {
String phraseToChange = "";
int wordCounter = 0;
char[] acroynmArray = new char[100];
Scanner input = new Scanner(System.in);
System.out.println("This program builds acronyms");
System.out.println("Enter a phrase:");
String[] line = input.nextLine().split(" ");
for (int i = 0; i < line.length; i++) {
phraseToChange = line[i];
acroynmArray[i] = phraseToChange.charAt(0);
wordCounter++;
}
for (int i = 0; i < wordCounter; i++) {
System.out.print(acroynmArray[i]);
}
}
}
Sample build output:
run:
This program builds acronyms
Enter a phrase:
Google Rocks Socks
GRSBUILD SUCCESSFUL (total time: 4 seconds)
Code snippet that causes the change:
String[] line = input.nextLine().split(" ");
for (int i = 0; i < line.length; i++) {
phraseToChange = line[i];
acroynmArray[i] = phraseToChange.charAt(0);
wordCounter++;
}
Alternatively you could use this:
public static void main(String[] args) {
String phraseToChange = "";
int wordCounter = 0;
char[] acroynmArray = new char [100];
Scanner input = new Scanner(System.in);
System.out.println("This program builds acronyms");
System.out.println("Enter a phrase:");
String line = input.nextLine(); // Obtain user entered line
acroynmArray[0] = line.charAt(0); // First letter is known; set it
wordCounter++; // increment wordCounter
//Loop the characters in the retrieved line
for(int i = 0; i < line.length(); i++){
// If it's whitespace then we know the next character must be the letter we want
if(Character.isWhitespace(line.charAt(i))){
acroynmArray[wordCounter] = line.charAt(i+1); // Set it
wordCounter++;
}
}
But as Tom said in my deleted post, this is quite fragile code. It works, until it doesn't, as in it wouldn't take much to break it as it doesn't handle trailing and starting whitespaces

Creating a string array from random user input

I want to have a user input a random string of letters, put those in an array, then sort them alphabetically. Problem I have is putting the input into an array. What I have is:
import java.util.Scanner;
public class ArraySort {
public static void main(String[] args)
{
System.out.println("Enter letters");
Scanner kb = new Scanner(System.in);
String input = kb.nextLine();
int stringLength = input.length();
String[] stringArray = new String[stringLength];
for (int i = 0; i < stringLength; i++)
{
stringArray[i] = input;
}
System.out.println(stringArray);
}
}
This gives me [Ljava.lang.String;#55f96302 when I print.
You have two problems, you're not printing the Array correctly, and you're storing the entire input in each cell of the array. Try:
for (int i = 0; i < stringLength; i++)
{
stringArray[i] = input.charAt(i)+"";
System.out.println(stringArray[i]);
}
You are making 2 major mistakes:
1) You are assigning each string the whole input stringArray[i] = input;
2) You have to iterate over each element of your string array.
In Java8 this could be done easily with Arrays.stream().
A corrected Version of your code is:
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
System.out.println("Enter letters");
Scanner kb = new Scanner(System.in);
String input = kb.nextLine();
int stringLength = input.length();
String[] stringArray = new String[stringLength];
for (int i = 0; i < stringLength; i++)
{
stringArray[i] = Character.toString(input.charAt(i));
}
Arrays.stream(stringArray).forEach(System.out::print);
}
}
Btw. String[] stringArray=input.split(""); would be much shorter.
Additional:
If you want sorted output:
stringArray=Arrays.stream(stringArray).sorted().toArray(String[]::new);
Arrays.stream(stringArray).forEach(System.out::print);
And you are done.
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
System.out.println("Enter letters");
Scanner kb = new Scanner(System.in);
String input = kb.nextLine();
String[] stringArray=input.split("");
stringArray=Arrays.stream(stringArray).sorted().toArray(String[]::new);
Arrays.stream(stringArray).forEach(System.out::print);
}
}
To get the String form of an array, use the Arrays class toString method.
System.out.println(Arrays.toString(stringArray));
Also note the sort method of this class, although in the code's current state each item of your array will be equal to the input line.

For looping to add variables for a Scanner input

So I'm new to Java and I figured I'd do something simple like a for loop to print out an array of strings or something,
My code ended up like this:
package package.four;
import java.util.Scanner;
public class arrayrecurse {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.println("Please enter 5 words");
String a = in.next();
String b = in.next();
String c = in.next();
String d = in.next();
String e = in.next();
String[] s = {a, b, c, d, e};
for(int i = 0; i< s.length;){
System.out.println(s[i]);
i++;
}
in.close();
}
}
It works fine but my question is if it's possible to make a for loop cycle through variables.
For examples if I wanted something like:
for(words = 5; words > 0;){
String a = in.next();
a++}
Where would it change the variables each time I enter a new word.
Would it be possible to do something like that or do I need to type out the String variable = in.next(); every time I want to enter a new word input from the console?
You can call next() inside the loop, but you need to declare the variable outside the loop if you want to use it afterwards, also, there is no ++ operator for String or array in Java:
String[] inputs = new String[5];
for (int i = 0; i < inputs.length; ++i)
{
inputs[i] = in.next();
}
Use an ArrayList to store the input variables.
That is:
import java.util.*;
public static void main(String[] args) {
List<String> inputVars = new ArrayList<>();
Scanner sc = new Scanner(System.in);
while (sc.hasNext())
{
inputVars.add(sc.next());
}
for (String s: inputVars)
{
System.out.println(s);
}
}
Or alternatively, if you want to change the contents of the ArrayList:
public static void main(String[] args) {
List<String> inputVars = new ArrayList<>();
Scanner sc = new Scanner(System.in);
while (sc.hasNext())
{
inputVars.add(sc.next());
}
for (int i = 0; i < inputVars.size(); i++)
{
System.out.println(inputVars.get(i));
//Change the variable
inputVars.set(i, "Hello, " + inputVars.get(i));
}
}

Categories

Resources