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);
}
}
}
Related
Write a Java program that takes all the lines input to standard input and writes them to standard output in reverse order. That is, each line is output in the correct order, but the ordering of the lines is reversed.
I wrote this:
public static void main(String[] args) {
Scanner sc=new Scanner (System.in);
System.out.println("Enter the line");
String a=sc.nextLine();
System.out.println("Enter the line");
String b=sc.nextLine();
System.out.println(b+" "+a);
}
Is this efficient?
As suggested by one of the comments a Deque would be a good data structure to achieve this:
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Deque deque = new LinkedList<>();
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your lines (Enter exit to continue):");
while(sc.hasNext()) {
String line = sc.next();
if(line.toLowerCase().equals("exit")) {
break;
}
deque.add(line);
}
System.out.println("\n=====Reversed Lines=====\n");
Iterator reverse = deque.descendingIterator();
while (reverse.hasNext()) {
System.out.println(reverse.next());
}
}
}
Try it here!
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");
}
}
Hi I'm trying to write a program that will check a designated file for a number that a user has input, however if the number is not present in the file I want the program to loop back to the beginning, how could I do this?
Here is the mess I've made so far:
import java.util.Scanner;
public class Classtest2 {
public static void main(String[] args) {
// //1. class
Scanner sc = new Scanner(Classtest2.class.getResourceAsStream("trombones.txt"));
Scanner myScanner = new Scanner(System.in);
System.out.println("What number would you like to check for?");
String number = myScanner.nextLine() ;
String keyWord = number, word;
int lineNum = 0;
while(sc.hasNextLine()) {
word = sc.next();
if(word.equals(myScanner.nextLine().trim())) {
System.out.println("The number "+number+ " is there");
break;
} else {
// not found
}
} // main
} // class
all you need to do is take input from user and then check is it exist in file .you shouldn't use myScanner.nextLine().trim() inside while loop because then it waits to get user input every loop time .ones you get a number from user ,you should check it in the file .what you did is get user input and then again wait for user to input value again and again
fixed code
import java.util.Scanner;
public class Classtest2 {
public static void main(String[] args) {
// //1. class
Scanner sc = new Scanner(Classtest2.class.getResourceAsStream("trombones.txt"));
Scanner myScanner = new Scanner(System.in);
System.out.println("What number would you like to check for?");
String number = myScanner.nextLine() ;
int lineNum = 0;
while(sc.hasNextLine()) {
word = sc.next();
if(word.equals(number.trim())) { //here was the problem
System.out.println("The number "+number+ " is there");
return;
} else {
}
}
System.out.println("not found"); // not found
}
the best approach
import java.util.Scanner;
public class Classtest2 {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println("What number would you like to check for?");
String number = myScanner.nextLine();
if(isFound(number)){
System.out.println("The number "+number+ " is there");
}else{
System.out.println("The number "+number+ " doesn't exist");
}
}
public static boolean isFound(String number) {
Scanner sc = new Scanner(Classtest2.class.getResourceAsStream("trombones.txt"));
String word="";
while (sc.hasNextLine()) {
word = sc.next();
if (word.equals(number.trim())) {
return true;
}
}
return false;
}
}
This works for me, hope is useful for you:
package test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class Classtest2 {
public static void main(String[] args) throws IOException {
File f = new File("trombones.txt");
f.createNewFile();
Scanner myScanner = new Scanner(System.in);
boolean numExiste = menu(new Scanner(f), myScanner);
while (!(numExiste)){
numExiste = menu(new Scanner(f), myScanner);
}
myScanner.close();
}
private static boolean menu(Scanner fileScanner, Scanner myScanner) throws FileNotFoundException{
String word = "";
System.out.println("What number would you like to check for?");
String number = myScanner.nextLine().trim();
while(fileScanner.hasNextLine()){
word = fileScanner.nextLine();
if(word.trim().equals(number)){
System.out.println("The number "+number+ " is there");
return true;
}else{
//Not the number
}
}
System.out.println("The number "+ number+ " is not in the file\n\n");
return false;
}
} // main } // class
An email address contains the # character. Write a program that takes a word from the keyboard and outputs whether it is an email address based on the presence of the # character. Do not worry about what else is in the word.
import java.util.Scanner;
public class EmailAddress {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(" Enter a word: " );
String word = input.nextLine();
int count = 0;
for(int i = 0; i < word.length(); i++) {
if(word.charAt(i) == '#')
count++;
}
if(count > 0)
System.out.println("Its an E-mail ");
else
System.out.println("Its not an E-mail ");
}
}
import java.util.Scanner; //Imports the scanner function
public class TestingCode { //standard java input
public static void main(String args[]) { //standard java input
Scanner scan = new Scanner (System.in) ; //asks the user to input the email they would like to find the domain for
System.out.print ( "What is the email? : " );
String email = scan.next(); //scans for the next string
int index = email.indexOf('#') ; //finds the index at which the # is located at and stores it as index
String domain = email.substring (index , email.length() ); //uses the substring function to cut out everything before the # symbol and stores that snippet as variable domain .
System.out.print("The email domain is " + domain ); //displays variable domain
}
}
I don't know why y'all making this code so complicated?!
import java.util.Scanner;
import java.util.*; //I Always import this as a good habit
public class EmailAddress
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print(" Enter a word: " );
String word = input.nextLine();
if(word.contains('#'))
{
System.out.println("It's an Email");
}
else
{
System.out.println("It's not an Email");
}
}
}
import java.util.Scanner;
public class SeperateLetters
{
public static void main(String[] args)
{
Scanner scan= new Scanner(System.in);
System.out.println("Enter a word:");
String w= scan.nextLine();
for(int i=0; i<w.length();i++)
System.out.println(w.charAt(i));
}
}
This is what I have so far and I can't figure how to make it so that if the word is 5 letters or longer to print it one letter per line and if not to just print the word. So far it'll just print any word with one letter per line.
You are very close. The only thing missing is an if-else conditional statement, to check whether the word has a length of five. Without this check, you will always print the string one character per line, regardless of its length.
import java.util.Scanner;
public class SeperateLetters {
public static void main(String[] args) {
Scanner scan= new Scanner(System.in);
System.out.println("Enter a word:");
String w = scan.nextLine();
if (w.length() >= 5) { // print one char per line if length is 5
for (int i = 0; i < w.length(); i++)
System.out.println(w.charAt(i));
} else {
System.out.println(w); // otherwise, print the whole string
}
}
}
Use an if-else statment to check if w.length() == 5 or not.
public class SeperateLetters
{
public static void main(String[] args)
{
Scanner scan= new Scanner(System.in);
System.out.println("Enter a word:");
String w= scan.nextLine();
if( w.length() > 5)
{
for(int i=0; i<w.length();i++)
{
System.out.println(w.charAt(i));
}
}
}
}