Not able to use Scanner String input in other class - java

I am working on a program that has two classes. Class 1 contains a constructor called "Probability" that takes three inputs: a String and two doubles. This code is shown below:
public Probability(String inputString, double inputDouble1, double inputDouble2) {
this.inputString = inputString;
this.inputDouble1 = inputDouble1;
this.inputDouble2 = inputDouble2;
}
There is also a modifier that has five conditionals depending on the String that is fed in (i.e. if this.inputString == "String1"...), with a catch for invalid inputs. Class 2 calls the "Probability" constructor multiple times to create probabilities I need for my program.
So here's my dilemma. There are five String inputs that I need to be able to enter based on whatever I'm doing. Before, I was going into my Class 2 code and changing all of the references to this String manually (the references were "String1", "String2", etc...). In other words, the code looked something like this:
Probability P1 = new Probability("String1", double1, double2);
This is obviously a pain when you have twenty references. So I wanted to use a Scanner to take user input in order to change all of the references at once when I run my Main. The user would enter String1 when prompted, and then the input would be set equal to a String variable. This is my new code, where double1 and double2 are previous Scanner user inputs:
Scanner scan = new Scanner(System.in);
System.out.print("Please enter a string: ");
String userInput = scan.nextLine();
Probability P1 = new Probability(userInput, double1, double2);
But this doesn't work. I get the error that I've set up in my catch in the Class 1 modifier that says the input doesn't match any of the strings in the conditionals. I have tried the inputs String1 and "String1". Does anyone have any ideas why this may be? I have no issues with the double inputs fed from Class 2 into the Class 1 modifier.

Yes my friend as other suggest you have to compare the two string using equals method not by using == operator which is for reference matching not content matching.

Related

Am trying to recall the output of line 8 but still having problems

