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.
Related
In oder to check the value entered by the user AND to see what random number has been calculated, I want to let those numbers projected in the console (eclipse). But what sketches my astonishment?? the last two system.out.println's (right above invoermax.close())) do NOT appear in the console screen after I entered the number???? It's like java doesn't even read or notice these code lines, How come???
Here my code:
package Package1;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class test6KOPIE1 {
public static void main(String[] args)
{
Scanner Invoermax = new Scanner(System.in);
System.out.println("Under which number you want to guess");
int Invoer = Invoermax.nextInt();
int Hoogte = ThreadLocalRandom.current().nextInt(1,Invoermax.nextInt());
System.out.println("So a guess under max: " + Invoer);
System.out.println("The random number has become " + Hoogte);
Invoermax.close();
}
}
every time you call Scanner.nextInt() it will wait for input from you.
The problem is that you are calling it twice, replace:
int Hoogte = ThreadLocalRandom.current().nextInt(1,Invoermax.nextInt());
With the variable you already got:
int Hoogte = ThreadLocalRandom.current().nextInt(1,Invoer);
And BTW, usually in java you start field/variable name with lower case letter, so should be hoogte, inoverMax, inover etc.
You can do something like this.
// code
Scanner Invoermax = new Scanner(System.in);
System.out.println("Under which number you want to guess");
int Invoer = Invoermax.nextInt();
Invoermax.nextLine(); // reading empty space left
int Hoogte = ThreadLocalRandom.current().nextInt(1,Invoermax.nextInt());
// code
You have two scanner.nextInt() calls, so there are two input readings, two input waitings.
int Invoer = Invoermax.nextInt(); // the first input reading
int Hoogte = ThreadLocalRandom.current().nextInt(1,
Invoermax.nextInt()); // the second input reading
When you enter two int values in a console (any of the kind) you'll see your ending print rows.
If your design was to have a single input, then use cashed value for the second usage
int Invoer = Invoermax.nextInt(); // the first input reading
int Hoogte = ThreadLocalRandom.current().nextInt(1,
Invoer ); // use cashed value
import java.util.Scanner;
public class Tipping {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Please enter initial price followed by tip percentage: ");
double Price = s.nextDouble(); double TipRate = s.nextDouble();
double TipAmount;
TipAmount = (Price*TipRate)/100;
System.out.println("Tip amount: " + TipAmount);
System.out.print("Total price: " + (TipAmount + Price) +".");
}}
I always get the price on the first line and the tiprate on the other.
Judging by your wording, you don't like that when input is handled via the Scanner, pressing Enter on the first double value (The Price) it advances to the next line and waits for the second double value (The TipRate). First of all, the character "Enter" is essentially the system dependent new-line character, so the Scanner immediately splits the input when the enter key is pressed. Specifically, the Scanner uses the Character.isWhiteSpace(char ch); function to evaluate where to split the tokens.
It all depends on how you want your input handled. Sadly, without importing a Curses-esque library and using a custom command prompt, the "\n" character cannot be reversed. What you can do is write your input and separate it by a space, for example writing "23.4 12.3" will write the input in the same line and correctly break the line into the 2 tokens you want.
If it is purely for aesthetic reasons you could catch the token as a String, evaluate if the "\n" character exists within and ask the user to re-input the variables in a single line or, if the "\n" character doesn't exist, split the String on the " " character and then use the Double.valueOf(String str); function.
Beware not to use the (Scanner in).setDelimiter(String str) since that will avoid breaking the tokens on the "\n" character (If the str String is for example " ") and will only freeze your program until the user splits 2 inputs with the space character and then throw an InputMismatchException because 12.3\n12.3 32.3 would be "valid" input but the token "12.3\n12.3" can't be evaluated to a single Double variable.
Sure, avoid calling:
System.out.println()
As the name (somehow) indicates, that prints a whole "line"; ending with a line break.
So, either call System.out.print() multiple times; or better practice: call System.out.println() once, but give all the strings you wanted to be printed to that call.
And as I just saw your comment: you are calling println() - in the line before you call print()!
Given your comment: you have to understand how that scanner works. The scanner reads strings; and by default, line by line.
In other words: when you use nextDouble() then the scanner assumes that you will enter a string that represents a number - but that your input is "terminated" by the user pressing ENTER. In other words; those line breaks are inevitable!
So, simply deal with them like:
System.out.print("Please enter initial price: ");
double Price = s.nextDouble();
System.out.print("Please enter tip percentage: ");
double TipRate = s.nextDouble();
double TipAmount = (Price*TipRate)/100;
System.out.println("Tip amount: " + TipAmount + " results in Total price: " + (TipAmount + Price) +".");
Long story short: when using the console in/out like this; you can't prevent certain line breaks. Simply accept that, and don't get to much into perfectionism.
Use instead of System.out.println (which stands for print line) with System.out.print. The System.out.println will print an line break after the given string on the output stream.
You could also combine the print's with a single print line.
For example you could use this:
System.out.println(String.format("Tip amount: %f Total Price: %f", TipAmount, (TipAmount + Price)));
Update
Simple solution for the scanner problem would be to input the numbers in one line separated with a whitespace.
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
I know there is a similar question already asked, so let me apologize in advance. I am new to Java and before this, my only programming experience is QBasic.
So here is my dilemma: I need to accept 2 integer values and I would like to be able to enter both values on the same line, separated by a space (IE: Enter "45 60" and have x=45 and y=60).
From what I have seen, people are suggesting arrays, but I am weeks away from learning those... is there a simpler way to do it? We have gone over "for", "if/else", and "while" loops if that helps. I don't have any example code because I don't know where to start with this one.
I have the program working with 2 separate calls to the scanner... just trying to shorten/ clean up the code. Any ideas??
Thanks!
//UPDATE:
Here is the sample so far. As I post this, I am also reading the scanner doc.
And I don't expect you guys to do my homework for me. I'd never learn that way.
The println at the end it my way of checking that the values were stored properly.
public static void homework(){
Scanner hwScan = new Scanner(System.in);
System.out.println("Homework and Exam 1 weights? ");
int hwWeight = hwScan.nextInt();
int ex1Weight=hwScan.nextInt();
System.out.println(hwWeight+" "+ex1Weight);
}
Even simple scanner.nextInt() would work for you like below:
Scanner scanner = new Scanner(System.in);
int x = scanner.nextInt();
int y = scanner.nextInt();
System.out.println("x = " + x + " y = " + y);
Output:
1 2
x = 1 y = 2
If you only have to accept two integer numbers you could do something like this:
String input = System.console().readLine(); //"10 20"
//String input = "10 20";
String[] intsAsString = input.split(" ");
int a = Integer.parseInt(intsAsString[0];
int b = Integer.parseInt(intsAsString[1]);
intsAsString is an array, in simple terms, that means it stores n-strings in one variable. (Thats very simplistic, but since you look at arrays more closely later you will see what i mean).
Be sure to roughly understand each line, not necessarily what exactly the lines do but conceptually: Read data form Console, parse the line so you have the two Strings which represent the two ints, then parse each string to an int. Otherwise you will have a hard time in later on.
The following requisites are those for the program I'm currently having an issue with:
The program must be able to open any text file specified by the user, and analyze the frequency of verbal ticks in the text. Since there are many different kinds of verbal ticks (such as "like", "uh", "um", "you know", etc) the program must ask the user what ticks to look for. A user can enter multiple ticks, separated by commas.
The program should output:
the total number of tics found in the text
the density of tics (proportion of all words in the text that are tics)
the frequency of each of the verbal tics
the percentage that each tic represents out of all the total number of tics
My program is working very well, but what I basically need to do is that I must use separate methods for each component of the analysis. So I think the idea is that I need to split up the program in a few parts, which I have done by using the comments // because I'm basically having problems determining which type I should return, I know the last part (// public static void output(){)
should definitely be void because it returns nothing and only prints out.
public static void main(String[] args) throws FileNotFoundException {
double totalwords = 0; // double so density (totalwords/totalticks) returned can be double
int totalticks = 0;
System.out.println("What file would you like to open?");
Scanner sc = new Scanner(System.in);
String files = sc.nextLine();
Scanner input = new Scanner(new File(files));
// public static int[] initialise()
System.out.println("What words would you like to search for? (please separate with a comma)");
String ticks = sc.nextLine();
ticks = ticks.toLowerCase();
String[] keys = ticks.split(",");
int[] values = new int[keys.length];
// public static int[] processing(){?
for (int z=0; z<keys.length; z++){
values[z] = 0;
}
while (input.hasNext()){
String next = input.next();
totalwords++;
for (int x = 0; x<keys.length; x++){
if (next.toLowerCase().equals(keys[x])){
values[x]+=1;
}
}
}
for (Integer u : values) {
totalticks += u;
}
//public static void output(){
System.out.println("Total number of tics :"+totalticks);
System.out.printf("Density of tics (in percent): %.2f \n", ((totalticks/totalwords)*100));
System.out.println(".........Tick Breakdown.......");
for (int z = 0; z<keys.length; z++){
System.out.println(keys[z] + " / "+ values[z]+" occurences /" + (values[z]*100/totalticks) + "% of all tics");
}
}
Essentially the problem I'm having is the scope of the variables because Eclipse (my IDE) no longer recognizes the variables within each method once I get them out of comments - I know I need to use some static variables but would really like a hand as to how I could hook my program up together using methods.
Thanks a bunch,
M
You should do an object (class) decomposition. First ask the question "What objects do I have". (At a quick glance you might have "Text" and "Ticks" objects. You then want to see what methods you want to use for each object. For example in Text have countTicks(Ticks). Conotinue in this fashion to decompose your program.
First, please indent your code more consistently, with the first line of a block three spaces farther to the right, such as
for(...) {
//Do stuff
if(...) {
//Do stuff
}
}
It is hard to read what you've posted (luckily someone spruced it up for you!).
Consider re-writing your program from scratch, instead of trying to fix what you already have. Your current knowledge of the problem should allow you to recreate it pretty quickly. You will probably be able to cut and paste bits and pieces from your original code as well.
How about starting small, with something like
Scanner sc = getInputScannerFromUserInput();
private static final Scanner getInputScannerFromUserInput() {
System.out.println("What file would you like to open?");
return new Scanner(System.in);
}
and just go from there. Bit by bit. Good luck!