Java Scanner class to JOptionPane class? - java

This is what this code does: Allows the user to enter one character (L or S) and three integers between 100 and 1000. The program outputs the following:
Display the message: “Wrong input!” if the numbers are not included in the interval [100-1000] using method CheckInput;
The largest number if the user enters the letter L, using method Largest;
The smallest number if the user enters the letter S, using method Smallest;
All numbers and their digits reversed using the method Backwards;
Using the method EvenOrOdd that takes one integer and outputs ‘True’ if the number is even or ‘False’ if it is odd, output the numbers entered followed by ‘True’ or ‘False’
Use the method CheckDivisor, that takes all three numbers and checks if the first number is a divisor of the second or third, and returns ‘True’ or ‘False’
Make the output easier to understand and add two more methods to the program
For number 7 I added, double and sum
import java.util.Arrays;
import java.util.Scanner;
public class Words {
public static void main(String[] args) {
Scanner scan = new Scanner(System. in );
while (scan.hasNext()) {
String line = scan.nextLine();
if (line.equals("exit")) {
break;
}
String[] words = line.split(" ");
//alphabetical
System.out.print("Alphabetical order: ");
alphabetical(words);
// concatenate and mix
String[] sorted = words.clone();
Arrays.sort(sorted);
String all = "";
for (String s: sorted) {
all += s;
}
System.out.println("All together: " + all);
System.out.println("Concatenate and Mix: " + mix(all));
// find first 2 and last 2 letters
first2last2(all);
//middlexx
System.out.println("Replace middle with xx or yy: " + middlexx(all));
System.out.println();
}
}
private static void alphabetical(String[] words) {
String[] ws = words.clone();
Arrays.sort(ws);
for (int i = 0; i < ws.length; i++) {
if (i != 0) {
System.out.print(" ");
}
System.out.print(ws[i]);
}
System.out.println();
}
private static String mix(String s) {
return s.replaceAll("a|e|i|o|u", "x");
}
private static void first2last2(String s) {
if (s.length() < 5) {
System.out.println("Invalid command!");
} else {
System.out.println("First two characters: " + s.substring(0, 2));
System.out.println("Last two characters: " + s.substring(s.length() - 2, s.length()));
}
}
private static String middlexx(String s) {
if (s.length() % 2 == 0) {
return s.substring(0, s.length() / 2) + "xx" + s.substring(s.length() / 2, s.length());
} else {
return s.substring(0, s.length() / 2) + "yy" + s.substring(s.length() / 2 + 1, s.length());
}
}
}
How would I convert this into JOptionPane class? I want the program to ask the user to type L or S, and to type 3 integers using something like this:
String input1 = JOptionPane.showInputDialog("Please enter L or S");
a = Double.valueOf(input1).doubleValue();

You can take input from JOptionPane like this
JOptionPane.showInputDialog ( "put your message here" );
Sample Code
Object[] possibilities = {"ham", "spam", "yam"};
String s = (String)JOptionPane.showInputDialog(
frame,
"Complete the sentence:\n"
+ "\"Green eggs and...\"",
"Customized Dialog",
JOptionPane.PLAIN_MESSAGE,
icon,
possibilities,
"ham");
//If a string was returned, say so.
if ((s != null) && (s.length() > 0)) {
setLabel("Green eggs and... " + s + "!");
return;
}
//If you're here, the return value was null/empty.
setLabel("Come on, finish the sentence!");
For More: https://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html

Related

Hangman: How do you reveal letters when they are guessed?

