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");
}
}
Related
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.");
}
}
I am trying to make this program that prints out the words that start with a certain letter from a list words. For example if you enter the letter "e" it should only print words that start with the letter "e" but for some reason it is reading words like "far east" even though it does not start with the letter "e". Any suggestions?
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class words {
public static void main(String[] args) throws IOException {
Scanner key = new Scanner(System.in);
File wordfile = new File("wrds.txt");
if(wordfile.exists()){
Scanner keyboard = new Scanner(wordfile);
int counter = 0;
System.out.println("Enter a character");
char wrd = key.next().charAt(0);
while(keyboard.hasNext()) {
String word = keyboard.next();
if(word.startsWith(""+ wrd)) {
counter++;
}
}
System.out.println("Found "+counter+" words that begin with "+ wrd);
}
}
}
By default, scanner breaks words with whitespaces. So 'far east' is scanned as 'far' and 'east'. Use delimiter instead to ignore whitespaces. Refer the code below.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Words {
public static void main(String[] args) throws IOException {
Scanner key = new Scanner(System.in);
File wordfile = new File("wrds.txt");
if(wordfile.exists()){
Scanner keyboard = new Scanner(wordfile);
int counter = 0;
System.out.println("Enter a charycter");
char wrd = key.next().charAt(0);
keyboard.useDelimiter(System.getProperty("line.separator"));
while(keyboard.hasNext()) {
String word = keyboard.next();
if(word.startsWith(""+ wrd)) {
counter++;
}
}
System.out.println("Found "+counter+" words that begin with "+ wrd);
}
}
}
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];
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
I've been trying to add elements to a TreeSet using a loop that accepts user input. The problem I'm running into is that the loop I created is only filling the TreeSet with the first element that the user inputs. I was using all string variables in this example and I was also attempting to use the word 'end' as a sentinel value to terminate the loop and then print out the elements that had been added to the TreeSet. My only problem is not being able to fill the TreeSet with more than the first user input element. This is the code I used:
import java.util.*;
import java.util.Scanner;
public class TestRun {
public static void main(String[] args) {
java.util.TreeSet wordList = new java.util.TreeSet();
Scanner input = new Scanner(System.in);
String word;
System.out.print("Enter a word: ");
wordList.add(input.next());
while(!(word = input.nextLine()).equals("end")){
System.out.print("Enter a word: ");
}
java.util.Iterator iterator = wordList.iterator();
while(iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
}
}
You're missing a call to wordList.add in your loop:
while(!(word = input.nextLine()).equals("end")){
wordList.add(word); // The call you were missing
System.out.print("Enter a word: ");
}
import java.util.Scanner;
import java.util.TreeSet;
public class largestandSmallestelementinanArray {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
int size=0;
System.out.println("enter the size of an array");
size = sc.nextInt();
TreeSet tr = new TreeSet();
while(size>0)
{
tr.add(sc.nextInt());
size--;
}
System.out.println(tr);
}
}