How to I go from a String to an Array - java

I want to change my strings into array lists in my scanner program. I know that I have to use the .split method, but I am not sure how. I will use this example:
This is a good class with JAVA -> [This, is, a, good, class, with, Java]
This is what I have so far:
import java.util.*;
public class scanner_LAB {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a sentance with the word \"java\" in it: ");
// input and end program
System.out.println();
System.out.println("Done - Press enter key to end program");
String line = input.nextLine();
System.out.println(line);
// length
int length = line.length();
System.out.println("Your sent " + length);
// upper case and lower case
String lowerCase = line.toLowerCase();
System.out.println(lowerCase);
String upperCase = line.toUpperCase();
System.out.println(upperCase);
System.out.println(lowerCase.indexOf("java"));
// java to Java
System.out.println(line.substring(0,line.toLowerCase().indexOf("java")) + "Java" + line.substring(line.toLowerCase().indexOf("java")+4, line.length()));
// java to JAVA
System.out.println(line.substring(0,line.toLowerCase().indexOf("java")) + "JAVA" + line.substring(line.toLowerCase().indexOf("java")+4, line.length()));
// string to arrays
}
}

You can use the split function of string to split the string into array.
String[] strArray = line.split(" ");

To answer your question about using the split method, this is the general way to use it
// string to arrays
String[] words = line.split(" ");
for(String word: words)
System.out.println(word);
I ran your code and this works four your intended purpose (I've just commented out some of your code that wasn't related to this question)
import java.util.*;
public class scanner_LAB {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a sentance with the word \"java\" in it: ");
// input and end program
//System.out.println();
//System.out.println("Done - Press enter key to end program");
String line = input.nextLine();
System.out.println(line);
// length
int length = line.length();
System.out.println("Your sent " + length);
// upper case and lower case
String lowerCase = line.toLowerCase();
System.out.println(lowerCase);
String upperCase = line.toUpperCase();
System.out.println(upperCase);
System.out.println(lowerCase.indexOf("java"));
// java to Java
//System.out.println(line.substring(0,line.toLowerCase().indexOf("java")) + "Java" + line.substring(line.toLowerCase().indexOf("java")+4, line.length()));
// java to JAVA
//System.out.println(line.substring(0,line.toLowerCase().indexOf("java")) + "JAVA" + line.substring(line.toLowerCase().indexOf("java")+4, line.length()));
// string to arrays
String[] words = line.split(" ");
System.out.println(Arrays.asList(words));
}
}

Related

Storing user input in a string array