I am creating a hangman program in java. The program is supposed to randomly generate the word and as the user correctly guesses a letter it should reveal it. I have created the function where it prints the amount of underscores depending on the length of the word. The issue I have is I'm not sure how I'm supposed to replace the underscore with the letter when it's guessed.
public static void main(String[] args) {
int choice;
String wordSoFar = "";
Console.print("Take your time.");
choice = Console.readInt("Enter your choice, when you're ready : ");
}
if (choice == 1) {
for (int i = 0; i < wordLength; i++) {
word += " _ ";
}
do {
String guess = Console.readString("Enter your guess here : ");
String response = secert(guess);
Console.print(response);
} while (incorrectLetters < maxIncorectLetters || correctLetters < wordLength);
}
}
public static String secretWordSelector(String secretWord) {
String[] secretWordsList = { "fun", "boring", "yellow", "phython", "tesla", "iphone", "computer", "adventure",
};
int min = 0;
int max = 8;
secretWord = secretWordsList[randomNumber(min, max)];
return secretWord;
}
public static String letterChecker(String guess, String wordSoFar) {
String response = "";
String secertWord = "";
if (secretWord == guess)) {
int index = secretWord.indexOf(guess);
correctLetters++;
answer = "Congratulations!
} else {
answer= "That is a incorrect guess!
}
return answer;
}
Your code can be improved a lot by the following changes:
You do not need the complex function, randomNumber. You can simply pass the length of the array to Random#nextInt and it will generate an int in the range of 0 to length_of_array - 1.
Similarly, your function, length is not required. You can simply call String#length to get the length of the string.
You have unnecessarily passed an argument to your function, secretWordSelector.
Since you are using String wordSoFar in multiple methods, it will be easier to process it by making it global.
You have called secretWordSelector again in letterChecker which is wrong. You have to process the same word which was selected randomly at the time when the user selected a choice.
Your while loop is infinite because of the wrong operator. It should be while (incorrectLetters < maxIncorectLetters && correctLetters < wordLength)
I have re-written the method, letterChecker with many changes which are self-explanatory. I have also put some comments to help you understand its code easily.
Code incorporating these improvements:
import java.util.Random;
import java.util.Scanner;
public class Main {
private static int incorrectLetters;
private static int correctLetters;
private static String wordSoFar = "";
public static void main(String[] args) {
int choice;
Scanner scanner = new Scanner(System.in);
final int maxIncorectLetters = 6;
System.out.println("Welcome to Mahmoud's Hangman game!");
System.out.println("Would you like to play. 1 - Yes. 0 - No");
System.out.print("Enter your choice: ");
choice = Integer.parseInt(scanner.nextLine());
if (choice == 0) {
System.out.println("Take your time.");
System.out.print("Enter your choice, when you're ready: ");
choice = Integer.parseInt(scanner.nextLine());
}
if (choice == 1) {
System.out.println("Be careful, you can only have 6 wrong guesses");
int wordLength = 0;
String secretWord = secretWordSelector();
wordLength = secretWord.length();
System.out.println("Your word has " + wordLength + " letters.");
for (int i = 0; i < wordLength; i++) {
wordSoFar += "_";
}
do {
System.out.print("Enter your guess here: ");
String guess = scanner.nextLine();
String response = letterChecker(guess.toLowerCase().charAt(0), secretWord);
System.out.println(response);
} while (incorrectLetters < maxIncorectLetters && correctLetters < wordLength);
}
}
public static String secretWordSelector() {
String[] secretWordsList = { "geography", "cat", "yesterday", "java", "truck", "opportunity", "fish", "token",
"transportation", "bottom", "apple", "cake", "remote", "boots", "terminology", "arm", "cranberry",
"tool", "caterpillar", "spoon", "watermelon", "laptop", "toe", "toad", "fundamental", "capitol",
"garbage", "anticipate", "pesky" };
return secretWordsList[new Random().nextInt(secretWordsList.length)];
}
public static String letterChecker(char guess, String secretWord) {
String response = "";
// Initialize a StringBuilder with wordSoFar
StringBuilder sb = new StringBuilder(wordSoFar);
if (secretWord.indexOf(guess) != -1) {// i.e. if guess is present in secretWord
// Replace each corresponding occurrence of '_' in the StringBuilder with guess
for (int i = 0; i < secretWord.length(); i++) {
char ch = secretWord.charAt(i);
if (ch == guess) {
sb.setCharAt(i, ch);
correctLetters++;
}
}
// Assign the updated StringBuilder to wordSoFar
wordSoFar = sb.toString();
return "Congratulations! You have guessed correctly. " + " You have " + incorrectLetters
+ " incorrect guesses " + wordSoFar;
}
incorrectLetters++;
response = "That is a incorrect guess! " + " You have " + incorrectLetters + " incorrect guesses " + wordSoFar;
return response;
}
}
A sample run:
Welcome to Mahmoud's Hangman game!
Would you like to play. 1 - Yes. 0 - No
Enter your choice: 1
Be careful, you can only have 6 wrong guesses
Your word has 4 letters.
Enter your guess here: o
That is a incorrect guess! You have 1 incorrect guesses ____
Enter your guess here: e
That is a incorrect guess! You have 2 incorrect guesses ____
Enter your guess here: a
That is a incorrect guess! You have 3 incorrect guesses ____
Enter your guess here: h
Congratulations! You have guessed correctly. You have 3 incorrect guesses ___h
Enter your guess here: f
Congratulations! You have guessed correctly. You have 3 incorrect guesses f__h
Enter your guess here: i
Congratulations! You have guessed correctly. You have 3 incorrect guesses fi_h
Enter your guess here: s
Congratulations! You have guessed correctly. You have 3 incorrect guesses fish

