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.
Related
This question already has answers here:
Reverse a string in Java
(36 answers)
Closed 4 years ago.
There are some assignments in Walter Savitch's Java book, where it asks you to write some code to reverse the order of a word that is entered. I came up with the following and am wondering if I could be able to optimize it as it seems a little heavy:
public static void main(String[] args) {
String statement;
System.out.print("Enter a statement to reverse: ");
statement = keyboard.nextLine();
int n;
String finalWord = "";
String letter;
for (n = statement.length(); n > 0; n--)
{
letter = statement.substring(0, 1);
finalWord = letter + finalWord;
statement = statement.substring(1);
System.out.println(finalWord);
}
System.out.println("Final work: " + finalWord);
Any insight would be appreciated.
}
import java.lang.*;
import java.io.*;
import java.util.*;
class ReverseString
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter String To Reverse:- ");
String input = sc.next();
// convert String to character array
char[] arr = input.toCharArray();
for (int i = arr.length-1; i>=0; i--)
System.out.print(arr[i]);
}
}
You can use below given code to reverse string
public class ReversString
{
public static void main(String args[])
{
String name = "Vinayak Dwivedi";
String reverseStrinf = "";
for(int i = name.length() - 1;i >= 0 ;i--)
{
reverseStrinf = reverseStrinf + name.charAt(i);
}
System.out.println("reverseStrinf:-"+reverseStrinf);
}
}
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
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));
}
}
I have a tutorial work based on vectors in java se. The task is to prompt the user to input ten words in a string and then we are supposed to split the words into single words and add each of them into a vector element. However, right at the beginning, I'm already facing problems with my codes. Right now, I even have problem finding out the size of the vectors so could you guys help me out here? Thanks!
import java.util.*;
class TenWords
{
public static void main (String [] args)
{
Vector <String> words = new Vector <String>();
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter ten words");
String a;
while(userInput.hasNext())
{
a = userInput.next();
words.add(a);
System.out.println(a);
}
int s = words.size();
System.out.println(s);
}
}
In this case userInput.hasNext() always returns true. So you need a finite loop. Use for loop
import java.util.Scanner;
import java.util.Vector;
public class TenWords {
public static void main(String[] args) {
Vector<String> words = new Vector<String>();
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter ten words");
String a;
for (int i = 0; i < 10; i++) {
a = userInput.next();
words.add(a);
System.out.println(a);
}
int s = words.size();
System.out.println(s);
}
}
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]);
}
}
}