Pig latin Java program with try-catch, translation passed though function - java

I am making a java program that translates a sentence to pig latin. I need to have at least one try-catch in this program and the translation must be done in a function. The original word will be passed to this function and return the translated word back to the function call per my professor's wishes. I am also having trouble asking the user if they want to translate something else. even when I say no it still restarts the program.
this is what I have:
package midtermPigLatin;
import java.util.Scanner;
import textio.TextIO;
public class midtermPigLatin {
public static void main(String[] args)
{
Scanner input = new Scanner( System.in );
String yourSentence="";
boolean again = true;
try {
do {
String[] words;
System.out.print("Enter your words here: ");
yourSentence = input.nextLine();
words = yourSentence.split(" ");
for (String word : words)
{
if (word.startsWith("a") || word.startsWith("e") || word.startsWith("i") || word.startsWith("o") || word.startsWith("u"))
System.out.print(word + "way ");
else if (word.startsWith("sh") || word.startsWith("ch") || word.startsWith("th"))
System.out.print(word.substring(2)+word.substring(0,2)+"ay ");
else
System.out.print(word.substring(1)+word.substring(0,1)+"ay ");
}
System.out.println();
System.out.println("Do you want to play again, Yes or no");
again = TextIO.getBoolean();
} while(!yourSentence.equals("quit"));
}catch(Exception errMsg)
{
System.out.print(" error" + errMsg);
}
}
}
I just need help modifying my program to pass the translation through a function original word will be passed to this function and return the translated word back to the function call and the ending the program if user says no.
Here is what I get when I run the program:
Enter your words here: apple door shave
appleway oorday aveshay
Do you want to play again, Yes or no
no
Enter your words here:

Related

How do I go back to the menu after taking several questions?

I am currently creating a program where the user enters a specific set of questions. And the program must go back to the menu after completely answering all questions. How should I do it?
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("""
\n \nAre you ready to take the quiz?
Enter "Y" to proceed or "N" to exit the program:""");
String TakeQuiz = input.nextLine();
if (TakeQuiz.equalsIgnoreCase("Y"))
do {
//blocks of code
}
}
}
System.out.println("Do you want to take the quiz again?");
String RetakeQuiz = input.nextLine();
while (RetakeQuiz.equalsIgnoreCase("Y")) ;
else {
System.out.println("We hope to see you again soon!");
System.exit(0);
}
}
}
There are many ways to achieve what you want, I would not clutter the main method and break the code to another function and loop there.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
for(;;)
takeQuiz();
}
public static void takeQuiz(){
Scanner input = new Scanner(System.in);
System.out.print("\n \nAre you ready to take the quiz?" +
"Enter \"Y\" to proceed or \"N\" to exit the program:");
String takeQuiz = input.nextLine();
if (takeQuiz.equalsIgnoreCase("Y")) {
System.out.println("Running code...");
System.out.println("Question 1");
System.out.println("Question 2");
System.out.println("Question 3");
}
// retake
if (takeQuiz.equalsIgnoreCase("R")){
takeQuiz();
}
if (takeQuiz.equalsIgnoreCase("N")){
System.out.println("We hope to see you again soon!");
System.exit(0);
}
}
}
Notice the escape character for quotes \" and the + for multiline Strings
Java 15 and beyond allows triple quotes as Java Text Blocks
so your String message should be valid
The basic structure is something like this:
boolean continueWithQuiz = true;
while (continueWithQuiz) {
// Put the code here for handling the quiz
...
// Should we keep going?
System.out.println("Do you want to take the quiz again?");
String retakeQuiz = input.nextLine();
continueWithQuiz = retakeQuiz == "Y";
}
One more comment. Please follow Java naming standards. Class names begin with an upper case letter. Constants should be ALL_CAPS. Everything else is in lower case.

Java Pig Latin Converter is spitting out an extra word

I'm working on a project for my Programming Applications course with WGU. I've decided to adapt a python-based pig latin converter from the previous course. I've almost got it done, but when I run the program, I get an extra word. For example, if I enter Latin, it prints atinLay, then on the next line, prints inLatay.
I'm not sure which part of the code is causing this. I know it should be a simple fix but I just can't find it. Here is my code:
import java.util.Scanner;
public class PigConverter
{
public static void main(String[] args)
{
Scanner anscay = new Scanner(System.in);
System.out.print("Enter a word:");
String word = anscay.nextLine();
System.out.println("This word, in pig latin, would be:");
String pigConvert;
for (int i=0; i < word.length(); i++)
{
if(word.charAt(i)=='a' || word.charAt(i)=='e' || word.charAt(i)=='i' ||
word.charAt(i)=='o' || word.charAt(i)=='u')
{
String second = word.substring(0,i);
String first = word.substring(i,word.length());
System.out.println(first+second+"ay");
}
}
}
}
I think that your loop is finding BOTH vowels in the word, so it/s doing the output twice. I think that your loop should break once you find the first vowel.

Checking Multiple strings with if, else if statement