if/else statement is not being read correctly by the program

This is a program that list several facts about an integer input from a Scanner object. However, I'm having some trouble with the if/else statement at the end.
The problem is if the input is a positive integer other than 0, the program always reads this statement: System.out.println("j) It is smaller than its reverse value: " + reverse);. If it's a negative int, it always prints System.out.println("j) It is bigger than its reverse value: " + reverse);.
I think it's because the data that's stored in reverse is 0, because int reverse = 0; is declared before the while loop. However, the program properly prints the reverse of the input.
import java.util.Scanner;
public class Integer {
public static void main(String[] args) {
System.out.println("This program will:");
System.out.println("1) Prompt you for an integer then \n2) List several facts about that integer");
Scanner keyboard = new Scanner (System.in); // define a Scanner object attached to a keyboard
System.out.print("\nEnter an integer: "); // prompt the user to enter an integer
while ( ! keyboard.hasNextInt()) { // is the first input value an int?
String badInput; // assign non-integer inputs to badInput
badInput = keyboard.next();
System.out.println("Error: expected an integer, encountered: " + badInput);
System.out.print("Please enter an integer: ");
}
int integer = keyboard.nextInt(); // assign the input to the integer variable
System.out.println("A list of several facts about the number: " + integer); // safe to read first input value
System.out.println("================================================================");
// print the input with space betweeen each digits
System.out.print("a) The digit(s) in it is/are: ");
String number = String.valueOf(integer);
for ( int count = 0; count < number.length(); count++) {
char counted = number.charAt(count); // read each digit in the input
System.out.print(counted + " ");
}
System.out.println(); // skip a line
// determine whether the input is negative or positive
if ( integer >= 0 ) {
System.out.println("b) It is positive");
}
else {
System.out.println("b) It is negative");
}
// determine whether the input is even or odd
if (integer % 2 == 0) {
System.out.println("c) It is even");
}
else {
System.out.println("c) It is odd");
}
int countOdd = 0;
int countEven = 0;
int countDigit = 0;
int countZero = 0;
int reverse = 0;
int sum = 0;
int product = 1;
int readRightMost;
while(integer != 0) {
readRightMost = integer % 10; // read rightmost digit in the input
reverse = reverse * 10 + readRightMost;
integer /= 10; // drop the rightmost digit in the input
++countDigit;
sum += readRightMost;
product *= readRightMost;
if (readRightMost % 2 == 0){ // count how many even digits are in the input
++countEven;
}
else { // count how many odd digits are in the input
++countOdd;
}
if (readRightMost == 0) { // count how many zero digits are in the input
++countZero;
}
}
System.out.println("d) It has " + countDigit + " digit(s)");
System.out.println("e) It has " + countOdd + " odd digit(s)");
System.out.println("f) It has " + countEven + " even digit(s)");
System.out.println("g) It has " + countZero + " zero digit(s)");
System.out.println("h) The sum of the digits in it is " + sum);
System.out.println("i) The product of the digits in it is " + product);
if (integer < reverse) { // if the reverse value of an int is greater than its original value
System.out.println("j) It is smaller than its reverse value: " + reverse);
}
else { // if the reverse value of an int is lesser than its original value
System.out.println("j) It is bigger than its reverse value: " + reverse);
}
System.out.println("================================================================");
}
}
At the end of your while(integer != 0) loop, you know integer must be 0, and you never change it again before your if (integer < reverse), so it may as well be if (0 < reverse), which has exactly the behavior you're seeing. To fix it, make your loop operate on a different variable than you test later.

