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.
Related
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. :)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
The string is, for example "r1" and I need the 1 in an int form
Scanner sc = new Scanner("r1");
int result = sc.nextInt(); // should be 1
compiles correctly but has a runtime error, should I be using the delimiter? Im unsure what the delimiter does.
Well, there's a few options. Since you literally want to skip the "r" then read the number, you could use Scanner#skip. For example, to skip all non-digits then read the number:
Scanner sc = new Scanner("r1");
sc.skip("[^0-9]*");
int n = sc.nextInt();
That will also work if there are no leading non-digits.
Another option is to use non-digits as delimiters, as you mentioned. For example:
Scanner sc = new Scanner("x1 r2kk3 4 x56y 7g");
sc.useDelimiter("[^0-9]+"); // note we use + not *
while (sc.hasNextInt())
System.out.println(sc.nextInt());
Outputs the six numbers: 1, 2, 3, 4, 56, 7.
And yet another option, depending on the nature of your input, is to pre-process the string by replacing all non-digits with whitespace ahead of time, then using a scanner in its default configuration, e.g.:
String input = "r1";
input = input.replaceAll("[^0-9]+", " ");
And, of course, you could always just pre-process the string to remove the first character if you know it's in that form, then use the scanner (or just Integer#parseInt):
String input = "r1";
input = input.substring(1);
What you do depends on what's most appropriate for your input. Replace "non-digit" with whatever it is exactly that you want to skip.
By the way I believe a light scolding is in order for this:
Im unsure what the delimiter does.
The documentation for Scanner explains this quite clearly in the intro text, and even shows an example.
Additionally, the definition of the word "delimiter" itself is readily available.
There are some fundamental mistakes here.
First, you say:
One = sc.nextInt("r1");
compiles correctly ...
No it doesn't. If sc is really a java.util.Scanner, then there is no Scanner.nextInt(String) method, so that cannot compile.
The second problem is that the hasNextXXX and nextXXX methods do not parse their arguments. They parse the characters in the scanner's input source.
The third problem is that Scanner doesn't provide a single method that does what you are (apparently) trying to do.
If you have a String s that contains the value "r1", then you don't need a Scanner at all. What you need to do us something like this:
String s = ...
int i = Integer.parseInt(s.substring(1));
or maybe something this:
Matcher m = Pattern.compile("r(\\d+)").matcher(s);
if (m.matches()) {
int i = Integer.parseInt(m.group(1));
}
... which checks that the field is in the expected format before extracting the number.
On the other hand if you are really trying to read the string from a scanner them, you could do something like this:
String s = sc.next();
and then extract the number as above.
If the formatting is the same for all your input where the last char is the value you could use this:
String s = sc.nextLine()
Int i = Integer.parseInt(s.charAt(s.length() -1));
Else you could for instance make the string a char Array, iterate trough it and check whether each char is a number.
Im trying to write a program that takes a string of user inputs such as (5,6,7,8) and converts it to an arrayList of integers e.g. {5,6,7,8}. I'm having trouble figuring out my for loop. Any help would be awesome.
String userString = "";
ArrayList<Integer> userInts = new ArrayList<Integer>();
System.out.println("Enter integers seperated by commas.");
userString = in.nextLine();
for (int i = 0; i < userString.length(); i++) {
userInts.add(new Integer(in.nextInt()));
}
If your list consists of single-digit numbers, your approach could work, except you need to figure out how many digits there are in the string before allocating the result array.
If you are looking to process numbers with multiple digits, use String.split on the comma first. This would tell you how many numbers you need to allocate. After than go through the array of strings, and parse each number using Integer.parseInt method.
Note: I am intentionally not showing any code so that you wouldn't miss any fun coding this independently. It looks like you've got enough knowledge to complete this assignment by reading through the documentation.
Lets look at the lines:
String userString = ""
int[] userInt = new int[userString.length()];
At this point in time userString.length() = 0 since it doesnt contain anything so this is the same as writing int[] userInt = new int[0] your instantiating an array that cant hold anything.
Also this is an array not an arrayList. An arrayList would look like
ArrayList<Integer> myList = new ArrayList()<Integer>;
I'm assuming the in is for a Scanner.
I don't see a condition to stop. I'll assume you want to keep doing this as long as you are happy.
List<Integer> arr = new ArrayList<Integer>();
while(in.hasNext())
arr.add(in.nextInt());
And, say you know that you will get 10 numbers..
int count = 10;
while(count-- > 0)
arr.add(in.nextInt());
Might I suggest a different input format? The first line of input will consist of an integer N. The next line contains N space separated integers.
5
3 20 602 3 1
The code for accepting this input in trivial, and you can use java.util.Scanner#nextInt() method to ensure you only read valid integer values.
This approach has the added benefit of validate the input as it is entered, rather than accepting a String and having to validate and parse it. The String approach presents so many edge cases which need to be handled.
I'm trying to make an undirected graph with some of the nodes (not all, unlike my example) being connected to one another. So my input format will look like
3
1:2,3
2:1,3
3:1,2
Meaning there's three nodes in all, and 1 is connected to 2 and 3, 2 is connected to 1 and 3 and so on.
However, I cannot understand how to take the input in a meaningful way. Here's what I've got so far.
public Graph createGraph() {
Scanner scan = new Scanner(System.in).useDelimiter("[:|,|\\n]");
int graphSize = scan.nextInt();
System.out.println(graphSize);
for (int i = 0; i < graphSize; i++) {
while (!scan.hasNext("\\n")) {
System.out.println("Scanned: " + scan.nextInt());
}
}
return new Graph(graphSize);
}
Can my
while (!scan.hasNext("\\n"))
see the newline character when I'm using a delimiter on it?
In my opinion, you shouldn't be using those delimiters if they are meaningful tokens. In the second line for example, the first integer doesn't have the same meaning as the others, so the : is meaningful and should be scanned, even if only to be discarded later. , however doesn't change the meaning of the tokens that are separated by it, so it's safe to use as a delimiter : you can grab integers as long as they are delimited by ,, they still have the same meaning.
So in conclusion, I would use , as a delimiter and check manually for \nand : so I can adapt my code behaviour when I encounter them.
yup, scanner can definitely detect new line. infact you dont even have to explicitly specify it. just use
scan.hasNextLine()
which essentially keeps going as long as there are lines in your input
Edit
Why dont you read everything first and then use your for loop?
Alright I figured it out. It's not the prettiest code I've ever written, but it gets the job done.
public Graph createGraph() {
Scanner scan = new Scanner(System.in);
number = scan.nextLine();
graphSize = Integer.valueOf(number);
System.out.println(graphSize);
for (int i = 0; i < graphSize; i++) {
number = scan.nextLine();
Scanner reader = new Scanner(number).useDelimiter(",|:");
while (reader.hasNextByte()) {
System.out.println("Scanned: " + reader.nextInt());
}
}
return new Graph(graphSize);
}
I want to be able to choose an array index using input.
Object stud1 [][] = {
{1,2,3},
{"favorite food: ","pet name: ","bday: "}
}
System.out.println("how many inputs?");
If a user inputs 1, then "favorite food:" will prompt the user and if the user inputs 2, then
both "favorite food: " and "pet name: " will prompt the user and so on.
After the user completes the prompt input, this will display:
favorite food: chicken
pet: doge
birthday: december 25,1994
/////////////////////////////////////////my code/////////////////////////////////////////////
This question is similar to my other question, I just could not find the right answer for my question because I think it was confusing and not specific enough.
It's kind of working already but the problem is that when I input 1 then it still outputs everything. I only want it to output everything if the user inputs 3 which is the number of indexes in my array.
I am not pretty good with arrays yet especially multi array, I'm still experimenting.
String ctr1;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter How Many Inputs: ");
int num1 = Integer.parseInt(in.readLine());
if (num1 <= stud1.length) {
for (int x = 1; x<stud1.length;x++){
for (int i = 0; i<stud1[x].length;){
/*System.out.print("Enter Value #" + x++ +":");
ctr1 =Integer.parseInt(in.readLine());
i++;*/
System.out.println(stud1[x][i]);
ctr1 =in.readLine();
i++;
}
}
I'm sorry but I don't think this is a good example for multidimensional arrays... nothing is really being done with the first element here: {1,2,3}.
To answer the specific question of why all 3 elements are printing out when the user only inputs a "1", it is because that value is being read into the variable num1, but num1 is not used anywhere in the loop that prints the output. If you want the input to control how many values are printed, then num1 needs to be used in the for loop's test expression (the middle phrase in the parentheses). I think a good first step is to change your inner loop like so:
for (int i = 0; i<num1;i++){
System.out.println(stud1[1][i]);
ctr1 =in.readLine();
}
Also note that the i++ is moved inside the parentheses for the for loop. That's really where it belongs, if you're using for.
Hope this helps!