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];
Related
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));
}
}
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.
This program needs to print a.b.c. but it prints a.b.c...
How do I eliminate the last dot in output.
The program has to work with user ending loop with "."
import java.util.Scanner;
public class dots1 {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
String input;
String output = "";
System.out.println("Hello! I print out an acronym. ");
do {
System.out.println("Please Enter a Character");
input = s.nextLine();
output = output+input+".";
} while (!input.equals("."));
System.out.println(output);
}
}
Because your exit condition is "." and you add it to output and add another dot. Try following:
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
String input = "";
String output = "";
System.out.println("Hello! I print out an acronym. ");
while (true) {
System.out.println("Please Enter a Character");
input = s.nextLine();
if(input.equals("."))
break;
output = output + input + ".";
} ;
System.out.println(output);
}
I use a little trick using a simple check to see if its not the first read.
boolean isFirst=true;
do{
System.out.println("Please Enter a Character");
input = s.nextLine();
if(!isFirst) output="."+output;
isFirst=false;
output = output+input;
}while(!input.equals("."));
Instead of the do... while, you should use the the while function.
while (!input.equals(".") {
}
You have to use substring function in java and remove the last character of the String.
your loop end while you enter a dot in input.
Example given below.
Try this
import java.util.Scanner;
public class dots1 {
Scanner s = new Scanner(System.in);
String input;
String output = "";
System.out.println("Hello! I print out an acronym. ");
do{
System.out.println("Please Enter a Character");
input = s.nextLine();
output = output+input+".";
}while(!input.contains("."));
System.out.println(output.substring(0, output.length() - 2));
}
}
Output of Single Input
output of Multiple Inputs
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]);
}
}
I get an extra comma on the end of my string after the user inputs their text. How do I get rid of the last comma? The good old fence post problem, but I'm stuck on the fence.
import java.util.Scanner;
public class fencepost {
public static void main(String[] args) {
System.out.print("Enter a line of text: ");
Scanner console = new Scanner(System.in);
String input = console.nextLine();
System.out.print("You entered the words: ");
Scanner linescanner = new Scanner(input);
while (linescanner.hasNext()) {
System.out.print(linescanner.next());
System.out.print(", ");
}
}
}
I get as output "hello, there," with an extra comma after there.
Add an if statement inside your loop to determine if there's still a next line, if so, then add a comma, otherwise, don't add one:
while (linescanner.hasNext()) {
System.out.print(linescanner.next());
if (linescanner.hasNext()) {
System.out.print(", ");
}
}