Counting even and odd number of letters in words

I am currently trying to count how many words from a textfile have even numbers and odd numbers of characters but I cant seem to get it to work. so far i have done
int countEven = 0;
int countOdd = 0;
for (int i = 0; i <latinLength.length(); i++) {
if (Character.isLetter(latinLength.charAt(i))) {
countEven++;
} else {
countOdd++;
}
}
System.out.println("Total number of unique even words in Latin names = " + countEven);
System.out.println("Total number of unique odd words in Latin names = " + countOdd);
}
i think what i did wrong is i am not accessing the right part of the text file. i do have a get function for the information i want which is getLatinName, but i am not sure how to implement it correctly
String tempLatinName = " ";
String latinLength = " ";
int letters = 0;
for (int i = 0; i < info.size(); i++) {
tempLatinName = info.get(i).getLatinName();
latinLength = tempLatinName.replace(" ","");
letters += latinLength.length();
}
System.out.println("Total number of letters in all Latin names = " + letters);
i have edited the code to show the bit i have done before trying to calculate how many words have odd and even number of characters, the code above is to calculate the total number of characters in each word and then gives me a total
/**
*
* #author g_ama
*/
import java.io.*;
import java.util.*;
public class Task1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
BufferedReader reader = new BufferedReader(new FileReader("shark-data.txt"));
String line;
List<Shark> info = new ArrayList<>();
while ((line = reader.readLine()) != null) {
String[] data = line.split(":");
int MaxLength = Integer.parseInt(data[2]);
int MaxDepth = Integer.parseInt(data[3]);
int MaxYoung;
try {
MaxYoung = Integer.parseInt(data[4]);
} catch (Exception X) {
MaxYoung = -1;
}
int GlobalPresence = Integer.parseInt(data[5]);
ArrayList<String> OceanicRegion = new ArrayList<>();
String[] Region = data[6].split(",");
for (String Element : Region) {
OceanicRegion.add(Element);
}
Shark shark = new Shark(data[0], data[1], MaxLength, MaxDepth, MaxYoung, GlobalPresence, OceanicRegion);
info.add(shark);
}
Collections.sort(info);
System.out.println("The three largest sharks");
System.out.println(info.get(info.size() - 1).getCommonName() + ", " + info.get(info.size() - 1).MaxLength + " cm");
System.out.println(info.get(info.size() - 2).getCommonName() + ", " + info.get(info.size() - 2).MaxLength + " cm");
System.out.println(info.get(info.size() - 3).getCommonName() + ", " + info.get(info.size() - 3).MaxLength + " cm");
System.out.println("The three smallest sharks");
System.out.println(info.get(0).getCommonName() + ", " + info.get(0).MaxLength + " cm");
System.out.println(info.get(1).getCommonName() + ", " + info.get(1).MaxLength + " cm");
System.out.println(info.get(2).getCommonName() + ", " + info.get(2).MaxLength + " cm");
//count total characters for Latin Name
String tempLatinName = " ";
String latinLength = " ";
int letters = 0;
for (int i = 0; i < info.size(); i++) {
tempLatinName = info.get(i).getLatinName();
latinLength = tempLatinName.replace(" ", "");
letters += latinLength.length();
}
System.out.println("Total number of letters in all Latin names = " + letters);
//count even or odd words
int countEven = 0;
int countOdd = 0;
for (int i = 0; i < latinLength.length(); i++) {
if (Character.isLetter(latinLength.charAt(i))) {
countEven++;
} else {
countOdd++;
}
}
System.out.println("Total number of unique even words in Latin names = " + countEven);
System.out.println("Total number of unique odd words in Latin names = " + countOdd);
}
}
Explanation
Currently you are only counting how many letters and non-letters your text has. That is of course not the amount of even words or odd words.
For example if you have a word like
test12foo!$bar
Your code will currently output
countEven => 10 // Amount of letters (testfoobar)
countOdd => 4 // Amount of non-letters (12!$)
Compare this to your if-condition:
if (Character.isLetter(latinLength.charAt(i))) {
countEven++;
} else {
countOdd++;
}
What you want is to count how often the length of your words is even or odd, so suppose words like
test // length 4, even
foo // length 3, odd
bartest // length 7, odd
then you want
countEven => 1 // (test)
countOdd => 2 // (foo, bartest)
Solution
Instead you will need to split your text into words (tokenize). After that you will need to count, for each word, the amount of characters. If that is even you may increase countEven by one. Likewise countOdd++ if it's an odd number.
The core will be this condition
word.length() % 2 == 0
it is true if the word has an even length and false if it's odd. You can easily verify this yourself (% returns the remainder after division, 0 or 1 in this case).
Let's assume your text structure is simple and words are always separated by whitespace, i.e. something like
test foo bar John Doe
All in all your code could then look like
Path path = Paths.get("myFile.txt");
AtomicInteger countEven = new AtomicInteger(0);
AtomicInteger countOdd = new AtomicInteger(0);
Pattern wordPattern = Pattern.compile(" ");
Files.lines(path) // Stream<String> lines
.flatMap(wordPattern::splitAsStream) // Stream<String> words
.mapToInt(String::length) // IntStream length
.forEach(length -> {
if (length % 2 == 0) {
countEven.getAndIncrement();
} else {
countOdd.getAndIncrement();
}
});
System.out.println("Even words: " + countEven.get());
System.out.println("Odd words: " + countOdd.get());
Or without all that Stream stuff:
Path path = Paths.get("myFile.txt");
List<String> lines = Files.readAllLines(path);
List<String> words = new ArrayList<>();
// Read words
for (String line : lines) {
String[] wordsOfLine = line.split(" ");
words.addAll(Arrays.asList(wordsOfLine));
}
// Count even and odd words
int countEven = 0;
int countOdd = 0;
for (String word : words) {
if (word.length() % 2 == 0) {
countEven++;
} else {
countOdd++;
}
}
System.out.println("Even words: " + countEven);
System.out.println("Odd words: " + countOdd);
Adjusted to your specific code
As you've just added your specific code I'll add a solution adapted to it.
In your code the list info contains all Sharks. From those sharks the words you want to consider is represented by Shark#getLatinName. So all you will need to do is some kind of this:
List<String> words = info.stream() // Stream<Shark> sharks
.map(Shark::getLatinName) // Stream<String> names
.collect(Collectors.toList());
and you can use this words exactly as shown in the other code examples. Alternatively you don't need to collect everything into a new list, you can directly stay in the Stream and continue with the stream-approach shown before. All in all:
AtomicInteger countEven = new AtomicInteger(0);
AtomicInteger countOdd = new AtomicInteger(0);
info.stream() // Stream<Shark> sharks
.map(Shark::getLatinName) // Stream<String> names
.mapToInt(String::length) // IntStream length of names
.forEach(length -> {
if (length % 2 == 0) {
countEven.getAndIncrement();
} else {
countOdd.getAndIncrement();
}
});
System.out.println("Even words: " + countEven);
System.out.println("Odd words: " + countOdd);
And substitute this into that part in your code:
//count even or odd words
(substitute here)

