The program is supposed to translate a word from American to British version. It only works for the first word but it doesn't work for the other words because it gives the else statement instead.
My code:
import java.util.Scanner;
public class BritishTranslator {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
String word;
String [] america = new String[8];
String [] british = new String[8];
america[0] = "attic";
america[1] = "business suit";
america[2] = "elevator";
america[3] = "frenc fries";
america[4] = "ice cream";
america[5] = "sneakers";
america[6] = "truck";
america[7] = "zero";
british[0] = "loft";
british[1] = "lounge suit";
british[2] = "lift";
british[3] = "chips";
british[4] = "ice";
british[5] = "plimsolls";
british[6] = "lorry";
british[7] = "nough";
System.out.println("Please enter an American word: ");
word = input.nextLine();
for (int i = 0; i < america.length; i++)
{
for(int j = 0; j < british.length; j++)
{
if (word.equals(america[i]))
{
System.out.println(america[i] + " in british is: " + british[j]);
System.exit(0);
}
else
{
System.out.println("Word not found in the dictionary.");
System.exit(0);
}
}
}
}
}
I need help learning how to debug this code.
you just need to iterate over the america array, if you find the word look at the same index in the british array.
and the else out of the loop
for (int i = 0; i < america.length; i++){
if (word.equals(america[i])) {
System.out.println(america[i] + " in british is: " + british[i]);
System.exit(0);
}
}
System.out.println("Word not found in the dictionary.");
System.exit(0); // you dont need this as well
}
Since the 2 arrays contain the word-translation in the same index, you don't have to iterate through the 2nd table. Just find the index of word in the 1st table and use this index to get the translation in the 2nd table. Also use a boolean flag found to check after the loop if the word is not found:
System.out.println("Please enter an American word: ");
word = input.nextLine();
boolean found = false;
for (int i = 0; i < america.length; i++) {
found = word.equals(america[i]);
if (found) {
System.out.println(america[i] + " in british is: " + british[i]);
break;
}
}
if (!found)
System.out.println("Word not found in the dictionary.");
With the use of break the loop stops as soon as the word is found.
Since you are pairing your american words to your french words, you only need to loop the arrays once and if the word equals your american word then you want to print the string at the same index in both your french array and american array.
for (int i = 0; i < america.length && i < british.length; i++)
{
if (word.equals(america[i]))
{
System.out.println(america[i] + " in british is: " + british[i]);
System.exit(0);
}
}
System.out.println("Word not found in the dictionary.");
I believe you have a couple things going on here.
First, I think you don't want to do your else statement until after you have gone through the loop. As it is currently written, it will terminate as soon as your first 'if' statement fails due to the nature of your if/else and the System.exit(0) call.
System.out.println("Please enter an American word: ");
word = input.nextLine();
for (int i = 0; i < america.length; i++)
{
for(int j = 0; j < british.length; j++)
{
if (word.equals(america[i]))
{
System.out.println(america[i] + " in british is: " + british[j]);
System.exit(0);
}
}
}
System.out.println("Word not found in the dictionary.");
System.exit(0);
However, you don't actually need the second loop, since you have the index that you've found when you are iterating through your first loop, so you can further simplify your answer to.
System.out.println("Please enter an American word: ");
word = input.nextLine();
for (int i = 0; i < america.length; i++)
{
if (word.equals(america[i]))
{
System.out.println(america[i] + " in british is: " + british[i]);
System.exit(0);
}
}
System.out.println("Word not found in the dictionary.");
System.exit(0);
Since the values are mapped via index, you're able to directly access the thing you wish to translate without having a second loop, making your program faster and less complex!
Related
This question already has answers here:
Avoid printing the last comma
(13 answers)
Closed 1 year ago.
I'm writing a simple java code that takes two integers as min and max and a third integer as divisor and it finds all numbers between that are divisible by the third integer, which worked fine but in the output I can't get rid of the last comma.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
int a = scanner.nextInt();
System.out.print("Enter the second number: ");
int b = scanner.nextInt();
System.out.print("Enter the divisor: ");
int d = scanner.nextInt();
for(int i=a; i<=b; i++) {
if(i%d == 0)
System.out.print(i+", ");
}
How could I do it?
I prefer to avoid the issue by writing commas before things where appropriate, and not after. It seems more straightforward to know when you're doing the first thing, compared to knowing when you're doing the last thing.
String sep = ""; // no separator before first print
for (int i=a; i<=b; i++) {
if (i%d == 0) {
System.out.print(sep + i);
sep = ", "; // separator for every following print
}
}
You can use an if statement to print a comma only if it is not the last element.
if(i%d == 0){
System.out.print(i);
if(((i/d)+1)*d <= b) System.out.print(", ");
}
For these kinds of problems the StringJoiner is especially useful:
StringJoiner out = new StringJoiner(",");
for(int i=a; i<=b; i++) {
if(i%d == 0)
out.add(Integer.toString(i));
}
System.out.println(out);
You can use as boolean to control printing the comma.
boolean addComma = false;
for (int i=a; i<=b; i++) {
if (i%d == 0) {
System.out.print((v ? "," : "") + i);
addComma = true;
}
}
You could use substringto strip the space and comma off the end if it is the last number. It is not as elegant as Unmitigated's solution, but it should work:
String validNumbers = "";
for(int i=a; i<=b; i++) {
if(i%d == 0)
validNumbers += i + ", ";
}
if (validNumbers != "") {
validNumbers = validNumbers.substring(0, validNumbers.length() - 2);
}
System.out.print(validNumbers);
I have an assignment, it looks pretty easy however I cannot figure it out how to solve it.
It says:
a) Ask the user: How many words/sentences do you want to write (at
least 5) ? (Use while loop)
b) Use for loop to make the user write the words/sentences
c) After the user's written the words/sentences, output which
word/sentence comes last alphabetically (using .compareTo() method )
This is what I came up with:
import java.util.Scanner;
import java.lang.String;
import java.util.Arrays;
public class LastString {
public static void main (String [] args){
Scanner input = new Scanner (System.in);
final short MIN_NUM = 2;
int num = 0;
int count = 0;
String [] sentence = new String [0];
String last = "";
while (num < MIN_NUM){
System.out.println("How many words/sentences do you want to put? " + "\t\t\t\t\t\t\t\t --- at least " + MIN_NUM);
num = input.nextInt();
sentence = new String [num];
}
for (int i = 0; i < num ; i++ ) {
System.out.println("\nWrite a word/sentence" + "\t\t\t\t\t\t\t\t\t --- (Time: " + (i+1) + " )");
sentence [i] = input.nextLine();
System.out.println("The word/sentence is: " + sentence[i]);
}
int i = 0;
int max;
for (i=0;i<num-1 ;i++ ) {
if(sentence[i].compareTo(sentence[i+1]) > 0){
last = sentence[i];
count ++;
}else if (sentence[i].compareTo(sentence[i+1]) < 0) {
last = sentence[i+1];
count++;
}
}
System.out.println("\n\n------------" +
"\nLast word/sentence is: " + last);
System.out.println(Arrays.toString(sentence));
}
}
I compiles and runs. I have two problems:
nextLine >>> it is skiping the first Sentence
I don't know how to make the algorithm to calculate which word/sentence has the biggest value or, using the compareTo() method which word/sentence has the value > 0 compared to each and every other value on the array.
Thank you.
Answer to Q1 : num = input.nextInt(); takes a number as the input but doesn't also consume the new-line, and hence the nextLine consumes the empty new line ... you could use input.nextLine also to get the first number instead of num = input.nextInt(); by reading a line, then parsing the int value as num = Integer.parseInt(input.nextLine());
Answer to Q2 :
You re-set the value of last everytime but you don't compare the value of the next biggest candidate with the last before re-assigning last ...
for example, look at the following :
for (int i = 0; i < num - 1; i++) {
String thisLast = "";
if (sentence[i].compareTo(sentence[i + 1]) > 0) {
thisLast = sentence[i];
count++;
} else if (sentence[i].compareTo(sentence[i + 1]) < 0) {
thisLast = sentence[i + 1];
count++;
}
if (thisLast.compareTo(last) > 0)
last = thisLast;
}
it will solve your problem....
int count = 0;
String [] sentence = new String[6];
String last = "";
for (int i = 0; i < num ; i++ ) {
System.out.println("\nWrite a word/sentence" + "\t\t\t\t\t\t\t\t\t --- (Time: " + (i+1) + " )");
sentence [i] = input.nextLine();
count++;
if(count >= 2){
if(sentence[i].compareTo(last) > 0){
last = sentence [i] ;
}
}else{
last = sentence [i];
}
System.out.println("The word/sentence is: " + sentence[i]);
}
I need to build a simple automaton for my Automata class. I am using Java and I cannot figure out for the life of me why my program keeps exiting prematurely. I've tried debugging it, having print statements everywhere to figure out where it's stopping, and although I know where it stops, I do not see anything that would make the program stop working. The stoppage happens on line 27 (Right where I SOP "Enter a string of digits...".
Knowing me it's probably something simple, but I cannot figure this one out.
import java.util.*;
public class hw1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please indicate the number of states");
int numState = input.nextInt();
int[] state = new int[numState];
boolean[] accept = new boolean[numState];
for (int i = 0; i < numState; i++) {
System.out.println("Is the state q" + (i + 1) + " a final state? (Answer 1 for yes; 0 for no)");
int finalState = input.nextInt();
if (finalState == 1)
accept[i] = true;
} // for
System.out.println("Enter the number of symbols s: ");
int numSym = input.nextInt();
int[][] next = new int[numState][numSym];
for (int i = 0; i < numState; i++) {
for (int j = 0; j < numSym; j++) {
System.out.println("What is the number for the next state for q" + i + " when it gets symbol " + j);
next[i][j] = input.nextInt();
}//nested for
}//for
String digits = input.nextLine();
System.out.print("Enter a string of digits (0-9) without spaces to test:");
int[] digitArray = new int[digits.length()];
for (int i = 0; i < digits.length(); i++) {
digitArray[i] = digits.charAt(i);
}
for (int i = 0; i < digits.length(); i++) {
System.out.print(digitArray[i] + " ,");
}
System.out.println("end of program");
}// main;
}// class
Change your code to :
input.nextLine();
System.out.print("Enter a string of digits (0-9) without spaces to test:");
String digits = input.nextLine();
This will get and ignore the newline character left in the stream after call to nextInt()
I have wrote this code and now i'm practicing and i'm trying it to write it in a different or more efficient way. Basically this code asks the user to enter a word and the second player guesses the letters of the word with 6 tries and at the end there is one last chance to guess the whole entire word. Any suggestions on how i can write this code in a simple way?
static int NUM_OF_TRIES = 6;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Player 1 please enter the word");
String word = keyboard.next();
for (int i = 0; i < NUM_OF_TRIES; i++) {
System.out.println("Enter your guess please");
String guess = keyboard.next();
boolean a = true;
for (int j = 0; j < word.length(); j++) {
if (guess.charAt(0) == word.charAt(j)) {
System.out.println(" at position " + (j + 1));
a = false;
break;
}
}
if (a) {
System.out.println("Sorry not letter " + guess.charAt(0));
continue;
}
}
System.out.println("Enter your last guess: ");
String wordComp;
wordComp = keyboard.next();
if (wordComp.equals(word)) {
System.out.println("You got it!");
} else {
System.out.println("Sorry you lost!");
}
}
}
Well, here is a shorter version:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Player 1 please enter the word");
String word = keyboard.next();
for (int i = 0; i < NUM_OF_TRIES; i++) {
System.out.println("Enter your guess please");
String guess = keyboard.next();
int index = word.indexOf(guess.charAt(0));
if (index == -1)
System.out.println("Sorry not letter " + guess.charAt(0));
else
System.out.println(" at position " + (index + 1));
}
System.out.println("Enter your last guess: ");
String wordComp = keyboard.next();
if (wordComp.equals(word))
System.out.println("You got it!");
else
System.out.println("Sorry you lost!");
}
---First of all you'll have to ensure that
word.length <=guess.length
or you'll run into an exception.--- edit: that was obv not correct
Can't test right now bc I'm on my mobile, but as far as I can see, you'll run into problems if the word to guess has the same letter multiple times, since you're breaking out of the loop after finding the equal first letter.
As mentioned in comments, the comparison could be done by a method like
private static List<Integer> getLetterIndices(String word, char letter);
Then you won't need your boolean to indicate correct guesses, but a list of indices found
And of course you can do an object oriented approach instead of the static main method (not that it's faster to implement or better performance, just for practicing), perhaps something in the lines of this:
public class WordToGuess{
private Map<Character,List<Integer>> letter2indices;//...
public WordToGuess(String word){
parseIndices(word);
}
//parse indices of each letter to the map
private void parseIndices(String word);
public List<Integer> getLetterIndices(char letter);
}
I am a beginner in java. There is an error which appears 15 times in lines 24, 27, 29, 30, 35, 36, 37, 42, 43 and 46, saying:
//Tokens cannot be resolved to a variable
And:
// i cannot be resolved to a variable
What variables do these errors want to identify? Because I thought I identified everything and I don't understand what variables my code still needs.
Here is my code:
import java.util.Scanner;
public class Jo_code {
public static int wordFrequency(String s) {
String tokens[] = s.split(" ");// splits the words
int count = tokens.length;
return count;
}
public static void main(String args[]) {
System.out.println("Write your sentence or type END to quit the program:");// prints out the first instruction.
Scanner scan = new Scanner(System.in); //object initialisation.
String line = " ";//declaration for letters(String) characters.
int max = 20; //declaration for number(int) characters.
while ((line = scan.nextLine()) != null) { //scanner instruction, get a line from the key board.
if (line.equals("END")) {
break;// if you are happy with the code, then type "END", and the code will stop running.
} else { // if you decide not to type "END" the program will continue to allow you to type sentences.
String[] array = line.split(" ");// splits the words
System.out.println("your sentence is " + line);//prints out what you have typed.
System.out.println("The total of words for the line is " + tokens.length);// prints out the total of words that you have typed.
int maxTokensLength = 0;
int tokensLength = 0;
for (int i = 0; i < tokens.length; i++) {// this line of code checks for what must be true to carry on.
array[i] = array[i].replaceAll("a-zA-Z]", "");
}
tokensLength = array[i].length();
tokensLength = tokens[i].length();
if (tokensLength > maxTokensLength) {
maxTokensLength = tokensLength;
}
}
}
int[] intArray = new int[maxTokensLength + 1];
for (int i = 0; i < tokens.length; i++) { // this line of code checks for what must be true to carry on.
intArray[array[i].length()]++;
}
for (int i = 1; i < intArray.length; i++) { // this line of code checks for what must be true to carry on.
System.out.printf("%word(s) of length %d<br>", intArray[i], i);
}
for (int i = 0; i < tokens.length; i++) { // this line of code checks for what must be true to carry on.
System.out.println("word " + i + ": " + tokens[i] + " = " + tokens[i].length() + " characters");
}
System.out.println("The length for the word " + tokens[i] + " is = " + tokens[i].length());//This line of code prints out the word frequency for each word.
System.out.println("The word frequency of the whole sentence is =");//results
System.out.println("type END to quit");//instructions
}
}
Thank you very much for any help, its much appreciated!
For one thing, your very first for loop has no open and close brackets. This means only the first statement is considered part of the for loop. so the statement 'tokensLength = array[i].length();' can't reach the variable i because it is not in the for loop. I believe adding open and close brackets around everything you want in the first for loop should fix it