Scanner Issue with Java String Parsing - java

Feel like I'm missing something really basic here, but my brain is fried right now. Goal is to parse strings with a comma, gets through one loop and throws before the next line. Pretty sure it has something to do with userInput = scan.nextLine();
import java.util.Scanner;
public class ParseStrings
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String userInput = "";
boolean finished = false;
while (!finished)
{
System.out.print("Enter input string: \n");
userInput = scan.nextLine();
if (userInput.equals("q"))
{
System.out.println("First word: " + userInput);
finished = true;
} else
{
String[] userArray = userInput.split(",");
System.out.println("First word: " + userArray[0]);
System.out.println("Second word: " + userArray[1]);
System.out.println();
}
}
return;
}
}
Throwing:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at ParseStrings.main(ParseStrings.java:12)
Thank you in advance

Related

How do I categorize a list of user inputs into different orders?

I am supposed to make a program that asks users for a list of input. Then, from that list, my program is supposed to pick out the third answer and then print it out. It sounds really simple, but how do I assign numbers to each of the user inputs? Do I even do that? I am a beginner, and thank you so much for your help!
This is the code I have so far:
import java.util.*;
public class MyProgram
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
while(true) {
System.out.println("What do you appreciate in your life or school?");
String ans = scan.nextLine();
if(ans.equals(""))
{
break;
}
}
System.out.println("You said \"" + input3 + "\" as your third answer.");
}
}
You can strore the third input in a variable you initialized bevor the loop.
if there is no third input it prints: ""
import java.util.*;
public class MyProgram
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int index = 0;
String input3 = "";
while(true) {
System.out.println("What do you appreciate in your life or school?");
String ans = scan.nextLine();
if (index == 2) {
input3 = ans;
}
if(ans.equals("")){
break;
}
index++;
}
System.out.println("You said \"" + input3 + "\" as your third answer.");
}
}

Why System.out.println "Input" comes out twice?

i'm new to programming and we've got an example from school to understand how Scanner works. My problem is that i do not understand why the message "Input" (System.out.println in the while loop) gets printed twice.
import java.util.Scanner;
class ScannerInput {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println("Give me a String:");
String zeichenkette = myScanner.nextLine();
System.out.println("Give me an Integer:");
int einInteger = myScanner.nextInt();
// Output input by user
System.out.println("String: " + zeichenkette);
System.out.println("Integer: " + einInteger);
boolean scannerSuccess = false;
while(!scannerSuccess) {
System.out.print("Input: ");
if(myScanner.hasNextInt()) {
einInteger=myScanner.nextInt();
myScanner.nextLine();
scannerSuccess=true;
} else if(myScanner.hasNextLine()){
myScanner.nextLine();
scannerSuccess=false;
}
}
myScanner.close();
}
}
else if(myScanner.hasNextLine()){
myScanner.next();
scannerSuccess=false;
}
try this code

Java parsing strings Error: Exception in thread "main" java.util.NoSuchElementException

Why do I get an exception error when trying to run this program? What does it mean and how can I fix it? Is it because I am using nextline? I get no error when running this in IntelliJ but when I run it in Zybooks (online coding lessons with assignments) I get the error.
My error:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at ParseStrings.main(ParseStrings.java:40)
Code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
System.out.println("Enter input string:");
userInput = scnr.nextLine();
while (!userInput.equals("q")) {
while (userInput.contains(",") == false) {
System.out.println("Error: No comma in string");
System.out.println("Enter input string:");
userInput = scnr.nextLine();
}
String[] myArray = userInput.split(",");
System.out.println("First word: " + myArray[0]);
System.out.println("Second word: " + myArray[1]);
//get the next input
System.out.println("Enter input string:");
userInput = scnr.nextLine();
}
}
}
The issue is when you assign a value to userInput variable so you aren't be able to call it again in loop while so you need call it from scanner, let me add this example:
while (!(userInput = scnr.nextLine()).equals("q")) {
....
}

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 Program - "Erroneous tree type" Issue

I have been going thorough some practice problems and have a question on this code. I was able to figure it out using a different method, but I don't understand why this example doesn't work.The code asks for input until the user enters the same input twice, where it should then display the duplicate input before ending the program.
I am getting:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree type: any>
Error on the last line with the word variable. Any ideas?
import java.util.ArrayList;
import java.util.Scanner;
public class MoreThanOnce {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
// create here the ArrayList
ArrayList<String> words = new ArrayList<String>();
while (true){
System.out.print("Type a word: ");
String word = reader.nextLine();
if(!words.contains(word)){
words.add(word);
}else{
break;
}
}
System.out.println("You gave the word " + word + " twice");
}
}
Your code does not compile. The variable "word" you want to display at the end is not in the right scope : you declare it in the while loop but try to use it outside this loop.
Just change thing like this :
import java.util.ArrayList;
import java.util.Scanner;
public class MoreThanOnce {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
// create here the ArrayList
String word; //variable declared before loop
ArrayList<String> words = new ArrayList<String>();
while (true){
System.out.print("Type a word: ");
word = reader.nextLine();
if(!words.contains(word)){
words.add(word);
}else{
break;
}
}
System.out.println("You gave the word " + word + " twice");
}
Hope it helps.
Mathias
Are you using NetBeans ?
If yes then there is an open bug
Declare "String word" variable before while loop.
import java.util.ArrayList;
import java.util.Scanner;
public class MoreThanOnce {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
// create here the ArrayList
String word;
ArrayList<String> words = new ArrayList<String>();
while (true) {
System.out.print("Type a word: ");
word = reader.nextLine();
if (!words.contains(word)) {
words.add(word);
} else {
break;
}
}
System.out.println("You gave the word " + word + " twice");
}
}

Categories

Resources