I am a beginner to java. I try to write a program to read a series of words from the command-line arguments, and find the index of the first match of a given word. Like user can enter "I love apple", and the given word is "apple". The program will display "The index of the first match of ‘apple’ is 2".
What I did so far does not work. Is it my way of storing the input into the string array not correct?
import java.util.Scanner;
public class test {
public static void main(String [] args) {
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
int num=1;
String sentence[]=new String[num];
for(int i=0; i< num; i++) {
sentence[i] = input; // store the user input into the array.
num = num+1;
}
System.out.println("Enter the given words to find the index of its first match: ");
Scanner sc2 = new Scanner(System.in);
String key = sc2.next();
for(int j=0; j<num; j++) {
while (sentence[j].equals(key)) {
System.out.println("The index of the first match of "+key+" is "+j);
}
}
}
}
String array is not required in your solution.
Try this :-
System.out.println("enter sentence ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
System.out.println("enter the given word to fin the index ");
sc = new Scanner(System.in);
String toBeMatched = sc.nextLine();
if (input.contains(toBeMatched)) {
System.out.println("index is " + input.indexOf(toBeMatched));
} else {
System.out.println("doesn't contain string");
}
I have made the following changes to make your code work. Note you were storing the input string incorrectly. In your code, the entire code was being stored as the first index in the array. You don't need the first for-loop as we can use the function .split() to distinguish each word into a different index in the array. Rest of the code stays as it is.
public class ConfigTest {
public static void main(String[] args) {
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
// Use this to split the input into different indexes of the array
String[] sentence = input.split(" ");
System.out.println("Enter the given words to find the index of its first match: ");
Scanner sc2 = new Scanner(System.in);
String key = sc2.next();
for (int i = 0; i < sentence.length; i++) {
if (sentence[i].equals(key)) {
System.out.println("The index of the first match of " + key + " is " + i);
}
}
}
}
I think you have a scope problem. sentence[] is declared and instantiated in your first forloop. Try moving the declaration outside of the loop and you should do away with the error.
I also noticed a couple of errors. You could try this
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Enter Sentence");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String sentence[] = input.split("\\s");
System.out.println("Enter Word");
Scanner sc2 = new Scanner(System.in);
String key = sc2.next();
int index = 0;
for(String word : sentence)
{
if(word.equals(key))
{
System.out.println("The index of the first match of " + key + " is " + index);
break;
}
index++;
}
}
Turtle
sentence variable is only defined inside the for loop, it needs to be declared outside it
You can use the first Scanner (sc) declared variable again instead of declaring another one (sc2)
sentence[i] = input -- will mean -- sentence[0] = "I love apple"
Scanner variable can do all the work for you for the input into the array instead of a for loop
String[] a = sc. nextLine(). split(" ");
This will scan an input of new line and separate each string separated by a space into each array.
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String[] sentence = sc. nextLine(). split(" ");
System.out.println("Enter the given words to find the index of its first match: ");
String key = sc.nextLine();
for(int j=0; j<num; j++) {
if (sentence[j].matches(key)) {
System.out.println("The index of the first match of "+ key +" is "+ j);
}
}
Declare the String [] sentence outside the for loop. It is not visible outside the first for block.
The sentence array is created over and over again during the iteration of the for loop. The loop is not required to get the String from the command line.
Edited my answer and removed the use of any for loops, Arrays.asList() will take the words array and fetch the index of the word from the resulting List.
public static void main(String[] args) throws IOException {
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
System.out.println("Enter the given word to find the index of its first match: ");
Scanner wordInput = new Scanner(System.in);
String key = wordInput.next();
String[] words = input.split(" ");
int occurence = Arrays.asList(words).indexOf(key);
if(occurence != -1){
System.out.println(String.format("Index of first occurence of the word is %d", occurence));
}
}
You just need to declare sentence array outside the for loop, as for now, the issue is of scope.For more on the scope of a variable in java . Also, this is not you intend to do, you intended to take input as a command line.
So, the input which you will get will come in String[] args. For more on command line arguments check here.

homework parsing strings: removing comma from string (java zybooks)

I am trying to get the strings to separate, and WITHOUT the comma.
We haven't learned anything like arrays, this is an intro class.
Everything I find on here just keeps giving me errors or does nothing to my code in zybooks.
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // Input stream for standard input
Scanner inSS = null; // Input string stream
String lineString = ""; // Holds line of text
String firstWord = ""; // First name
String secondWord = ""; // Last name
boolean inputDone = false; // Flag to indicate next iteration
// Prompt user for input
System.out.println("Enter input string: ");
// Grab data as long as "Exit" is not entered
while (!inputDone) {
// Entire line into lineString
lineString = scnr.nextLine();
inSS = new Scanner(lineString);
firstWord = inSS.next();
lineString.split(",");
// Output parsed values
if (firstWord.equals("q")) {
System.out.println("Enter input string: ");
inputDone = true;
}
//This may be where I am messing up??
else if (lineString.contains(",")) {
secondWord = inSS.next();
System.out.println("First word: " + firstWord);
System.out.println("Second word: " + secondWord);
System.out.println();
} else {
System.out.println("Error: No comma in string");
System.out.println("Enter input string: ");
}
}
return;
}
}
I am messing up somewhere and keep getting different error codes as I keep messing with it...
"Enter input string:
First word: Jill,
Second word: Allen"
When it should be
"Enter input string:
First word: Jill
Second word: Allen"
And then also as the computer enters more data I start getting this message:
"Exception in thread "main" java.util.NoSuchElementException"
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at ParseStrings.main(ParseStrings.java:44)"
One of the possibilities (if you didn't learn about arrays) is to use StringBuilder and remove commas or simply loop over input string and if character at let's say index 8 is comma, you do yourString.substring(0,8);, and then print the second word as yourString.substring(10, yourstring.length); I put starting index of 10 in the second substring because you want to skip comma and a space that's separating first and last name. Here is code sample for using nothing but String class, it's methods and for loop:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first name and last name: ");
String str = in.nextLine();
int indexOfComma = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ',')
indexOfComma = i;
}
System.out.println("First name is: " + (str.substring(0, indexOfComma)));
System.out.println("Last name is: " + (str.substring(indexOfComma + 2, str.length())));
}
}
Or as I see you tried using split() (but since you said you didn't learn arrays yet I posted solution above), you can do it with .split() like this:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first name and last name: ");
String[] name = in.nextLine().split(", ");
System.out.println("First name is: " + name[0]);
System.out.println("Last name is: " + name[1]);
}
}
Also, here is an example with StringBuilder class:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first name and last name: ");
StringBuilder name = new StringBuilder(in.nextLine());
name.deleteCharAt(name.indexOf(","));
System.out.println("Full name is: " + name);
}
}
Your error happens when the Scanner reads all the data, such as calling the nextLine method and there's no line... Or next method when you didn't put a space after the comma
By default, the Scanner uses whitespace as a delimiter. If you want to add a comma delimiter before any whitespace, you can try this
Scanner sc=new Scanner(System.in);
sc.useDelimiter(",?\\s+");
Now, sc.next() will read only Hello from Hello, World, and a second call to it should return World
Or you can use the array you made
String[] words = lineString.split(",");
String first = words[0]:
String second = words[1];