I keep getting "Invalid constant error" on my program and I am not sure why?

This is my code that calculates ISBN 13th number but I seem to be having trouble. It keeps giving me an error on the return about invalid character constant and every time I change it, it gives an error on the method name I don't understand why.
import java.util.Scanner;
public class ISBN {
public static int VerifyISBN(String isbn) {
if(isbn.matches("[0-9]+") && isbn.length() > 12){
for(int i = 0; i < 12; i++){
char digit = isbn.charAt(i);
int sum = 0;
if (Character.isDigit(digit)){
int digitValue = digit - '0';
if(i % 2 == 0)
sum += digitValue;
else sum += 3 * digitValue;
}
else
return 'invalid'; (This is where I get the error)
}
}
}
public static void main(String[] args) {
final String TITLE = "ISBN-13 Identifier";
System.out.println("Welcome to the " + TITLE);
Scanner input = new Scanner(System.in);
String response;
do {
System.out.print("Enter the first 12 digits of an ISBN-13: ");
String isbn = input.nextLine().trim();
//String isbnVerifier = generateISBN(isbn);
//if(isbn.equals("INVALID"));
System.out.println("The 13th number of" + isbn + " is " +
((verifyISBN(isbn))));
System.out.print("Do this again? [nY]");
response = input.nextLine().toUpperCase();
} while (!response.equals("N"));
input.close();
System.out.println("Thank you for using the " + TITLE);
}
}
Two problems:
The literal 'invalid' is incorrect Java syntax. A string is delimited with double quotes. Single quotes are used to delimit single-character literals, such as 'a' but cannot be used for strings of characters.
The method is declared to return an integer, so you cannot return a String.
If your intent is to return a sentinel value indicating that the input was invalid, you should probably use something like -1, which can then be interpreted by the caller as the error condition.
Or, you could define the method to throw an exception.

