So I am currently working on a lab for class. I'll attach the lab below:
For this lab, you will use a series of nested if-else or if-else-if statements in order to convert a Roman Numeral number into its String word form. The numerals we are concerned with are I, II, III, IV, V, VI, VII, VIII, which coincide with One, Two, Three, Four, Five, Six, Seven, Eight. Numbers outside of this range are denied – you must tell the user that they are denied as input.
Your code must not fall for inputs like ‘I am the best roman numeral, ‘IIIlikefish’, or ‘VIII is delicious.’ Those inputs should be denied just like an input outside of I to VIII would be
What are possible ways to avoid falling for fake inputs?
Also, I currently have 8 different if statements, is there a faster way to do this?
import java.util.Scanner;
public class RomanNumeralChecker {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String romanNum;
System.out.println("Please enter a Roman Numeral between the values 1 and 8:");
romanNum = keyboard.next();
if (romanNum.equalsIgnoreCase("I")){
System.out.println(romanNum + " represents the number \"One\"");
}
else if (romanNum.equalsIgnoreCase("II")){
System.out.println(romanNum + " represents the number \"Two\"");
}
else if (romanNum.equalsIgnoreCase("III")){
System.out.println(romanNum + " represents the number \"Three\"");
}
else if (romanNum.equalsIgnoreCase("IV")){
System.out.println(romanNum + " represents the number \"Four\"");
}
else if (romanNum.equalsIgnoreCase("V")){
System.out.println(romanNum + " represents the number \"Five\"");
}
else if (romanNum.equalsIgnoreCase("VI")){
System.out.println(romanNum + " represents the number \"Six\"");
}
else if (romanNum.equalsIgnoreCase("VII")){
System.out.println(romanNum + " represents the number \"Seven\"");
}
else if (romanNum.equalsIgnoreCase("VIII")){
System.out.println(romanNum + " represents the number \"Eight\"");
}
else {
System.out.println("Sorry, but " + romanNum + " is out of the desired range.");
}
}
}
Your code is fine for what you need it to do. There are ways to check for valid entry other than what you have implemented but they may be a bit more involved. Professors tend to become upset (Maybe mines was just a jerk) when student do more than what is required for a coding lab.
In the code shown by #nakano531, there's no way that a "trick input" will work. If it what they input, literally does not match the HashMap, it will prompt them that they have entered an invalid answer. ( Don't have the necessary reputation points to say this under his answer, but I wanted to let you know)
Your code is using
romanNum = keyboard.next();
This will return first word from the given input.But you should use .
romanNum = keyboard.nextLine();
Which will read the entire String provided by the use like the ones( ‘I am the best roman numeral, ‘IIIlikefish’, or ‘VIII is delicious.’) you mentioned.
i Hope this will help you.
https://stackoverflow.com/help/someone-answers
public class answer {
public static void main (String[]args) {
Scanner sc = new Scanner(System.in);
String a0 = sc.nextLine();
String[]a1 = {"I","II","III","IV","V","VI","VII","VIII"};
String[]a2 = {"One","Two","Three","Four","Five","Six","Seven","Eight"};
for(int i=0;i<a1.length;i++) {
if(a0.equals(a1[i])) {
System.out.println(a0+" represent "+a2[i]);
}
else {
System.out.println("You Type smth wrong");
}
}
}
}
Okay, this is where we are now. The issue is I can't get the JOption windows to pop up after taking the users input.
public class RomanNumeralChecker {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String romanNum;
JOptionPane.showInputDialog(null,"Please enter a Roman Numeral between the values 1 and 8: ");
romanNum = keyboard.nextLine();
if (romanNum.charAt(0) == 'I') {
if (romanNum.equalsIgnoreCase("I"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"One\"");
if (romanNum.equalsIgnoreCase("II"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"Two\"");
if (romanNum.equalsIgnoreCase("III"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"Three\"");
if (romanNum.equalsIgnoreCase("IV"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"Four\"");
}
else if (romanNum.charAt(0) == 'V') {
if (romanNum.equalsIgnoreCase("V"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"Five\"");
if (romanNum.equalsIgnoreCase("VI"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"Six\"");
if (romanNum.equalsIgnoreCase("VII"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"Seven\"");
if (romanNum.equalsIgnoreCase("VIII"))
JOptionPane.showMessageDialog(null,romanNum + " represents the number \"Eight\"");
}
else {
JOptionPane.showMessageDialog(null,"Not in valid range.");
}
}
}
You can reduce the number of if statement by using Map.
import java.util.Scanner;
import java.util.*;
public class RomanNumeralChecker {
public static void main(String[] args) {
Map<String, String> m = new HashMap<String, String>();
m.put("I", "One");
m.put("II", "Two");
m.put("III", "Three");
m.put("IV", "Four");
m.put("V", "Five");
m.put("VI", "Six");
m.put("VII", "Seven");
m.put("VIII", "Eight");
System.out.println("Please enter a Roman Numeral between the values 1 and 8:");
Scanner keyboard = new Scanner(System.in);
String romanNum = keyboard.next();
String num = m.get(romanNum);
if (num != null) {
System.out.println(romanNum + " represents the number \"" + num + "\"");
} else {
System.out.println("Sorry, but " + romanNum + " is out of the desired range.");
}
}
}
Related
It will only go through one time so it will end with "Would you like to make another request?(y/n)"
and when I input "y" it stops there and won't do the loop.
package Chaterp5PPReynaGuerra;
import java.util.*;
public class MeetingRequest
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
final int CAPACITY=30;
String name;
int people;
int morePeople;
String answer="y";
int fewerPeople;
System.out.println("--------Meeting Request System"+
"--------");
System.out.println("\nWelcome to the Meeting Request System."+
" May I know your name?");
name=scan.nextLine();
while(answer.equalsIgnoreCase("y"))
{
System.out.println("Hello, "+name+", how many people"+
" will be attending the meeting?");
people=scan.nextInt();
morePeople = CAPACITY - people;
if(people < CAPACITY)
System.out.println("You can invite "+morePeople+
" more people to the meeting.");
else if(people > CAPACITY) {
fewerPeople= people - CAPACITY;
System.out.println("Sorry, the room is not "+
"big enough to seat that many people. You have to "+
"exclude "+fewerPeople+" from the meeting.");
}
System.out.println();
System.out.println("Would you like to make another"+
" request?(y /n)");
// gets rid of \n in the input stream
scan.next();
answer=scan.nextLine();
}
}
}
Replace
people=scan.nextInt();
with
people = Integer.parseInt(scan.nextLine());
Check Scanner is skipping nextLine() after using next() or nextFoo()? to learn more about it.
Given below is the corrected program:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
final int CAPACITY = 30;
String name;
int people = 0;
int morePeople;
String answer = "y";
int fewerPeople;
boolean valid;
System.out.println("--------Meeting Request System" + "--------");
System.out.println("\nWelcome to the Meeting Request System." + " May I know your name?");
name = scan.nextLine();
do {
do {
valid = true;
System.out.println("Hello, " + name + ", how many people" + " will be attending the meeting?");
try {
people = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
System.out.println("Invalid entry. Pleaase try again.");
valid = false;
}
} while (!valid);
morePeople = CAPACITY - people;
if (people < CAPACITY)
System.out.println("You can invite " + morePeople + " more people to the meeting.");
else if (people > CAPACITY) {
fewerPeople = people - CAPACITY;
System.out.println("Sorry, the room is not " + "big enough to seat that many people. You have to "
+ "exclude " + fewerPeople + " from the meeting.");
}
System.out.println();
System.out.println("Would you like to make another" + " request?(y /n)");
answer = scan.nextLine();
} while (answer.equalsIgnoreCase("y"));
}
}
A sample run:
--------Meeting Request System--------
Welcome to the Meeting Request System. May I know your name?
abc
Hello, abc, how many people will be attending the meeting?
x
Invalid entry. Pleaase try again.
Hello, abc, how many people will be attending the meeting?
10.4
Invalid entry. Pleaase try again.
Hello, abc, how many people will be attending the meeting?
4
You can invite 26 more people to the meeting.
Would you like to make another request?(y /n)
y
Hello, abc, how many people will be attending the meeting?
5
You can invite 25 more people to the meeting.
Would you like to make another request?(y /n)
n
Some other important points:
As you can see, a do...while loop is more appropriate instead of while loop in this case.
You should always check for the NumberFormatException whenever you parse a text (e.g. Scanner::nextLine()) to integer.
Using next() will only return what comes before the delimiter (defaults to whitespace). nextLine() automatically moves the scanner down after returning the current line.
To get rid of the \n use scan.nextLine
// gets rid of \n in the input stream
scan.nextLine();
answer=scan.nextLine();
Hope this help.
Where the commented section is, it says that there is a StackOverflowError - null. I am trying to get it to make random numbers to match up with an inputted value. The goal of this code is to do the following:
Accept a top number (ie 1000 in order to have a scale of (1-1000)).
Accept an input as the number for the computer to guess.
Computer randomly guesses the first number and checks to see if it is correct.
If it is not correct, it should go through a loop and randomly guess numbers, adding them to an ArrayList, until it guesses the input. It should check to see if the guess is already in the array and will generate another random number until it makes one that isn't in the list.
In the end, it will print out the amount of iterations with the count variable.
Code:
import java.util.*;
public class ArrNumGuess
{
public static Integer top, input, guess, count;
public static ArrayList <Integer> nums;
public static void main ()
{
System.out.println("Please enter the top number");
top = (new Scanner(System.in)).nextInt();
System.out.println("Please enter the number to guess (1 - " + top + ")");
input = Integer.parseInt(((new Scanner(System.in)).nextLine()).trim());
nums = new ArrayList<Integer>(); //use nums.contains(guess);
guess = (new Random()).nextInt(top) + 1;
nums.add(guess);
System.out.println("My first guess is " + guess);
count = 1;
if(guess != input)
{
guesser();
}
System.out.println("It took me " + count + " tries to find " + guess + " and " + input);
}
public static void guesser()
{
boolean check = false;
while(!check)
{
guess = (new Random()).nextInt(top) + 1; //Stack Overflow - null
if(nums.contains(guess) && !(guess.equals(input)))
{
count--;
guesser();
}
else if(guess.equals(input))
{
check = true;
System.out.println("My guess was " + guess);
// nums.add(guess);
count++;
}
else
{
System.out.println("My guess was " + guess);
nums.add(guess);
count++;
}
}
}
}
In guesser() method, you're invoking itself:
if(nums.contains(guess) && !(guess.equals(input)))
{
count--;
guesser();
}
There is quite a possibility it will never end. But all that is in while loop, so why not get rid of recurrence and do this in an iterative style?
OK - a different approach to your guesser for fun. Enumerate a randomized sequence of numbers in specified range (1 to 'top') and find the guess in the list whose index is effectively the number of "attempts" and return.
(BTW - #Andronicus answer is the correct one.)
/** Pass in 'guess' to find and 'top' limit of numbers and return number of guesses. */
public static int guesser(int guess, int top) {
List<Integer> myNums;
Collections.shuffle((myNums = IntStream.rangeClosed(1, top).boxed().collect(Collectors.toList())), new Random(System.currentTimeMillis()));
return myNums.indexOf(guess);
}
You are making it more complicated than it needs to be and introducing recursion unnecessarily. The recursion is the source of your stack overflow as it gets too deep before it "guesses" correctly.
There is a lot of sloppiness in there as well. Here's a cleaned up version:
import java.util.*;
public class Guess {
public static void main(String args[]) {
System.out.println("Please enter the top number");
Scanner scanner = new Scanner(System.in);
int top = scanner.nextInt();
System.out.println("Please enter the number to guess (1 - " + top + ")");
int input = scanner.nextInt();
if (input < 1 || input > top) {
System.out.println("That's not in range. Aborting.");
return;
}
ArrayList <Integer> nums = new ArrayList<>();
Random rng = new Random(System.currentTimeMillis());
while(true) {
int guess = rng.nextInt(top) + 1;
if (!nums.contains(guess)) {
nums.add(guess);
if (nums.size() == 1) {
System.out.println("My first guess is " + guess);
} else {
System.out.println("My guess was " + guess);
}
if (guess == input) {
System.out.println("It took me " + nums.size() + " tries to find " + guess);
break;
}
}
}
}
}
I wrote the piece of Java code below. When running it and typing in any value (either one defined, e.g. latte, or any other, e.g. az integer), I get an InputMismatchException.
As far as I could find answers, this exception means that the input type does not match the expected type. What am I missing, why isn't the code recognizing a String input? Thanks for the supprort.
Cheers, Gabor
package Lesson1;
import java.util.Scanner;
public class Coffee {
public static void main(String[] args) {
//I define the type of coffees as Strings, plus the order as String as well
String espresso = "espresso";
String americano = "americano";
String cappuccino = "cappuccino";
String latte = "latte";
String order = new String();
//I ask the user for their input
Scanner choice = new Scanner(System.in);
System.out.println("What kind of coffee would you like? We have: espresso, americano, cappuccino and latte");
//depending on the user's choice, the corresponding name is displayed; if any other string is entered, the else clause is displayed
if (order.equals(choice.next(espresso))) {
System.out.println("Your order: " + espresso);
} else if (order.equals(choice.next(americano))) {
System.out.println("Your order: " + americano);
} else if (order.equals(choice.next(cappuccino))) {
System.out.println("Your order: " + cappuccino);
} else if (order.equals(choice.next(latte))) {
System.out.println("Your order: " + latte);
} else {
System.out.println("Unfortunately we can't serve you. Have a nice day!");
}
}
}
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Lesson1.Coffee.main(Coffee.java:22)
You write once in default input, but you're trying to read multiple times using choice.next(..).
One solution is assign your choice in a String before the if-else statement and then check it using equalsIgnoreCase.
//I ask the user for their input
Scanner choice = new Scanner(System.in);
System.out.println("What kind of coffee would you like? We have: espresso, americano, cappuccino and latte");
String picked = choice.next();
//depending on the user's choice, the corresponding name is displayed; if any other string is entered, the else clause is displayed
if (picked.equalsIgnoreCase(espresso)) {
System.out.println("Your order: " + espresso);
} else if (picked.equalsIgnoreCase(americano)) {
System.out.println("Your order: " + americano);
} else if (picked.equalsIgnoreCase(cappuccino)) {
System.out.println("Your order: " + cappuccino);
} else if (picked.equalsIgnoreCase(latte)) {
System.out.println("Your order: " + latte);
} else {
System.out.println("Unfortunately we can't serve you. Have a nice day!");
}
I think you are using the Scanner wrong. Trying using the next() method with no parameters to get the user input, and only call it once (instead of inside each if else branch). Like this:
package com.company;
import java.util.Scanner;
public class Coffee {
public static void main(String[] args) {
//I define the type of coffees as Strings, plus the order as String as well
String espresso = "espresso";
String americano = "americano";
String cappuccino = "cappuccino";
String latte = "latte";
//I ask the user for their input
Scanner choice = new Scanner(System.in);
System.out.println("What kind of coffee would you like? We have: espresso, americano, cappuccino and latte");
//depending on the user's choice, the corresponding name is displayed; if any other string is entered, the else clause is displayed
String order = choice.next();
if (order.equals(espresso)) {
System.out.println("Your order: " + espresso);
} else if (order.equals(americano)) {
System.out.println("Your order: " + americano);
} else if (order.equals(cappuccino)) {
System.out.println("Your order: " + cappuccino);
} else if (order.equals(latte)) {
System.out.println("Your order: " + latte);
} else {
System.out.println("Unfortunately we can't serve you. Have a nice day!");
}
}
}
I am trying to write a code to give off the user's name in different formats after they enter it. However, if a user does not have a middle name, the system should print that there was an error. I have it so it works perfectly if the user enters three names but does not work if the user enters two names. Here is my code:
import java.util.Scanner;
public class Assignment3
{
public static void main(String[] args)
{
String fullName;
Scanner in = new Scanner(System.in);
System.out.print ("What are your first, middle, and last names? ");
fullName = in.nextLine();
System.out.println(fullName);
if (fullName.contains(" "))
{
String[] nameParts = fullName.split(" ");
String firstInitial = nameParts[0].substring(0,1).toUpperCase();
String secondInitial = nameParts[1].substring(0,1).toUpperCase();
String thirdInitial = nameParts[2].substring(0,1).toUpperCase();
if (nameParts[2].isEmpty())
{
System.out.println("No Middle Name Detected");
}
else
{
System.out.println ("Your initials are: " + firstInitial + secondInitial + thirdInitial);
String lastVariationOne = nameParts[2].substring(0, nameParts[2].length());
lastVariationOne = lastVariationOne.toUpperCase();
String firstVariationOne = nameParts[0].substring(0, nameParts[0].length());
firstVariationOne = firstVariationOne.substring(0,1).toUpperCase() + firstVariationOne.substring(1, nameParts[0].length());
System.out.println("Variation One: " + lastVariationOne + ", " + firstVariationOne + " " + secondInitial + ".");
String lastVariationTwo = nameParts[2].substring(0, nameParts[2].length());
lastVariationTwo = lastVariationTwo.substring(0,1).toUpperCase() + lastVariationTwo.substring(1, nameParts[2].length());
System.out.println("Variation Two: " + lastVariationTwo + ", " + firstVariationOne);
}
}
else
{
System.out.println("Wrong. Please enter your name properly.");
}
}
}
Instead of this:
if (nameParts[2].isEmpty())
{
System.out.println("No Middle Name Detected");
}
something like
if(nameParts.length != 3)
{
System.out.println("Invalid entry");
}
might be preferrable.
Basically, in the case that there are only two names entered, split() will return an array of length 2, whose elements are accessible by indices 0 and 1.
But in your if condition you attempt to access index 2, which could be out of bounds (it would be OOB for the case where you entered only two names).
To resolve this, you could either (a) try it like you do, but catch the ArrayIndexOutOfBoundsException or (b) check first that split produced a properly sized array, then go from there (this was the approach I took with the change I listed).
I'd suggest (b), but both approaches seem fine.
If you don't input middlename, would the array size be 2?
So there is NO namespart[2].
Just check size of namespart.
#jedwards jedwards's solution is there.
How do I round my numbers of output += Math.pow(baseUno, powernumber)+ " "; to the nearest whole number?
They always give me an output of, for example, 1.0 or 2.0. How do you round these so that they would simply result as 1 and 2?
import javax.swing.*;
import java.text.*;
import java.util.*;
public class level7Module1
{
public static void main(String[] args)
{
String base, power, output = " "; //user inputs, and the output variable
double baseUno, powerUno, basenum = 0, powernum = 0; //user inputs parsed so they can be used in mathematical equations
DecimalFormat noDigits = new DecimalFormat("0");
// oneDigit.format(variablename)
base = JOptionPane.showInputDialog(null,"Enter your prefered base, a number between 1 and 14: \nPress 'q' to quit."); //User input
if (base.equals("q"))
{
JOptionPane.showMessageDialog(null,"Goodbye!");
System.exit(0); //quits
}
baseUno = Integer.parseInt(base);
// basenum = noDigits.format(baseUno);
if (baseUno <= 0)
{
JOptionPane.showMessageDialog(null,"Really? Why would you try to trick me? ):");
System.exit(0);
}
if (baseUno > 14)
{
JOptionPane.showMessageDialog(null,"That wasn't cool. Take some time to think about this \nand\nthen\ntry\nagain.\n\n\n\n\n\n\n\nJerk.");
System.exit(0);
}
//I chose 0 and 14 because on my monitor the combination of 14 and 14 filled up the entire screen, so I limited to things
//that would fit on my monitor :)
power = JOptionPane.showInputDialog(null, "How many numbers of this base would you like? Between 1 and 14 again, please.\nPress 'q' to quit.");
if (power.equals("q"))
{
JOptionPane.showMessageDialog(null,"Goodbye!");
System.exit(0);
}
powerUno = Integer.parseInt(power);
// powernum = noDigits.format(powerUno);
if (powerUno <= 0)
{
JOptionPane.showMessageDialog(null,"Really? Why would you try to trick me? ):");
System.exit(0);
}
if (powerUno > 14)
{
JOptionPane.showMessageDialog(null,"That wasn't cool. Take some time to think about this \nand\nthen\ntry\nagain.\n\n\n\n\n\n\n\nJerk.");
System.exit(0);
}
for (int powernumber=0; powernumber!=powerUno; powernumber++) //Set the number of powers done to 0, then until it's "powernum" input, it keeps going.
{
output += Math.pow(baseUno, powernumber)+ " "; //Output is the basenum to the power of powernum plus a space, then repeats condition above.
}
JOptionPane.showMessageDialog(null,"Your numbers are: " + output); //Giving the users their outputs
}
}
To the simplest approach change this line :
JOptionPane.showMessageDialog(null,"Your numbers are: " + output);
to
JOptionPane.showMessageDialog(null,"Your numbers are: " + (int)output);
just type caste the result to int