How to print a string with an int - java

I am trying to get this code to run and basically solve an equation. So, I asked the user to write an equation. It looked like this:
System.out.println("Write an equation and I will solve for x.");
int answer = in.nextLine();
But I can't get the user to write a string and an int. Do I need to say String answer or int answer?

An int is used when you want the user to enter a number, but here you're looking for a combination of numbers and other characters, so you will need to use a string. When you have the equation stored in a string, you can use other methods to split up the equation into something solvable, then set int answer to whatever the answer comes out to be.

On a simpler side, String will be required input from the user, User will enter the equation.
Then comes the complex part of solving/computing the equation.
1.) create your own parser to pass operands/operator.
2.) Provide a equation with values to some API, you can make use of MVEL or ANTLR

Here's a little program that demonstrates one way to get the equation and divide into numeric / non-numeric values provided the equation input is space delimited. You can then determine what the non-numeric values are and proceed from there.
import java.util.Scanner;
public class SolveX{
public static void main(String[] a){
Scanner in = new Scanner(System.in);
System.out.println("Write an equation and I will solve for x.");
String input = "";
while( in.hasNext() ){
input = in.next();
try{
double d = Double.parseDouble(input);
System.out.println("Double found at: " + input);
// Do what you need to with the numeric value
}
catch(NumberFormatException nfe){
System.out.println("No double found at: " + input);
// Do what you need to with the non numeric value
}
}
}//end main
}//end SolveX class

Related

User input. Should i convert string to int or get int as input?

I haven't found answer to my question from anywhere else so now i need to ask it here.
My small java program asks user to input a number.
What is the good practice to do it? Should it read string and convert it to int or should it read int?
I need to do exception handling anyway to check the value.
So does it matter and what is the proper way to do it?
in my case, this works for me. I read the string and convert it to int. Next is an example
public class Test{
public static void main(String arg[]){
try{
int number = Integer.parseInt(arg[0]);
System.out.println("Your number is " + number);
}catch(NumberFormatException e){
System.out.println("Enter a number");
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Enter a number");
}
}
}
Every thing your program reads from standard input stream or file, is by default buffer of characters, and we can see them as String.
So if you need other type, you should parse that string and convert to your desired type.
but some functions do that conversion and you can use from them.
like :
Scanner myInput = new Scanner( System.in );
System.out.print( "Enter first integer: " );
int a = myInput.nextInt();
for more information you can see content of this page:
https://www.tutorialspoint.com/read-integers-from-console-in-java

Want to programm calculator, want to change String into real operator

I want to code a simple calculator and already got some code. But now I want to change the String I got there into an Operator. For example:
My input is: "1,5 - 1,1 + 3,2 ="
Now I have a double array and a String array.
So after that I want to put it together, so it calculates this complete task.
double result = double[0] String[0] double[1] ....
I hope you can help there, and I apologize for my grammar etc., english is not my main language.
import java.util.*;
public class calculator
{
public static void main(String[] args)
{
int a = 0;
int b = 0;
double[] zahl;
zahl = new double[10];
double ergebnis;
String[] zeichen;
zeichen = new String[10];
Scanner input = new Scanner (System.in);
while (input.hasNext())
{
if (input.hasNextDouble())
{
zahl[a] = input.nextDouble();
a++;
}
else if (input.hasNext())
{
zeichen[b] = input.next();
if (zeichen.equals ("=")) break;
b++;
}
}
input.close();
}
}
If I type in: "1,5 + 2,3 * 4,2 =" I want to get the result with point before line and without .math
What you want to do is parse a single String and convert it into a mathematical expression, which you then want to resolve and output the result. For that, you need to define a "language" and effectively write an interpreter. This is not trivial, specifically if you want to expand your syntax with bracketing and thelike.
The primary question you have to answer is, whether you want to use a solution (because you are not the first person to attempt this) or if you want to actually write this yourself.
There are "simple" solutions, for example, you could instantiate a javascript engine in Java and input your string, but that would allow much more, and maybe even things you don't want. Or you could use a library which already does this. This Thread already answered a similar question with multiple interesting answers:
How to evaluate a math expression given in string form?
Otherwise, you might be in for a surprise, concerning the amount of work, you are getting yourself into. :)