Recursive method print string and counts down by 1 and deletes 1 letter for each recursion

I'm working on a recursive method that will return and print in my main method a String that will count down by 1 for N. Deleting one letter for each recursion for the string. Until N becomes 1 or until the string has 1 letter. (N being a int on the commandline)
For example if my command lines aruments are: 5 valentine
It should output too:
5 valentine, 4 alentine, 3 lentine, 2 entine, 1 ntine,
So far I managed to count down the number inputted on the commandline argument. I just don't know how to go about deleting one letter from the string? :o
My code so far:
public static void main(String[] args){
int number = Integer.parseInt(args[0]);
String word = new String("");
word = args[1];
String method = recursive.method1(number);
System.out.println(method);
}
public static String method1(int number){
if (number < 0){
return "";
}
else{
return number + ", " + method1(number - 1);
}
}
You can read through subString() documentation to understand how to go about taking the portions of a String.
Change your method definition to include the word
Add the word to your return statement: return number + " " + word +...
Call substring of the original word from the 1st index
Check for <=0 rather than <0
Code:
public static void main(String[] args){
int number = 5;
String word = new String("");
word = "Valentine";
String method = Recurcive.method1(number, word);
System.out.println(method);
}
public static String method1(int number, String word){
if (number <= 0){
return "";
}
else{
return number + " " + word + ", " + method1(number - 1, word.substring(1));
}
}
Gives,
5 Valentine, 4 alentine, 3 lentine, 2 entine, 1 ntine,

Categories