i'm trying to read a line and then go into a if-statement. But after it have red the first input it just terminates.
I have no idea what's wrong, and I can't figure it out
import java.util.Scanner;
public class mainen {
public static void main(String[] args) {
Formler form = new Formler();
Scanner Sscan = new Scanner(System.in);
Scanner Dscan = new Scanner(System.in);
String input;
System.out.println("Formler: Molmassa");
input = Sscan.nextLine();
if(input == "molmassa" || input == "Molmassa"){
double m;
double M;
System.out.println("Massa: "); m = Dscan.nextDouble();
System.out.println("Molmassa: "); M = Dscan.nextDouble();
System.out.println(form.getMolmassa(m, M));
}
}
}
Change your if statement to:
if(input.equalsIgnoreCase("molmassa") ) { }
Then it should work as you expect. Remember always compare strings using equals() or equalsIgnoreCase() method. == compares object references not the actual values.
You need to replace the equals checks:
if(input == "molmassa" || input == "Molmassa"){
with the following;
if(input.equals("molmassa") || input.equals("Molmassa")){
The first checks if the Strings are the same object, whereas the second checks that they're the same value, which is what you need here.
The problem is in you if condition change it to
if(input.equalsIgnoreCase("molmassa) )
and every thing should work fine.
One more thing you don't need to have separate Scanner to take String and double input you can use one Scanner object for both the inputs.
if(input == "molmassa" || input == "Molmassa"){}
You should equal String object with equals method or equalsIgnoreCase method.
if(input.equalsIgnoreCase("Molmassa")){}
== is used for primitive equaling check.
Related
I'm trying to make my program validate between the use of two single characters that are input by the user, which must be A or M.
Here's my code I have thus far:
static char getCustomerType() {
System.out.println("Please enter the term for the Policy the client would like");
System.out.println("A for Annual or M for Monthly. Annual provides the user with a 10% discount");
String s = inputs.next();
while (s != 'A' && s != 'M') {
System.out.println("Incorrect, please try again");
s = inputs.next();
}
}
Netbeans however, does not like this stating the inputs.next is never used when I have set it to be used before the while statement?
It also doesn't like the while statement producing incompatible string type referencing boolean to string.
I assume this is because I have declared s as a String?
You can have single characeter input from user using below code assuming inputs is your scanner object:
char c = inputs.next(".").charAt(0);
and then you can compare it using != or .equals() or .equalsIgnoreCase()
why not write
while ( ("A".equalsIgnoreCase(s) || "M".equalsIgnoreCase(s)) == false)
I want to make my program loop until the user types in x instead of a number. I tried using a while statement but I do not know how to use it with multiple variables. Here is my code
public static void main(String[] args)
{
int denominatorOne = 1, numeratorOne = 1;
System.out.println("Welcome, type an \"x\" at any point to exit the program");
while (numeratorOne !=x)
{
Scanner in = new Scanner(System.in);
//Prompt the user for fraction one
System.out.print("Enter the first numerator (top number): ");
numeratorOne = in.nextInt();
System.out.print("Enter the first denominator (bottom number): ");
denominatorOne = in.nextInt();
}
}
The exact phrasing from my assignment is The program should run in loop and allow the user to exit with some special character input (e.g. x or X to exit)
First off, 'x' isn't a number and won't be accepted by nextInt or a comparison to 'x', you should trying checking to see if it has next int (in.hasNextInt()) and process depending. Besides the point, you can easily test two variables in a while loop. Assuming you set up the variables right to be chars:
do {
// scan code.
} while(!(numChar1.equals('x') && numChar2.equals('x')))
what you need to do is have a bool value that holds the loop and when have a if statement check for the keydown event in the loop
bool looping = true
while ( looping == true)
{
if (x button was pressed == true)
{looping = false
}
}
try changing it to
while(!numeratorOne.equals("x")){...}
You can just call the method over again in this case main();.
What I suggest however is to create a new method, in the method just checking the users input returning the input as a string. Then you can check the string in your main method, and if that's not the string you wanted then recall the method. Here's an example, please note I didn't use an IDE for this.
public String getMessage(){
Scanner input = System.in();
return input;
}
public void checkMessage(String wantedString){
if(!getMessage().equalsIgnoreCase(wantedString)){
System.out.println("Please retry");
checkMessage();
}
}
public static void main(String[] args){
checkMessage();
}
I'm new to the Java programming language and want to create a program that reads in three words using scanner class and lexicoggraphically order the three words doing this in the main method for example user enters Tom Harry Dick, answer should be Dick Harry and Tom.. I tried to use an if statement to compare the strings using java compareTo() but if statement wont return anything for me since the main method is void.
public class SortWords {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
String firstWord;
String secondWord;
String thirdWord;
System.out.println("Enter three words seperated by white space");
firstWord = userInput.next();
System.out.println(firstWord);
secondWord = userInput.next();
System.out.println(secondWord);
thirdWord = userInput.next();
System.out.println(thirdWord);
}
}
Then try to read as an array elements then sort that array
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
String[] strings = new String[3];
for (int i = 0; i < strings .length; i++)
{
System.out.println("Please enter name");
strings [i] = input.next();
}
}
Arrays.sort(strings);
"I tried to use an if statement to compare the strings using java compareTo() but if statement wont return anything for me since the main method is void."
This is incorrect.
First, we do not say an if statement 'returns anything', we say that it chooses to either execute its statement block or not (the one enclosed by { }) based on whether its condition (enclosed by ( )) evaluates to true or false. (Similar idea when else and else if are thrown in)
Second, this is not effected by the return type of the method it's in, since it has nothing to do with return.
You should use print and println statements to print out the results of your comparisons of the three strings, since this is the main method and there is no higher method to return to.
I'm trying to ask the user to enter a character ("y"/"n") and check whether or not that was the right answer. I'm getting the following error: "incomparable types: java.util.Scanner and java.lang.String"
Scanner userInput = new Scanner(System.in);
System.out.printf("Is this word spelled correctly?: %s", wordToCheck);
rightCheck(userInput);
public boolean rightCheck(Scanner usersAnswer)
{
if(usersAnswer == "y")
{
//"Correct!"
//Increment User's Score
}
else
{
//"Incorrect"
//Decrement User's Score
}
}
Yes, because a scanner is a way of getting input rather than the value itself. You want to fetch the next value from the input, and then compare it. Something like this:
String answer = scanner.next();
if (answer.equals("y")) {
...
} else if (answer.equals("n")) {
...
}
Note that you should usually (including this case) not compare strings with ==, as that compares whether the two operands refer to the exact same string object - you're only interested in whether they refer to equal objects. (See this question for more details.)
I have modified your code, haven't tested it but it should work:
Scanner userInput = new Scanner(System.in);
System.out.println("Is this word spelled correctly?:" + wordToCheck);
rightCheck(userInput.next());//send the string rather than the scanner
public boolean rightCheck(String usersAnswer)//convert the parameter type to String
{
if(usersAnswer == "y")
{
//"Correct!"
//Increment User's Score
}
else
{
//"Incorrect"
//Decrement User's Score
}
}
I believe you should first get the String from Scanner (through next() maybe?). Then in your method, do not use "==" as a string comparator.
In order to make my program more streamlined (Without try and catch everywhere), I tried to create a seperate method just for getting data. I have one for Doubles, and Strings, as well.
For some reason, when I try to use this method, it is completely ignored, and passed by like a comment. Is there something I'm doing wrong?
public int inputint(){
Scanner sc = new Scanner (System.in);
int variable = 0;
boolean valid = true;
do{
try{
if (variable >= 0 && valid){
}
else if(valid){
System.out.print("Please enter positive values only: ");
}
valid = true;
}
catch (InputMismatchException e){
System.out.print("Please enter numerical values only: ");
sc = new Scanner(System.in);
valid = false;
}
}while (!valid || variable < 0);
return variable;
}
Well first of all, you're code is insanely hard to understand. (or could just be me I guess)
But if you look at your code
Scanner sc = new Scanner (System.in);
int variable = 0;
boolean valid = true;
You are creating the Scanner object, but nowhere in the method are you actually using it.
The next few lines,
if (variable >= 0 && valid){
}
both of those conditions are met. So with nothing in the brackets, no code is executed. So from there, it just returns the value of the variable, which is 0.
So you need to actually use your Scanner class to grab an integer. Which I believe, though I'm not sure, the method for that is
Scanner.nextInt();
Edit: From the JavaDocs http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html
You can simply use
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
to read an integer from the Scanner.
Your variable variable is assigned 0 and the valid variable is assigned true. Consequently, the while (!valid || variable < 0) expression will always be evaluated to false and the do-while loop will only be executed once (without the Scanner ever being created).
I guess that you would like to read the user input before checking the variable variable, so you would probably like create the Scanner and read the input before doing the if (variable >= 0 && valid) check.
Side note, you can probably skip the valid variable and use variable =sc.nextInt();, compare with #Austin's answer.