Java input/output confusion

I am writing a program and I need to input a value for index, but the index should be composite, e.g 44GH.
My question is, how to make the program to do not crash when I ask the user to input it and then I want to display it?
I have been looking for answer in the site, but they are only for integer or string type.
If anyone can help, would be really appreciated.
Scanner s input = new Scanner(System.in);
private ArrayList<Product> productList;
System.out.println("Enter the product");
String product = s.nextLine();
System.out.println("Input code for your product e.g F7PP");
String code = s.nextLine();
}
public void deleteProduct(){
System.out.println("Enter the code of your product that you want to delete ");
String removed = input.nextLine();
if (productList.isEmpty()) {
System.out.println("There are no products for removing");
} else {
String aString = input.next();
productList.remove(aString);
}
}
Remove all non digits char before casting to integer:
String numbersOnly= aString.replaceAll("[^0-9]", "");
Integer result = Integer.parseInt(numbersOnly);
The best way to do it is to create some RegEx that could solve this problem, and you test if your input matches your RegExp. Here's a good website to test RegExp : Debuggex
Then, when you know how to extract the Integer part, you parse it.
I think the OP wants to print out a string just but correct me if I am wrong. So,
Scanner input = new Scanner(System.in);
String aString = input.nextLine(); // FFR55 or something is expected
System.out.println(aString);
Then obviously you can use:
aString.replaceAll();
Integer.parseInt();
To modify the output but from what I gather, the output is expected to be something like FFR55.
Try making the code split the two parts:
int numbers = Integer.parseInt(string.replaceAll("[^0-9]", ""));
String chars = string.replaceAll("[0-9]", "").toUpperCase();
int char0Index = ((int) chars.charAt(0)) - 65;
int char1Index = ((int) chars.charAt(1)) - 65;
This code makes a variable numbers, holding the index of the number part of the input string, as well as char0Index and char1Index, holding the value of the two characters from 0-25.
You can add the two characters, or use the characters for rows and numbers for columns, or whatever you need.

Need help splitting a string into two separate integers for processing

I am working on some data structures in java and I am a little stuck on how to split this string into two integers. Basically the user will enter a string like '1200:10'. I used indexOf to check if there is a : present, but now I need to take the number before the colon and set it to val and set the other number to rad. I think I should be using the substring or parseInt methods, but am unsure. The code below can also be viewed at http://pastebin.com/pJH76QBb
import java.util.Scanner; // Needed for accepting input
public class ProjectOneAndreD
{
public static void main(String[] args)
{
String input1;
char coln = ':';
int val=0, rad=0, answer=0, check1=0;
Scanner keyboard = new Scanner(System.in); //creates new scanner class
do
{
System.out.println("****************************************************");
System.out.println(" This is Project 1. Enjoy! "); //title
System.out.println("****************************************************\n\n");
System.out.println("Enter a number, : and then the radix, followed by the Enter key.");
System.out.println("INPUT EXAMPLE: 160:2 {ENTER} "); //example
System.out.print("INPUT: "); //prompts user input.
input1 = keyboard.nextLine(); //assigns input to string input1
check1=input1.indexOf(coln);
if(check1==-1)
{
System.out.println("I think you forgot the ':'.");
}
else
{
System.out.println("found ':'");
}
}while(check1==-1);
}
}
Substring would work, but I would recommend looking into String.split.
The split command will make an array of Strings, which you can then use parseInt to get the integer value of.
String.split takes a regex string, so you may not want to just throw in any string in it.
Try something like this:
"Your|String".split("\\|");, where | is the character that splits the two portions of the string.
The two backslashes will tell Java you want that exact character, not the regex interpretation of |. This only really matters for some characters, but it's safer.
Source: http://www.rgagnon.com/javadetails/java-0438.html
Hopefully this gets you started.
make this
if(check1==-1)
{
System.out.println("I think you forgot the ':'.");
}
else
{
String numbers [] = input1.split(":"); //if the user enter 1123:2342 this method
//will
// return array of String which contains two elements numbers[0] = "1123" and numbers[1]="2342"
System.out.print("first number = "+ numbers[0]);
System.out.print("Second number = "+ numbers[1]);
}
You knew where : is occurs using indexOf. Let's say string length is n and the : occurred at index i. Then ask for substring(int beginIndex, int endIndex) from 0 to i-1 and i+1 to n-1. Even simpler is to use String::split