Java basic usage of string [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I am trying to code a program that allows to enter various words(step by step) until one types in "quit" .
I am having trouble stopping the loop (even with the word quit typed, it doesn't stop)
Using System.out.println(sum); I can check that the words are adding up, but it never stops..
((Summary : if(string == "quit") does not work and for (String end = "quit"; string!=end;) does not work ))
Sorry if its hard to read. its my second day coding :(
public static void main(String[] args) {
java.util.Scanner scanner = new java.util.Scanner(System.in);
String sum = "";
System.out.println("Type in a word");
String string = scanner.nextLine();
if (string == "quit")
{System.out.println("Ending system");
}
else{
for(String end = "quit"; string!=end; )
{
sum = sum + " " + string;
System.out.println(sum);
System.out.println("Type in another word");
String stringextra = scanner.nextLine();
if(stringextra == "quit"){break;}
string = stringextra;
}
scanner.close();
System.out.println("Stopping... due to the word quit");
System.out.println("all the words typed are " + sum);
}
}}
Strings string and "quit" are not the same objects(as stored in the jvm) yet equal so checking with == will not work.
You need to use:
string.equals("quit")
see Object.equals() for more information
As pointed out in the other answer you need to use .equals() to compare strings. Also, your for loop is incorrect. A while loop is what is normally used in this case:
public class end_on_quit {
public static void main(String[] args)
{
java.util.Scanner scanner = new java.util.Scanner(System.in);
String sum = "";
System.out.println("Type in a word");
String string = scanner.nextLine();
while ( ! string.equals("quit") )
{
sum = sum + " " + string;
System.out.println(sum);
System.out.println("Type in another word");
string = scanner.nextLine();
}
System.out.println("Ending system");
scanner.close();
System.out.println("Stopping... due to the word quit");
System.out.println("all the words typed are " + sum);
}
}
Easiest way to doing something like your code using do while so your code running until user write quit. I will give you simple example :
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String sum = "";
System.out.println("Type in a word");
String stringextra = scanner.nextLine();
if (stringextra.equalsIgnoreCase("quit")) {
System.out.println("Bye bye");
System.exit(0);
} else {
do {
sum = sum + " " + stringextra;
System.out.println(sum);
System.out.println("Type in another word");
stringextra = scanner.nextLine();
} while (!stringextra.equalsIgnoreCase("quit"));
}
scanner.close();
System.out.println("Stopping... due to the word quit");
System.out.println("all the words typed are " + sum);
}
I hope this help you, good luck.
You should use equalsto compare strings. In this case for you example is better use while instead of for to loop.
When you use equalsIgnoreCase it means that is no matter if the word is upper case or lower case (is the same).
The application finishes when the user types "quit or ends or QUIT or ENDS"
Example:
public static void main(String[] args) {
java.util.Scanner scanner = new java.util.Scanner(System.in);
String sum = "";
System.out.println("Type in a word");
String string = scanner.nextLine();
while (!string.equalsIgnoreCase("quit")) {
sum = sum + " " + string;
System.out.println(sum);
System.out.println("Type in another word");
string = scanner.nextLine();
if (string.equalsIgnoreCase("ends")) {
string = "quit";
}
}
System.out.println("Ending system");
scanner.close();
System.out.println("Stopping... due to the word quit");
System.out.println("all the words typed are " + sum);
System.exit(0);
}
Output:
Type in a word
hi
Type in another word
this
Type in another word
an
Type in another word
example
Type in another word
ENDS
Ending system
Stopping... due to the word quit
all the words typed are hi this an example
Process finished with exit code 0
Simply do System.exit(0) after System.out.println("Ending system");

Java: How do I ensure, or make a user, input a comma in a string?

First off, I am brand new to both Java and to this website. I am going to ask my question as thoroughly as I can. However, please let me know if you think I left something out.
I am working on a school assignment, and I am stuck on the second portion of it. I am able to prompt the user, but can not for the life of me, figure out how to ensure that the input string contains a comma. I did try searching this site, as well as Googling it, and haven't been able to find anything. Perhaps I am not wording the question appropriately.
(1) Prompt the user for a string that contains two strings separated by a comma.
(2) Report an error if the input string does not contain a comma. Continue to prompt until a valid string is entered. Note: If the input contains a comma, then assume that the input also contains two strings.
So far I have this:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // Input stream for standard input
Scanner inSS = null; // Input string stream
String lineString = ""; // Holds line of text
String firstWord = ""; // First name
String secondWord = ""; // Last name
boolean inputDone = false; // Flag to indicate next iteration
// Prompt user for input
System.out.println("Enter string seperated by a comma: ");
// Grab data as long as "Exit" is not entered
while (!inputDone) {
// Entire line into lineString
lineString = scnr.nextLine();
// Create new input string stream
inSS = new Scanner(lineString);
// Now process the line
firstWord = inSS.next();
// Output parsed values
if (firstWord.equals("q")) {
System.out.println("Exiting.");
inputDone = true;
if else (lineString != ",") { // This is where I am stuck!
System.out.print("No comma in string");
}
} else {
secondWord = inSS.next();
System.out.println("First word: " + firstWord);
System.out.println("Second word: " + secondWord);
System.out.println();
}
}
return;
}
}
I know my "if else" is probably not correct. I just don't know where to begin for this particular command. Unfortunately my eBook chapter did not cover this specifically. Any thoughts would be greatly appreciated. Thank you so much!
I suspect you want to assert if the input contains a comma, and at least one letter either side. For this you need regex:
if (!input.matches("[a-zA-Z]+,[a-zA-Z]+")) {
System.out.print("Input not two comma separated words");
}
Since you are looking for a string with a comma in it and you want to get the string “Before” the comma and the string “After” the comma, then string.split(‘,’) is what you want. Asking if the string “Contains” a comma gives you no information about the string before or after the comma. That’s where string.split() helps. Since you don’t care “Where” the comma is you simply want the string before the comma and the string after the comma. The string.split(‘,’) method will return a string array containing the strings that are separated by commas (in your case) or any character.
Example:
string myString = “firstpart,secondpart”;
… then
string[] splitStringArray = myString.Split(‘,’)
This will return a string array of size 2 where
splitStringArray[0] = “firstpart”
splitStringArray[1] = “secondpart"
with this info you can also tell if the user entered the proper input… i.e…
if the splitStringArray.Length (or Size) = 0, then the user did not input anything, if the splitStringArray.Length (or Size) = 1 then the user input 1 string with no commas… might check for exit here. If the splitStringArray.Length (or Size) = 2 then the user input the string properly. if the splitStringArray.Length (Size) > 2 then the user input a string with more than 1 comma.
I hope that helps in describing how string.split works.
Your code however needs some work… without going into much detail below is a c# console while loop as an example:
inputDone = false;
while (!inputDone)
{
Console.Clear();
Console.WriteLine("Enter string seperated by a comma: ");
lineString = Console.ReadLine();
string[] splitStringArray = lineString.Split(',');
// check for user to quit
if (splitStringArray.Length == 1)
{
if (splitStringArray[0] == "q")
{
inputDone = true;
Console.Clear();
}
else
{
// 1 string that is not "q" with no commas
}
}
if (splitStringArray.Length == 2)
{
// then there are exactly two strings with a comma seperating them
// or you may have ",string" or "string,"
Console.WriteLine("First word: " + splitStringArray[0]);
Console.WriteLine("Second word: " + splitStringArray[1]);
Console.ReadKey();
}
else
{
Console.WriteLine("Input string empty or input string has more than two strings seperated by commas");
Console.ReadKey();
}
}
Hope that helps.
This worked for me:
import java.util.Scanner;
import java.io.IOException;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
Scanner inSS = null;
String lineString = "";
String firstWord = "";
String nextWord = "";
System.out.println("Enter input string: ");
while (lineString.matches("q") == false) {
lineString = scnr.nextLine();
lineString = lineString.replaceAll(",",", ");
inSS = new Scanner(lineString);
int delimComma = lineString.indexOf(",");
if ((delimComma <= -1) && (lineString.matches("q") == false)) {
System.out.println("Error: No comma in string");
System.out.println("Enter input string: ");
}
else if ((delimComma <= -1) && (lineString == null || lineString.length() == 0 || lineString.split("\\s+").length < 2) && (lineString.matches("q") == false)) {
System.out.println("Error: Two words");
System.out.println("Enter input string: ");
}
else if (lineString.matches("q") == false) {
firstWord = inSS.next();
nextWord = inSS.nextLine();
System.out.println("First word: " + firstWord.replaceAll("\\s","").replaceAll("\\W","").replaceAll("\\n",""));
System.out.println("Second word: " + nextWord.replaceAll("\\s","").replaceAll("\\W","").replaceAll("\\n",""));
System.out.println("\n");
System.out.println("Enter input string: ");
}
continue;
}
return;
}
}

