The assignment asks for three strings of alphabetical input (that is, letters and no numbers), then compare lexicographically and draw the middle one.
I found a similar concern here (Java: Three strings, lexicographic order), but can't comment to add my question. I sorted (for an instant) how to appropriately return the output, but now the code isn't giving any output and I don't know what I did wrong.
public static void main(String[] args)
{
printHeading();
String topString;
String middleString;
String bottomString;
Scanner in;
in = new Scanner(System.in);
System.out.println("Please enter a first word:");
while (!in.hasNext("[A-Za-z]+"))
{
System.out.println("Please use only alphabetic values.");
System.out.println("Please enter a first word:");
in.nextLine(); // Captures the first word
}
String firstWord = in.nextLine();
System.out.println("Please enter a second word:");
while (!in.hasNext("[A-Za-z]+"))
{
System.out.println("Please use only alphabetic values.");
System.out.println("Please enter a second word:");
in.nextLine(); // Captures the second word
}
String secondWord = in.nextLine();
System.out.println("Please enter a third word:");
while (!in.hasNext("[A-Za-z]+"))
{
System.out.println("Please use only alphabetic values.");
System.out.println("Please enter a third word:");
in.nextLine(); // Captures the third word
}
String thirdWord = in.nextLine();
if (firstWord.equalsIgnoreCase(secondWord) && secondWord.equalsIgnoreCase(thirdWord))
{
System.out.println();
System.out.println("The words are the same! Please try again.");
}
if (firstWord.compareTo(secondWord) > 0 && firstWord.compareTo(thirdWord) > 0)
{
topString = firstWord;
}
else if (firstWord.compareTo(secondWord) < 0 && firstWord.compareTo(thirdWord) > 0)
{
middleString = firstWord;
System.out.println();
System.out.println("The second word in lexicographic order is: " + middleString);
}
else
{
bottomString = firstWord;
}
if (secondWord.compareTo(firstWord) > 0 && secondWord.compareTo(thirdWord) > 0)
{
topString = secondWord;
}
else if (secondWord.compareTo(firstWord) < 0 && secondWord.compareTo(thirdWord) > 0)
{
middleString = secondWord;
System.out.println();
System.out.println("The second word in lexicographic order is: " + middleString);
}
else
{
bottomString = secondWord;
}
if (thirdWord.compareTo(secondWord) > 0 && thirdWord.compareTo(firstWord) > 0)
{
topString = thirdWord;
}
else if (thirdWord.compareTo(secondWord) < 0 && thirdWord.compareTo(firstWord) > 0)
{
middleString = thirdWord;
System.out.println();
System.out.println("The second word in lexicographic order is: " + middleString);
}
else
{
bottomString = thirdWord;
}
Your string comparison statements are incorrect - you need to check them and rewrite it. Here is another way to do it:
import java.util.Scanner;
public class FindMiddleWord
{
public static void main(String[] args)
{
String[] wordArray = new String[3];
Scanner in;
in = new Scanner(System.in);
System.out.println("Please enter a first word:");
while (!in.hasNext("[A-Za-z]+"))
{
System.out.println("Please use only alphabetic values.");
System.out.println("Please enter a first word:");
in.nextLine(); // Captures the first word
}
String firstWord = in.nextLine();
wordArray[0] = firstWord;
System.out.println("Please enter a second word:");
while (!in.hasNext("[A-Za-z]+"))
{
System.out.println("Please use only alphabetic values.");
System.out.println("Please enter a second word:");
in.nextLine(); // Captures the second word
}
String secondWord = in.nextLine();
wordArray[1] = secondWord;
System.out.println("Please enter a third word:");
while (!in.hasNext("[A-Za-z]+"))
{
System.out.println("Please use only alphabetic values.");
System.out.println("Please enter a third word:");
in.nextLine(); // Captures the third word
}
String thirdWord = in.nextLine();
wordArray[2] = thirdWord;
String temp;
int i,j = 0;
for (i = 0; i < wordArray.length; i++) {
for (j = 0; j < wordArray.length; j++) {
if (wordArray[i].compareToIgnoreCase(wordArray[j]) < 0) {
temp = wordArray[i];
wordArray[i] = wordArray[j];
wordArray[j] = temp;
}
}
}
System.out.println("The Middle Word is : "+wordArray[1]);
}
}
Related
Ask the user to "Input a number: " 4 times.
If the input is not a number, ask again.
Output "success." after they have entered 4 numbers.
Please answer this code for me using while, if, if else and do statements.
int counter; System.out.print("Input a number: ");
while(!(scan.hasNextInt()));{
for (int i = 0; i < 3; i++){
scan.next();
System.out.print("Input a number: ");
if (!(pass.equals(pass2))) {
counter++;
} else if (!(scan.hasNextInt())) {
}
}
if (counter >= 2) {
System.out.println("Input a number: ");
}
} else if (!(scan.hasNextInt())) { System.out.println("success."); }
This is very basic stuff but I am struggling.
int[] inputIntegers = new int[4]; // Array to save input
Scanner scan = new Scanner(System.in);
int counter = 0;
while(counter < 4) {
System.out.println("Input a number: ");
String input = scan.next();
if(input.matches("[-]?[0-9]*")){ // Checking, if input is an integer
inputIntegers[counter]=Integer.parseInt(input); // Persing string to integer
counter++;
} else {
System.out.println("Input is not an integer");
}
}
System.out.println("Success");
scan.close(); //Do not forget do close scanner
System.out.println("Enter your phone number: ");
while(in.hasNextLong()) {
long phone = in.nextLong();
if(in.hasNextLong()) {
if(phone < 1000000000) {
System.out.println("Phone number: "+phone);
}
} else if(!in.hasNextInt()) {
System.out.println("Please enter a valid phone number: ");
} else if (phone < 1000000000) {
System.out.println("Please enter a valid phone number: ");
}
tried another way
boolean valid;
long phone;
do {
System.out.println("Enter your phone number: ");
if(!in.hasNextLong()) {
phone =in.nextLong();
if(phone > 1000000000) {
System.out.println("Please enter a valid phone number");
in.nextLong();
valid=false;
}
}
}while(valid=false);
System.out.println("Phone: " + phone);
as you can see it doesnt work at all especially if you input a non integer and it ask for input twice im sorry its a mess
edit: ok so is there a way without using regex? my lecturer hasnt taught it yet so im not sure im allowed to use regex
you need to use regex. take a look to
https://www.w3schools.com/java/java_regex.asp
and try something along the lines...
...
final boolean isValid = inputValue.match(^[0-9]{1,9}?) // 1 to 9 digits
if (isValid) {
...
}
...
I would recommend doing it this way:
System.out.println("Enter your phone number: ");
int phone;
for (;;) { // forever loop
String line = in.nextLine();
if (line.matches("[0-9]{1,9}")) {
phone = Integer.parseInt(line);
break;
}
System.out.println("Please enter a valid phone number: ");
}
System.out.println("Phone number: "+phone);
That's my approach without using regex
System.out.println("Enter your phone number: ");
int phone;
int index = 0;
while(true) {
String line = in.nextLine();
if (valid(line)){
phone = Integer.parseInt(line);
break;
}
System.out.println("Please enter a valid phone number: ");
}
System.out.println("Phone number: " + phone);
And the valid() method
boolean valid(String line){
if(line.length() > 9) return false;
for(int i = 0; i < line.length(); i++){
boolean isValid = false;
for(int asciiCode = 48; asciiCode <= 57 && !isValid; asciiCode++){
//48 is the numerical representation of the character 0
// ...
//57 is the numerical representation of the character 9
//see ASCII table
if((int)line.charAt(i) == asciiCode){
isValid = true;
}
}
if(!isValid) return false;
}
return true;
}
Hi this code is part of my code that is supposed to check if the number string is palindrome.
I want to iterate from top to botoom of my code but it doesn't iterate at all , what is wrong ??
I searched in youtube and realized this kind of things , people usually use do-while loop so I was trying to follow the instruction but it doesn't give me what I want .
do {
System.out.println("You passed Catch-Block stage! , Please enter the number that you want to check if it is palindrome");
String str = kbd.nextLine().trim();
String org_str = str;
String rev = "";
int len = str.length();
for (int i = len - 1; i >= 0; i--) {
rev = rev + str.charAt(i);
}
if (org_str.equals(rev)) {
System.out.println(org_str + " is Palindrome Number");
} else {
System.out.println(org_str + "is Not Palindrome String");
}
System.out.println("Do you want to continue Y or N");
choice = kbd.next().charAt(0);
}while(choice=='y'||choice =='Y');
}
Here is my full code.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
char choice;
long firstNum = 0;
firstNum = getLong(" Enter the first number: ", '-');
do {
System.out.println("You passed Catch-Block stage! , Please enter the number that you want to check if it is palindrome");
String str = kbd.nextLine().trim();
String org_str = str;
String rev = "";
int len = str.length();
for (int i = len - 1; i >= 0; i--) {
rev = rev + str.charAt(i);
}
if (org_str.equals(rev)) {
System.out.println(org_str + " is Palindrome Number");
} else {
System.out.println(org_str + "is Not Palindrome String");
}
System.out.println("Do you want to continue Y or N");
choice = kbd.next().charAt(0);
}while(choice=='y'||choice =='Y');
}
public static long getLong(String prompt, char exitChar)
{
long retVal = 0;
boolean validInput = false;
String userInput = "";
Scanner kbd = new Scanner(System.in);
while (!validInput) {
System.out.println(prompt);
try
{
userInput = kbd.nextLine().trim();
if (userInput.length() > 0 && userInput.charAt(0) == exitChar)
{
System.out.println("Ending the program at the user's request");
System.exit(1);
}
retVal = Long.parseLong(userInput);
validInput = true;
}
catch (Exception ex)
{
System.out.println("That is not numeric. Try again or press " + exitChar + "to Quit");
}
}
return retVal;
}
}
Change this:
String str = kbd.nextLine().trim();
to this
String str = kbd.next();
When read choice, using nextLine() intead of next():
do {
System.out.println("You passed Catch-Block stage! , Please enter the number that you want to check if it is palindrome");
String str = kbd.nextLine().trim();
String org_str = str;
String rev = "";
int len = str.length();
for (int i = len - 1; i >= 0; i--) {
rev = rev + str.charAt(i);
}
if (org_str.equals(rev)) {
System.out.println(org_str + " is Palindrome Number");
} else {
System.out.println(org_str + "is Not Palindrome String");
}
System.out.println("Do you want to continue Y or N");
choice = kbd.nextLine().charAt(0); // <---here, change to nextLine()
}while(choice=='y'||choice =='Y');
}
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input. so in next loop it reads last input line that will be empty string.
As I have shown the codes below, option 1 initiates setting up a player name but it has to be between 3 and 25 characters long and also should not have any blank space. What logic and methods should be used behind this reason after the (String name = " ") statement?
import java.util.*;
public class Game
{
private Player player;
public Game()
{
this.player = null;
}
public void showMenu()
{
while(true)
{
System.out.println("=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=");
System.out.println("Welcome to Lucky Vending Machine Game");
System.out.println("=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=");
System.out.println("Please select 1 to Register a Player");
System.out.println("Please select 2 to Play a Round");
System.out.println("Please select 3 to View Round Information");
System.out.println("Please select 4 to Get Help");
System.out.println("Please select 5 to Exit");
System.out.println("Choose an option: ");
Scanner menuScanner = new Scanner(System.in);
int option = menuScanner.nextInt();
if (option < 1 || option > 5)
{
System.out.println("Error: Please, choose a number from 1 to 5");
continue;
}
else if(option == 1)
{
System.out.println("Please enter the player name");
Scanner playerName = new Scanner(System.in);
String name = " ";
player = new Player(name);
}
}
}
}
public boolean isValidName(String playerName) {
int length = playerName.length();
return ((length >= 3 && length <= 25) && !playerName.contains(" "));
}
You can use the below piece of code, here I am including only else part
else if(option == 1)
{
System.out.println("Please enter the player name");
Scanner scanner = new Scanner(System.in);
String name = " ";
name = scanner.next(); // return type for next() is string
if(name.length()>=3 && name.length()<=25 && !name.contains(" ")){
player = new Player(name);
}else{
System.out.println('Name length should be between 3 and 25 characters");
}
}
First, no need for another Scanner. The first scanner can be used for the playerName scanning.
Second, it's somehow a basic grammar.
else if(option == 1)
{
System.out.println("Please enter the player name");
String name = menuScanner.next();
if (name.length >= 3 && name.length <= 25 && !Pattern.compile("\\s").matcher(name).find())
{
// valid name
player = new Player(name);
}
else
{
// invalid name, do some warning output and ask user to reenter again.
}
}
Note that "blank space" may not only contains white space, but maybe a \t too.
You can use this,
Scanner sc = new Scanner(System.in);
String PlayerName = "";
do {
System.out.println("Enter a player's name");
PlayerName = sc.nextLine();
if((PlayerName.length()<3 && PlayerName.length()>25)|| PlayerName.contains(" "))
System.out.println("Invalid number !!!");
}while((PlayerName.length()<3 && PlayerName.length()>25) || PlayerName.contains(" "));
If you have more validations, you can use the .matches() method by passing the regular expression in it.
I'm a beginner in java. I want to check first if the user input is String or Double or int. If it's String, double or a minus number, the user should be prompted to enter a valid int number again. Only when the user entered a valid number should then the program jump to try. I've been thinking for hours and I come up with nothing useful.Please help, thank you!
import java.util.InputMismatchException;
import java.util.Scanner;
public class Fizz {
public static void main(String[] args) {
System.out.println("Please enter a number");
Scanner scan = new Scanner(System.in);
try {
Integer i = scan.nextInt();
if (i % 3 == 0 && (i % 5 == 0)) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i + "は3と5の倍数ではありません。");
}
} catch (InputMismatchException e) {
System.out.println("");
} finally {
scan.close();
}
}
One simple fix is to read the entire line / user input as a String.
Something like this should work. (Untested code) :
String s=null;
boolean validInput=false;
do{
s= scannerInstance.nextLine();
if(s.matches("\\d+")){// checks if input only contains digits
validInput=true;
}
else{
// invalid input
}
}while(!validInput);
You can also use Integer.parseInt and then check that integer for non negativity. You can catch NumberFormatException if the input is string or a double.
Scanner scan = new Scanner(System.in);
try {
String s = scan.nextLine();
int x = Integer.parseInt(s);
}
catch(NumberFormatException ex)
{
}
Try this one. I used some conditions to indicate the input.
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
int charCount = input.length();
boolean flag = false;
for(int x=0; x<charCount; x++){
for(int y=0; y<10; y++){
if(input.charAt(x)==Integer.toString(y))
flag = true;
else{
flag = false;
break;
}
}
}
if(flag){
if(scan.hasNextDouble())
System.out.println("Input is Double");
else
System.out.println("Input is Integer");
}
else
System.out.println("Invalid Input. Please Input a number");
Try this. It will prompt for input until an int greater than 0 is entered:
System.out.println("Please enter a number");
try (Scanner scan = new Scanner(System.in)) {
while (scan.hasNext()) {
int number;
if (scan.hasNextInt()) {
number = scan.nextInt();
} else {
System.out.println("Please enter a valid number");
scan.next();
continue;
}
if (number < 0) {
System.out.println("Please enter a number > 0");
continue;
}
//At this stage, the number is an int >= 0
System.out.println("User entered: " + number);
break;
}
}
boolean valid = false;
double n = 0;
String userInput = "";
Scanner input = new Scanner(System.in);
while(!valid){
System.out.println("Enter the number: ");
userInput = input.nextLine();
try{
n = Double.parseDouble(userInput);
valid = true;
}
catch (NumberFormatException ex){
System.out.println("Enter the valid number.");
}
}