This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I want to be able to make my if statement restart the program if "Yes" is inputted, end the program if "No" is imputed, and say "Capitalization is important" if neither "Yes" or "No" is inputted.
Scanner sc = new Scanner(System.in);
final String vowels = "aeiouAEIOU";
System.out.println("Enter your word:");
String word = sc.nextLine();
while (!word.equalsIgnoreCase("done"))
{
String beforVowel = "";
int cut = 0;
while (cut < word.length() && !vowels.contains("" + word.charAt(cut)))
{
beforVowel += word.charAt(cut);
cut++;
}
if (cut == 0)
{
cut = 1;
word += word.charAt(0) + "w";
}
System.out.println(word.substring(cut) + beforVowel + "ay");
Scanner keyboard = new Scanner (System.in);
System.out.print("Do you wish to convert another setence ");
String name = keyboard.nextLine();
if(name = "Yes"){
new Prog508a().launch;
}
if(name = "No"){
break;
}
else{
System.out.print("Capitalzation is important.");
}
String name = keyboard.nextLine();
if(name = "Yes"){
new Prog508a().launch;
}
if(name = "No"){
break;
}
This is really not a good way to do this, I suggest you use method returns instead.
Also you should not use
if(name = "Yes")
Since it is not a comparison, a better way of doing this would be
if(name.contains("y") || name.contains("Y")){
As this allows the user to enter anything starting with y or Y, but if you really want to use 'Yes' then you should do
if(name.equals("Yes"))
Related
Essentially my assignment is supposed to take 2 words, calculate the smallest of the two which I have done, but now I need to reference the smallest word itself instead of the number. Which I believe requires an If statement, but I cannot get my String to initialize and the console gets picky when I end the program with the system.out.println command.
Scanner scan = new Scanner(system.In);
System.out.println(" Input first password ");
String pass1 = scan.nextLine();
Int pass1l = pass1.length();
System.out.println(" input second password ");
String pass2 = scan.nextLine();
Int pass2l = pass2.length();
Int spassl = Math.min(pass1l,pass2l);
// problematic part here.
String spass;
If (pass1l > pass2l){ spass = pass2}
else if (pass1l < pass2l) {spass = pass1}
else if (pass1l == pass2l) {spass = null;};
Also the Else if statements come up as not statements and the first is an illegal start of an expression.
Then if I fix those I call spass with system.out and it says it's not initialized. I just started learning basic Java, I've used processing before but not for String related if statements, only integers.
You are almost there. the variable spass needs to be initialized as you are using if blocks without final else. Either you give spass="" or change final else if to else as below.
Scanner scan = new Scanner(System.in);
System.out.println(" Input first password ");
String pass1 = scan.nextLine();
System.out.println(" input second password ");
String pass2 = scan.nextLine();
// problematic part here.
String spass;
if (pass1.length() > pass2.length()) {
spass = pass2;
} else if (pass1.length() < pass2.length()) {
spass = pass1;
} else {
spass = null;
}
System.out.println("result: " + spass);
your problem is just a formating problem, if statements are formatet like this:
if(condition){
do_something;
}else if( second_condition ){
do_something_else;
}else{
alternative;
}
In your case it seems that you dont know where to set semicolons ;
You have to set semicolons inside the if block like this:
String spass;
If (pass1l > pass2l){
//Here semicolon
spass = pass2;
} else if (pass1l < pass2l) {
//Here semicolon
spass = pass1;
}else if (pass1l == pass2l) {
//Here semicolon
spass = null;
}
//No semicolon at the end of the if-else-statement
This question already has answers here:
Recognizing text in a String Array
(3 answers)
Closed 7 years ago.
do{
input.nextLine();
linhas [nLinhas] = input.nextLine();
nLinhas++;
}
while ();
I have this inside a switch which is inside a do-while (menu). I am doing a text editor, in which I ask the user for input, and in this part I'm trying to store the input in "String [] linhas".
(Portuguese) | (English)
Linhas = Lines
nLinhas = Number of Lines
The two nextLine() is because of a previous next().charAt().
The program should keep asking for more input unless the user presses ENTER two times... How do I go about doing this? I've tried using .length, .contains, but nothing worked...
This works will take multiple "enter" keystrokes:
Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();
while(readString!=null) {
System.out.println(readString);
if (readString.isEmpty()) {
System.out.println("Read Enter Key.");
}
if (scanner.hasNextLine()) {
readString = scanner.nextLine();
} else {
readString = null;
}
}
Have you tried adding a KeyListener and checking when the user hits Enter? Store a variable for space bar presses in a row, and if that number hits 2, perform an action.
Scanner scanner = new Scanner(System.in);
boolean hasNotEnd=true;
while(hasNotEnd) {
System.out.println("read 1st input0");
String readString1 = scanner.nextLine();
System.out.println("read 2nd input0");
String readString2 = scanner.nextLine();
if(readString1.isEmpty() && readString2.isEmpty()){
hasNotEnd=false;
}
This will be one solution
do {
String inputLine = input.nextLine();
linhas [nLinhas] = inputLine;
if (nLinhas > 1 && linhas[nLinhas].equals("") && linhas[nLinhas-1].equals("")) {
break;
}
nLinhas++;
}
while (true);
do{
String inputString;
inputString=input.nextLine();
linhas [nLinhas] = inputString;
if(nLinhas > 0 && linhas [nLinhas-1].equals("") && linhas [nLinhas].equals("")){
break;
}
nLinhas++;
}
while (true);
Here's the program that I'm working on but I'm having problems with figuring out how to ask the user if they are done with it by saying a word or number.
import java.util.Scanner;
class paliindrome {
public static void main(String args[]) {
String isPalindrome, reverse = "";
Scanner in = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
PalindromeChecker aGame = new PalindromeChecker();
System.out.println(" Please type a word and I'll figure out if it's a palindrome(The program is case sensitive).");
isPalindrome = in.nextLine();
int length = isPalindrome.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + isPalindrome.charAt(i);
if (isPalindrome.equals(reverse))
System.out.println("The word that you have entered is a palindrome.");
else
System.out.println("The word that you have typed isn't a palindrome.");
char answer;
do {
aGame.play ();
System.out.print("\n Do you want to continue (y or n)?");
answer = keyboard.next().charAt(0);
} while (answer == 'y' || answer == 'Y');
}
}
Put your entire application within the loop. One easy way would be to default answer to y (and you can use Character.toUpperCase(char) to eliminate the or) and something like
PalindromeChecker aGame = new PalindromeChecker();
char answer = 'y';
while (Character.toUpperCase(answer) == 'Y') {
String isPalindrome, reverse = "";
Scanner in = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
// ... The rest of your code ...
aGame.play();
System.out.print("\n Do you want to continue (y or n)?");
answer = keyboard.next().charAt(0);
}
There is one more way to solve your problem:
Put your entire code in a infinite while loop like this while(true), on the last line of loop just before exiting from the loop, u can ask user if he/she wants to continue. If answer is yes, then use the code System.exit(0) to exit from the program or if you want to just break from the loop use break; in the if condition.
You can use below code to ask user for quit.
boolean quit = false;
Scanner scanner = null;
try {
do {
System.out.println("Do you want to quit? (true/false)\n");
scanner = new Scanner(System.in);
String input = scanner.nextLine();
quit = Boolean.parseBoolean(input);
} while (!quit);
} finally {
scanner.close();
}
import java.util.Scanner;
public class paliindrome {
public static void main(String[] args) {
String isPalindrome, reverse = "";
Scanner in = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
PalindromeChecker aGame = new PalindromeChecker();
for (;;) {// or while(true)
System.out.println(
" Please type a word and I'll figure out if it's a palindrome(The program is case sensitive).");
isPalindrome = in.nextLine();
int length = isPalindrome.length();
for (int i = length - 1; i >= 0; i--) {
reverse = reverse + isPalindrome.charAt(i);
}
if (isPalindrome.equals(reverse))
System.out.println("The word that you have entered is a palindrome.");
else
System.out.println("The word that you have typed isn't a palindrome.");
System.out.print("\n Do you want to continue (y or n)?");
char answer = keyboard.next().charAt(0);
if (answer != 'y' && answer != 'Y') {
break;
}else{
aGame.play ();
}
}
}
}
This question already has answers here:
Java do-while loop isn't working
(3 answers)
Closed 7 years ago.
I working on a project for my course. The program runs fine until it hits my end program I've been messing with it for about 2 hours when I thought I was already finished.
This is the code it's messing up on.
do {
System.out.println("Do you want to end program? (Enter n or y):");
endProgram = Input.next();
if(!endProgram.equals("y") || (!endProgram.equals("n"))){
System.out.println("Do you want to end program? (Enter n or y):");
}
if (endProgram.equalsIgnoreCase("n")){
endProgram = "n";
aui = true;
}
if (endProgram.equalsIgnoreCase("y")){
endProgram = "y";
aui = true;
}
} while(aui = false);
I tried messing with the else if then switched to if. Full code is
public static String endProgram = null;
public static void main(String[] args) {
String MUR = "--------------Monthly Use Report--------------";
int minutesAllowed;
int minutesUsed = 0;
int minutesOver;
double totalOwed;
double monthlyRate = 74.99;
double minOver = 0.20;
double realOwed;
boolean valid = false;
boolean over = false;
boolean aui = false;
Scanner Input = new Scanner(System.in);
System.out.println("Welcome to the Cell Phone Minutes Calculator.");
do {
do {
System.out.println("Please input the amount of minutes you were allowed to use per month.");
System.out.println("Please Enter a value between (200 - 800)");
minutesAllowed = Input.nextInt();
} while (minutesAllowed <= 199 || minutesAllowed >= 801);{
}
do{
try{
System.out.println("How many minutes were used during the previous month?");
minutesUsed = Input.nextInt();
if(minutesUsed <= 1){
System.out.println("--Invalid Input! Please use a positive number.--");
} else {
valid = true;
}
} catch(Exception e){
System.out.println("Invalid Input! Please try again.");
Input.next();
}
}while(!valid);
minutesOver = minutesAllowed - minutesUsed;
if(minutesAllowed >= minutesUsed){
System.out.println("You were not over your minutes for the month!");
} else {
System.out.println("You were over your minutes by "+ Math.abs(minutesOver));
over = true;
}
totalOwed = (Math.abs(minutesOver))*(minOver);
realOwed = totalOwed+monthlyRate;
System.out.println(MUR);
System.out.println("Minutes allowed were "+ minutesAllowed);
System.out.println("Minutes used were "+ minutesUsed);
if(over){
System.out.println("Minutes over were "+ Math.abs(minutesOver));
System.out.println("Total due is $"+ realOwed);
} else {
System.out.println("Total due is $"+ monthlyRate);
}
do {
System.out.println("Do you want to end program? (Enter n or y):");
endProgram = Input.next();
if(!endProgram.equals("y") || (!endProgram.equals("n"))){
System.out.println("Do you want to end program? (Enter n or y):");
}
if (endProgram.equalsIgnoreCase("n")){
endProgram = "n";
aui = true;
}
if (endProgram.equalsIgnoreCase("y")){
endProgram = "y";
aui = true;
}
} while(aui = false);
}while((endProgram.equalsIgnoreCase("n")) && (aui = false));
}
}
Sorry if the code is sloppy. When I run the Program it runs properly unless I put two improper user inputs. such as,
Program running//
--------------Monthly Use Report--------------
Minutes allowed were 450
Minutes used were 500
Minutes over were 50
Total due is $84.99
Do you want to end program? (Enter n or y):
g
Do you want to end program? (Enter n or y):
If I add Input.Next(); to nest if statement to
if(!endProgram.equals("y") || (!endProgram.equals("n"))){
System.out.println("Do you want to end program? (Enter n or y):");
endProgram = Input.next();
it displays it correctly. I tried messing with the massive do while loop that goes across the whole project. If anybody can help me it will be much appreciated. Sorry if this is confused I'll respond if you guys have any questions. Thanks in advance for any response and sorry for the inconveniences.
Replace
while (aui = false); //here you are assigning aui to false value
to
while (aui == false); //here you are comparing aui to false value
= is as assignment operator, == is comparison operator.
The best practise is to use boolean directly, not by comparing:
while (!aui);
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I want to give user a possibility to stop inputing new lines in my String array by entering the word "end". I checked out - it really inputs 'end' before the if statement, but for some reason this doesn't break the while cycle:
Scanner scan = new Scanner(System.in);
String[] str = new String[50];
int j=0;
int f = 0;
System.out.println("Input 'end' to see your previous input!");
while(f != -1)
{
the input goes well, but the if statement doesn't work completely
String choice = scan.nextLine();
if(choice == "end")
{
f = -1;
}
else
{
str[j] = choice;
j++;
}
}
Use
choice.equals("end") instead of ==
See here
Also see equalsIgnoreCase() method for string comparision