I am having trouble with this String Parser, how can I approach it?

Create a String variable and assign your full name to the variable.
Using the String's substring method print out your first name, middle name, and last name on three separate lines.
Modify your program so that it creates a "Scanner" object to allow the user to type in any three names and store it in the String variable.
Modify your program so that it will print out the three names on separate lines no matter what three names the user enters (Hint: use the String's indexof method).
So for this problem, I am doing it in Java. Here is what I have so far. Thank you!
package stringparser;
import java.util.Scanner;
public class StringParser
{
public static void main(String[] args)
{
String Name = "Billy Bob Joe";
String first = Name.substring(0,5);
String middle = Name.substring(6,12);
String last = Name.substring(13,16);
System.out.println("First name: " + first);
System.out.println("Middle name: " + middle);
System.out.println("Last name: " + last);
Scanner in = new Scanner(System.in);
System.out.print("Type any 3 names: ");
System.out.print("First name: ");
String a = in.nextLine();
System.out.print("Second name: ");
String b = in.nextLine();
System.out.print("Third name: ");
String c = in.next();
}
}
2 ways I interpret this question.
Use Scanner 3 times
Use indexOf to find the nearest space character of the one console input.
In all, I find it painfully inefficient to use String.indexOf
Quickest way, but not necessarily the best way.
public StringParser () {
Scanner in = new Scanner(System.in);
String name = in.nextLine();
System.out.println(name.replace(" ", "\n")); // replacing all spaces with new line characters
}
This program will split the string with space and print all of them as result. You can edit the for loop condition as per your need. Hope it helps :)
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String str = in.nextLine();
String[] names = str.split(" ");
for(int i = 0; i < names.length; i++)
{
System.out.println(names[i]);
}
}

Categories

Resources