Issues with input from user [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have an input from user of the following form:
1234 abc def gfh
..
8789327 kjwd jwdn
stop
now if i use Scanner and in turn use
Scanner sc=new Scanner(System.in);
String t=sc.nextLine();
while(!t.equals("stop"))
{
int i=sc.nextInt();
int str=sc.nextLine();
t=sc.nextLine();
}
Is there some way by which i may get
i=1234
str="abc def gfh"
...
and so on...and stop when the user enters a stop
I want to accept the numerical values and strings separately...without using regex.
Also I want to stop taking input with keyword "stop".

First of all, you are doing nothing with the accepted input, just ignoring it to take next input.
Second, scanner.nextLine() returns you the next line read which is String. To get the tokens separately, you would need to split the string read to get them.
Third, you should check in your while, whether you have next input or not using scanner#hasNextLine, if its equal to true, then only you should read your input in your while loop.
If you want to read each token separately, you should better use Scanner#next method, which returns the next token read.
Also, you want to read integers and strings, so you also need to test, whether you are having an integer. You would need to use Scanner#hasNextInt method for that.
Ok, since you want to read integer and string separately on each line.
Here's what you can try: -
while (scanner.hasNextLine()) { // Check whether you have nextLine to read
String str = scanner.nextLine(); // Read the nextLine
if (str.equals("stop")) { // If line is "stop" break
break;
}
String[] tokens = str.split(" ", 1); // Split your string with limit 1
// This will give you 2 length array
int firstValue = Integer.parseInt(tokens[0]); // Get 1st integer value
String secondString = tokens[1]; // Get next string after integer value
}

You never change the value of t so the while condition will be always true unless the first line of your file is stop.

your code:
Scanner sc=new Scanner(System.in);
String t=sc.nextLine();
while(!t.equals("stop"))
{
int i=sc.nextInt();
int str=sc.nextLine();
t=sc.nextLine();
}
First of all int str=sc.nextLine(); is wrong as nextLine() returns string. According to me, what you can do is:
Scanner sc=new Scanner(System.in);
String t=sc.nextLine();
int i;
String str="";
while(!t.equals("stop"))
{
int index=t.indexOf(" ");
if(index==-1)
System.out.println("error");
else{
i=Integer.parseInt(t.substring(0,index));
str=t.substring(index+1);
}
t=sc.nextLine();
}
I hope it helps.

Related

Java How to Read Data From a String (stringstream equivalent) [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
Let's say I have a String (call it s) with the following format:
[String] [String] [double] [int]
for example,
"YES james 3.5 2"
I would like to read this data into separate variables (a String, a String, a double, and an int)
Note that I come from a C++ background. In C++, I would do something like the following:
std::istringstream iss{s}; // create a stream to the string
std::string first, second;
double third = 0.0;
int fourth = 0;
iss >> first >> second >> third >> fourth; // read data
In Java, I came up with the following code:
String[] sa = s.split(" ");
String first = sa[0], second = sa[1];
double third = Double.parseDouble(sa[2]);
int fourth = Integer.parseInt(sa[3]);
However, I will have to do this to many different inputs, so I would like to use the most efficient and fastest way of doing this.
Questions:
Is there any more efficient/faster way of doing this? Perhaps a cleaner way?
Try it like this. Scanner's constructor can take a string as a data source.
Scanner scan = new Scanner("12 34 55 88");
while (scan.hasNext()) {
System.out.println(scan.nextInt());
}
prints
12
34
55
88
As it has been mentioned in the comments, if this is coming from keyboard (or really from an input stream) you could use Scanner class to do so. However, from input sources other than keyboard, I will not use Scanner but some other method to parse strings. For example, if reading lines from a file, you may want to use a Reader instead. For this answer, I will assume the input source is the keyboard.
Using Scanner to get the input
Scanner scanner = new Scanner(System.in);
System.out.print("Provide your input: ");
String input = scanner.nextLine();
input.close();
Break the String into tokens
Here you have a few options. One is to break down the string into substring by splitting the input using white space as a delimeter:
String[] words = input.split("\\s");
If the order of these substrings is guaranteed, you can assign them directly to the variables (not the most elegant solution - but readable)
String first = words[0];
String second = words[1];
double third = words[2];
int fourth = words[3];
Alternatively, you can extract the substrings directly by using String#substring(int) and/or String#substring(int, int) methods and test whether or not the obtained substring is a number (double or int), or just simply a string.

Replace the character input by user [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Java program to find a character from a sentence and replace it with another character. If the character is not found in the string print "character not found".
Note: Replace only the first occurrence.
Sample input 1:
Enter the string:
java programming
Enter the character to be searched:
a
Enter the character to replace:
o
Sample output 1:
jova programming
Kindly suggest me how to take user input for the character to be replaced and replace the character.
In general to get a input from user you could a scanner class.
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter the character to be searched");
String characterToReplace = myObj.nextLine(); // Read user input
System.out.println("Enter the character to replace");
String replacementCharacter = myObj.nextLine();
Information on scanner class
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Other ways to read input from command line :
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
For replacing a character you could just string.replace method to perform the required operations.
You can achieve this by putting this code in a function:
Scanner readInput = new Scanner(System.in);
System.out.println("Enter the string to search:");
String search = readInput.nextLine();
System.out.println("Enter the character to be searched:");
String find = readInput.nextLine();
System.out.println("Enter the character to replace it with:");
String replace = readInput.nextLine();
if (search.contains(find)) {
return search.replaceFirst(find, replace);
} else {
return "Character not found";
}

Java Scanner get number from string [closed]

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.

How can I re-arrange my code to produce the output I want? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Please could you help me re-arrange my already working code to give me this output described in the bullet points underneath:
'Type your text' window appears
The user enters the text, for example 'hey'
The code prints out the text entered by the user (hey), underneath the code prints out the number of characters (3) and finally another scanner window 'Type your text' appears. So the program loops back to 2 and waits for another line to be typed.
This would look like this:
hey
3
another scanner for the text to be typed in
My code already works and calculates everything, i just ran out of ideas how to re-arrange it to make its output exactly what i want:
System.out.println("Type your text...");
Scanner sc = new Scanner(System.in);
System.out.println(sc.nextLine());
System.out.println(sc.nextLine().length());
System.out.println("Length of String: " + lengthOfString("hey"));
sc.close();
}
private static int lengthOfString(String string) {
int length = -1;
while (true) {
try {
string.charAt(++length);
} catch (StringIndexOutOfBoundsException exception) {
break;
}
}
return length;
}
I am a beginner and I have weak understanding of java so please be clear with your answers and all your answers will be much appreciated, thank you!
The main problem is that you are calling nextLine() twice when you only want to be calling it once. Instead of these two lines:
System.out.println(sc.nextLine());
System.out.println(sc.nextLine().length());
Use this:
String input = sc.nextLine();
System.out.println(input);
System.out.println(input.length());
Another problem is that you are closing sc. This will close the underlying stream (System.in), which you don't want to do. Finally, you need to invoke this code in a loop so that the process is repeated. You don't show the context for this code, but I'm assuming that it's in a method that is being called in a loop or is part of the body of a loop. In either case, it would be better to create a Scanner once and use it repeatedly, rather than creating and disposing of a Scanner for each transaction with the user.
while (true)
{
System.out.println("Type your text...");
String str = sc.nextLine();
System.out.println("Length of String: " + str.length());
}
Have removed unncessary complexity from your code,Try this code:
Scanner sc=new Scanner(System.in);
String s;
while(true) //have created infinite loop as you want to continuously take inputs,
{
System.out.println("Enter value:");
s=sc.next();
if(s.equals("quit")) //if enterd value is "quit" than it comes out of loop ,termination condition to come out
{
break;
}
System.out.println(""+s); //to Print string
System.out.println(""+s.length()); //to print Entered string's length
}
Try out this:
import java.util.Scanner;
public class CountingOccurences {
public static void main(String[] args) {
Scanner inp= new Scanner(System.in);
String str;
char ch;
int count=0;
System.out.println("Enter the string:");
str=inp.nextLine();
while(str.length()>0)
{
count++;
str.substring(count);
}
System.out.println("Length :"+count);
}
}
Use a loop, calling nextLine() twice reads two lines (and throws them away) and don't close your Scanner. System.in is a global, if you close() your Scanner that will close System.in and it will not reopen.
Scanner sc = new Scanner(System.in);
while(true) {
System.out.println("Type your text...");
// System.out.println(sc.nextLine()); // <-- thrown away!
// System.out.println(sc.nextLine().length()); // <-- Second next line call
String line = sc.nextLine();
System.out.println("Length of String: " + lengthOfString(line)); // <-- not "hey"
// sc.close();
}
Edit
Just read lengthOfString(String), let's fix that -
private static int lengthOfString(String string) {
return string.trim().length();
}

How do I ignore characters entered by the user via Scanner?

Im working right now on a program that can divide, add, ect, but, im also making it for others, so, the problems usually have letters as well. What code could I implement so that my program ignores characters, and just focuses on numbers?
import static java.lang.System.out;
import java.util.Scanner;
public class Trinomial {
public static void main(final String args[]) {
final Scanner first = new Scanner(System.in);
out.print("Enter the first number: ");
final int First = first.nextInt();
final Scanner second = new Scanner(System.in);
out.print("Enter the second number: ");
final int Second = second.nextInt();
final Scanner third = new Scanner(System.in);
out.print("Enter the third number: ");
final int Third = third.nextInt();
numFactors(First);
}
}
You can have your program check whether each character it looks at is a digit using Character.isDigit()
http://www.tutorialspoint.com/java/character_isdigit.htm
You probably also want to allow your math operators through, e.g.
if (Character.isDigit(input) || input == '+' ||
input == '-' || input == '/' || input == '*')
{
// Do something with input
}
If that's not what you're looking for, please improve your question to be more specific.
Firstly, you will have to use next() method from the scanner, as nextInt() will return an exception if the next token contains non-digit characters. This will read the token as a String. Then you can get rid of non-digit characters by, for example, creating an empty String (for performance reasons StringBuilder can be better, but that makes it more complex), looping through the original string and using the already mentioned isDigit() method to determine whether the character is a digit. If it is, add it to your new string. Once you have a string containing only digits, use Integer.parseInt(string) method to get the integer value.
I am not quite sure, why you initialise a new Scanner every time, I think you should be able to use the first one throughout your program.

Categories

Resources