I am creating a simple lift programme in java. I want to to have four users that are allowed to use the lift i have already got it working for 1 but i cant figure out how to check multiple strings using the one if statement.
import java.util.Scanner;
public class Username
{
public static void main (String[]args)
{
Scanner kb = new Scanner (System.in);
String name;
System.out.println("Enter your name");
name = kb.nextLine();
if (name.equals("barry "))
System.out.println("you are verified you may use the lift");
Scanner f = new Scanner(System.in);
int floor;
System.out.println("What floor do you want to go to ");
floor = f.nextInt();
if (floor >7)
System.out.println("Invalid entry");
else if (floor <= 7)
System.out.println("Entry valid");
}
}
Check out this related question:
Test if a string contains any of the strings from an array
Basically, put the names into an Array of strings, and compare the name entered with each name in the Array.
Use the OR symbol "||" or "|".
Such as if (name.equals("barry ") || name.equals("sara"))
For future reference the difference between the two is "||" short circuits. In this situtation, if barry is the name then the second statement for checking against sara will never be executed.
basically, you need an "Or" gate, this would work:
if(name.equals("name1")||name.equals("name2")||name.equals("name3"))
etc...

Java Continuous Input Code

Okay, so the program that I'm trying to figure out how to code (not really fix), I have to use Java to accept continuous input from the user until they enter a period. It then must calculate the total characters that the user input up to the period.
import java.io.*;
class ContinuousInput
{
public static void main(String[] args) throws IOException
{
InputStreamReader inStream = new InputStreamReader (System.in);
BufferedReader userInput = new BufferedReader (inStream);
String inputValues;
int numberValue;
System.out.println("Welcome to the input calculator!");
System.out.println("Please input anything you wish: ");
inputValues = userInput.readLine();
while (inputValues != null && inputValues.indexOf('.')) {
inputValues = userInput.readLine();
}
numberValue = inputValues.length();
System.out.println("The total number of characters is " + numberValue + ".");
System.out.println("Thank you for using the input calculator!");
}
}
Please don't suggest the use of Scanner, the Java SE Platform we're stuck using is the SDK 1.4.2_19 model and we can't update it.
Explanation of empty braces: I thought that if I put in the empty braces that it would allow for continuous input until the period was put in, but clearly that wasn't the case...
Edit: Updated code
Current Error: won't end when . is inputted.
You have to switch the if/else statement with while.
Sample :
inputValues = userInput.readLine();
while (!".".equals(inputValues) {
//do your stuff
//..and after done, read the next line of the user input.
inputValues = userInput.readLine();
}
Note: Never compare the values of String objects with the == operator. Use the equals() method.
If you just want to test, whether the sentence the user inputs contains a . symbols, you just have to switch from equals() to contains(). It's a built-in method from the java.lang.String class.
Sample:
while (inputValues != null && !inputValues.contains(".")) {
//do your stuff
}

How do I set the statement if to read letters instead of numbers?

"if" statement only allows to put numbers in it.
Is there a way to make it read letters?
I'm only in my fifth lesson of Java (I study in a uni and the teacher is very slow but I want to learn things fast)
for example.
import java.util.Scanner;
public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
int answer1;
System.out.println("Do you like Java?");
answer1 = scan.nextInt();
if (answer1 == yes)
System.out.println("Cool ~");
else
System.out.println("Ehh...");
}
}
I want to put "yes" instead of the number 5.
So if the user types "yes" it will print "correct".
P.S. I didn't find a clear answer to that in the search engine.
It's not a duplicated thread as I'm trying to find a clear answer to that.
I need a detailed explanation about it.
I'm still a beginner, using those "high tech java words" won't help me.
You need to modify your program so that your scanner to reads a String instead of an int. You can do that as:
import java.util.Scanner;
public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
String answer1;
System.out.println("Do you like Java?");
answer1 = scan.next();
if (answer1.equals("yes"))
System.out.println("Cool ~");
else
System.out.println("Ehh...");
}
}
I used next() for this since we only want one word (token), but be aware that there are other options for reading Strings.
Notice also that I've changed the test in the condition because it's now a String. See this answer for more on comparing Strings.
You need to modify your program so that your scanner to reads a String instead of an int. You can do that as:
import java.util.Scanner; public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
String answer1;
System.out.println("Do you like Java?");
answer1 = scan.next();
if (answer1.equals("yes"))
System.out.println("Cool ~");
else
System.out.println("Ehh...");
} }
I used next() for this since we only want one word (token), but be aware that there are other options for reading Strings.
Notice also that I've changed the test in the condition because it's
now a String. See this answer for more on comparing Strings.
Ok, what if you want the program to read both words and numbers:
Here's my program (more in depth, when you see the full thing), but this is one of 5 parts (that look a like) where I'm having the program...
public static void Gdr1() {
try {
System.out.print("[Code: Gdr1] Grade 1: %");
Scanner gdr1 = new Scanner(System.in);
Z = gdr1.next();
Z = Double.toString(Grd1);
Grd1 = Double.parseDouble(Z);
if ((Grd1<100)&&(Grd1>=5)) {
Gdr2();
} else if ((Grd1>=100)&&(Grd1<125)) {
System.out.println(" System> Great Job "+Stu+"!");
Gdr2();
} else if (Grd1<5) {
System.out.println("I'm sorry, the lowest grade I am allowed to compute is 5...");
Gdr1();
} else if (Z.equalsIgnoreCase("restart")) {
restart01();
} else {
System.out.println("("+Z+") cannot be resolved in my system...");
Gdr1();
}
} catch (Exception e) {}
}
Now everything works in the program, besides for when the End-User's input = "restart", I know some of the code in the program seems complicated, but it does work (most of it), can anyone help me try to figure this out, its for my portfolio at my school due latest by 1/25/2017 # 11:59 pm.
The things like Z (constant String), ""+Stu+"" (variable input), and [Code: Gdr1] are there for a purpose...

Categories

Resources