.useDelimiter to parse commas but not negative sign

So I have looked at a couple of related questions, but still can't seem to find my answer (I guess because it's specific). I'm trying to use the Scanner.useDelimiter method in Java and I can't get it to work properly... here is my dilemma...
We are supposed to write a program that takes a X, Y coordinate and calculates the distance between the two points. Obviously, one solution is to scan for each x and y coordinate separately, but this is sloppy to me. My plan is to ask the user to input the coordinate as "x, y" and then grab the integers using the Scanner.nextInt() method. However, I have to find a way to ignore the "," and of course, I can do that with the useDelimiter method.
According to other threads, I have to understand regex (not there yet) to put in the useDelimiter method and I've got it to ignore the commas, HOWEVER, there is a possibility that a user inputs a negative number as a coordinate (which is technically correct). How do I get useDelimiter to ignore the comma, but still recognize the negative sign?
This is my first time on here, here is my code:
import java.util.Scanner;
import java.text.DecimalFormat;
public class PointDistanceXY
{
public static void main(String[] args)
{
int xCoordinate1, yCoordinate1, xCoordinate2, yCoordinate2;
double distance;
// Creation of the scanner and decimal format objects
Scanner myScan = new Scanner(System.in);
DecimalFormat decimal = new DecimalFormat ("0.##");
myScan.useDelimiter("\\s*,?\\s*");
System.out.println("This application will find the distance between two points you specify.");
System.out.println();
System.out.print("Enter your first coordinate (format is \"x, y\"): ");
xCoordinate1 = myScan.nextInt();
yCoordinate1 = myScan.nextInt();
System.out.print("Enter your second coordinate (format is \"x, y\"): ");
xCoordinate2 = myScan.nextInt();
yCoordinate2 = myScan.nextInt();
System.out.println();
// Formula to calculate the distance between two points
distance = Math.sqrt(Math.pow((xCoordinate2 - xCoordinate1), 2) + Math.pow((yCoordinate2 - yCoordinate1), 2));
// Output of data
System.out.println("The distance between the two points specified is: " + decimal.format(distance));
System.out.println();
}
}
Thanks for your help and I look forward to helping other people down the line!
I think it would be easier (and more conventional for the command line type of programs) to just ask for x and y separately
Example:
Scanner myScan = new Scanner(System.in);
System.out.print("Enter your first x coordinate: ");
xCoordinate1 = Integer.parseInt(myScan.nextLine());
yCoordinate1 = Integer.parseInt(myScan.nextLine());
However if you insist on doing both at the same time and using a delimeter you could try using the return line as a delimeter instead of the ", " because you would have to delimit it twice remember, once after x and then again after y. But that sort of brings you back to the same result. The problem is that you need to delimit it twice if you want to use a delimeter and take it in at the same time. I'd suggest taking a look at the .split function of a string instead.
Another approach would be to use the .split(", "); function where ", " is your delimiter.
Example:
Scanner myScan = new Scanner(System.in);
System.out.print("Enter your first coordinate (format is \"x, y\"): ");
String input = myScan.nextLine();
xCoordinate1 = Integer.parseInt(input.split(", ")[0]);
yCoordinate1 = Integer.parseInt(input.split(", ")[1]);
Hope this helps, Enjoy.

Categories

Resources