am trying to refer back to line 8 but don't know how, sorry am new to Java.
I've tried many approaches but still hitting a wall, pls what should I do.
package Interview;
import java.util.Scanner;
public class Interview {
public static void main(String[] args) {
System.out.println("hello,please what is your name:");
System in = scanner(System.in);
String Input=in.nextLine();
System.out.println("well then welcome to startechz "+Input);
System.out.println("Are you a male or female:");
String Input=in.nextLine();
if (Input=male)
//recall outprint from line 8
System.out.println("once again, welcome mr"+Input of Line8);
else {
System.out.println("once again,welcome mrs"+Input of Line8);
}
}
there many syntax error on your code it would be better to use ide
change this
System in = scanner(System.in);
to
Scanner in = new Scanner(System.in);
you can not redefine same variable again you have to statement
that looks like this
String Input=in.nextLine();
to solve this either use this
String newInput=in.nextLine();
or just assign new value to the same variable (of course of course if you do not want to use the old one again) like that
Input=in.nextLine();
in java to compare value you use double = sign like
Input==male
single = are used to assign value like int value = 5;
you can use == with primitive type only it will work but for reference type it will not work as in your case you use String with is reference type
why it did not work with reference type cause it will compare the reference address (the address for the object in memory (to be accurate it not the physical address but think of it like that))
so use the equal method
like
if (Input.equals("male")) // you forget also to make male as string you forget the double quotations
Change
if (Input=male)
to
if(Input.equalsIgnoreCase("male")) // allows case independent compare
Use equals or equalsIgnoreCase to compare strings.

Why do I get wrong mathematical results when using scanner class and delimiters for getting a double in Java?

I am writing a program where I have to get a user input, saved as a double. The user must be able to put it using both ',' and '.' as a delimiter - however they want. I tried using useDelimiter which works only partially - it does indeed accept both values (e.g 4.5 and 4,5) but when I later use the entered value in a mathematical equation, I get wrong results - it seems to round the user input down to the closest integer and as an effect no matter whether I enter, 4 or 4.5 or 4,5 or 4.8 etc., I get the same result, which is actually only true to 4.
Does anyone happen to know why it doesn't work?
double protectiveResistor=0; //must be a double, required by my teacher
double voltage= 5;
System.out.println("Please provide the resistance.");
Scanner sc= new Scanner(System.in);
sc.useDelimiter("(\\p{javaWhitespace}|\\.|,)");
try
{
protectiveResistor=sc.nextDouble();
}
catch(InputMismatchException exception)
{
System.out.println("Wrong input!");
System.exit(1);
}
if (protectiveResistor<0){
System.err.println("Wrong input!");
System.exit(1);
}
double current = (double)voltage/protectiveResistor;
double power = (double)current*current*protectiveResistor;
Thank you!
The useDelimiter method is for telling the Scanner what character will separate the numbers from each other. It's not for specifying what character will be the decimal point. So with your code, if the user enters either 4.5 or 4,5, the Scanner will see that as two separate inputs, 4 and 5.
Unfortunately, the Scanner doesn't have the facility to let you specify two different characters as decimal separators. The only thing you can really do is scan the two numbers separately, then join them together into a decimal number afterwards. You will want to scan them as String values, so that you don't lose any zeroes after the decimal point.
What useDelimiter() does is split the input on the specified delimiter.
As an example, if you have the input of 4,5, the following code will print "4".
Scanner sc= new Scanner(System.in);
sc.useDelimiter(",");
System.out.println(sc.next())
If you also want to print the second part, after the ',', you need to add another line to get the next value, which would in this example print
"4
5":
Scanner sc= new Scanner(System.in);
sc.useDelimiter(",");
System.out.println(sc.next())
System.out.println(sc.next())
In your code you can do it like this:
Scanner sc= new Scanner(System.in);
sc.useDelimiter("(\\p{javaWhitespace}|\\.|,)");
try
{
String firstPart = "0";
String secondPart = "0";
if (sc.hasNext()) {
firstPart = sc.next();
}
if (sc.hasNext()) {
secondPart = sc.next();
}
protectiveResistor = Double.parseDouble(firstPart + "." + secondPart)
}
// Rest of your code here
What this code does is split the input on whitespace, '.' and ','. For a floating point value you expect one part before the decimal point and one after it. Therefore, you expect the scanner to have split the input in two parts. These two parts are assigned to two variables, firstPart and secondPart. In the last step, the two parts are brought together with the '.' as decimal point, as expected by Java and parsed back into a variable of type Double.

How to input number of variables in int form and then label them 1-20 automatically?

I am creating a java program that asks for a number of variables, what the user wants to name them, and then asks for the user to input an equation. The program then writes a program that asks for the variables defined by the user and then solves an equation using the formula the user defined.
I have this so far:
int variables;
String equation;
Scanner reader = new Scanner(System.in);
System.out.print("Enter the number of required variables for equation (at most 20 variables): ");
variables = reader.nextInt();
System.out.println("");
System.out.println("Assign letters or words to each variable: ");
I was thinking of making an if statement for each of the twenty possible variables, but that would be incredibly time consuming. I want my program to take the input number of variables, for example four, and automatically name them in the program "variable1", "variable2", etc. I also want to know how to take an input equation using the scanner and use that as a real equation in the program later on.
I was also thinking of somehow using the assigned names defined by the user as the classification of the variable. So if they had two variables and named the first one 'a' and the second 'b', the strings would be referenced as String a and String b, but yet again, I don't really know how to do that.
You can use an array of size 20,
int[] arr = new int[20];
and the read the integers.
for (int i = 0; i < 20; i++) arr[i] = reader.nextInt();
When you want to use these values in an equation:
int value = arr[0]*arr[1]/arr[2];
You can't use assigned values defined by the user to set variable names. This defeats the purpose of having variables; you won't know how to reference those variables in code, since the variables don't have a constant name.

Confusion with Scanners (Big Java Ex 6.3)

Currently reading Chapter 6 in my book. Where we introduce for loops and while loops.
Alright So basically The program example they have wants me to let the user to type in any amount of numbers until the user types in Q. Once the user types in Q, I need to get the max number and average.
I won't put the methods that actually do calculations since I named them pretty nicely, but the main is where my confusion lies.
By the way Heres a simple input output
Input
10
0
-1
Q
Output
Average = 3.0
Max = 10.0
My code
public class DataSet{
public static void main(String [] args)
{
DataAnalyze data = new DataAnalyze();
Scanner input = new Scanner(System.in);
Scanner inputTwo = new Scanner(System.in);
boolean done = false;
while(!done)
{
String result = input.next();
if (result.equalsIgnoreCase("Q"))
{
done = true;
}
else {
double x = inputTwo.nextDouble();
data.add(x);
}
}
System.out.println("Average = " + data.getAverage());
System.out.println("Max num = " + data.getMaximum());
}
}
I'm getting an error at double x = inputTwo.nextDouble();.
Heres my thought process.
Lets make a flag and keep looping asking the user for a number until we hit Q. Now my issue is that of course the number needs to be a double and the Q will be a string. So my attempt was to make two scanners
Heres how my understanding of scanner based on chapter two in my book.
Alright so import Scanner from java.util library so we can use this package. After that we have to create the scanner object. Say Scanner input = new Scanner(System.in);. Now the only thing left to do is actually ASK the user for input so we doing this by setting this to another variable (namely input here). The reason this is nice is that it allows us to set our Scanner to doubles and ints etc, when it comes as a default string ( via .nextDouble(), .nextInt());
So since I set result to a string, I was under the impression that I couldn't use the same Scanner object to get a double, so I made another Scanner Object named inputTwo, so that if the user doesn't put Q (i.e puts numbers) it will get those values.
How should I approach this? I feel like i'm not thinking of something very trivial and easy.
You are on the right path here, however you do not need two scanners to process the input. If the result is a number, cast it to a double using double x = Double.parseDouble(result) and remove the second scanner all together. Good Luck!

charAt method is returning an integer. Need to convert to int

I'm creating a method that will take the given input and set the value to "plate". I then proceed to use the charAt method and try to take the characters(letters/String) input and set it to a new value. But i'm told to set it to a char value. When I run aprint statement with it, the output is just a bunch of integers, or in my case (for the code i'm going to show) it outputs "195" when I put the license plate as abc 123. Also, the model doesn't do anything(or atleast isnt supposed to). If anyone could tell me what exactly i'm doing wrong it would be a great help.
Here is my code so far:
import java.util.Scanner;
public class CarRental {
public static String model;
public static String plate;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Car Model:");
model = input.nextLine();
System.out.println("License Plate: ");
plate = input.nextLine();
char one = plate.charAt(0);
char two = plate.charAt(1);
System.out.println(two + one);
}
}
To make my issue clear, what I'm hoping to do is, assign the actual letters I type into the input to a separate value. I'm using the charAt method and it is returning integers.
if anyone could offer a suggestion it would help alot!
Thanks,
Sully
the + operator treats 2 chars as ints, try
System.out.println("" + two + one);
You can just use
Character.toChars(X)
Where x is your number to convert to char and then display said chars once they've been converted.

Categories