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 6 years ago.
Improve this question
help me finding a way to read from user 3 integers in one line and then treat each saparately as a,b,c .. please be quick because i had tried reading a whole line but i want to deal with each integer in later statement
import java.util.Scanner;
public class MHDKhaledTotonji_301300797 {
public static void main(String[] args){
Scanner input=new Scanner(System.in);
int M,a,b,c;
System.out.println("Please, insert the normal dose in ml");
M = input.nextLine();
}
}
Scanner in = new Scanner(System.in);
int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
takes: 1 2 3
nextLine() returns a String, so M should be defined as a String.
Java naming conventions generally state that variables should start with lowercase letter, so M should be m.
As for the task of getting 3 integers from the user on one line, you have multiple choices, and it depends on how strict you want to be and how much error handling you need.
For very easy solution, with no error handling (kills program on bad input), Scanner is the answer. Error handling can be added, but is cumbersome.
Scanner in = new Scanner(System.in);
System.out.println("Please, insert the normal dose in ml");
int a = input.nextInt();
int b = input.nextInt();
int c = input.nextInt();
Another solution might be to read the line, like you are trying to do, then split the line and parse the values. A little more code, but forces user to enter all 3 on one line, which solution #1 doesn't.
Scanner in = new Scanner(System.in);
System.out.println("Please, insert the normal dose in ml");
String line = input.nextLine();
String[] values = line.split(" ");
int a = Integer.parseInt(values[0]);
int b = Integer.parseInt(values[1]);
int c = Integer.parseInt(values[2]);
For better control of the line from the user, a regular expression can be used. Here it is with full error handling.
Scanner in = new Scanner(System.in);
Pattern p = Pattern.compile("\\s*(\\d+)\\s+(\\d+)\\s+(\\d+)\\s*");
int a = 0, b = 0, c = 0;
for (;;) {
System.out.println("Please, insert the normal dose in ml");
String line = input.nextLine();
Matcher m = p.matcher(line);
if (m.matches())
try {
a = Integer.parseInt(m.group(1));
b = Integer.parseInt(m.group(2));
c = Integer.parseInt(m.group(3));
break;
} catch (Exception e) {/*fall thru to print error message*/}
System.out.println("** Bad input. Type 3 numbers on one line, separated by space");
}
use input.nextInt() instead of input.nextLine(). Also this is wrong because input.nextLine() returns String and you should parse to integer.
Simple change your code to:
M = input.nextInt();
a = input.nextInt();
b = input.nextInt();
c = input.nextInt();
Stick in mind that input.nextInt() ignores every white space including line feeds so you don't need to worry about reading from the same or different lines.
Related
While solving a problem at hacker-rank I am facing the issue that scanner/bufferedreader is unable to read the last. As the input provided by them is like
10
abcdefghijk
2
R 1 2
W 3 4
So both scanner/bufferedreader is unable to read the last line. If the input is like then the code seems to work fine.
10
abcdefghijk
2
R 1 2
W 3 4
(End of Input)
public class ScannerTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int len = input.nextInt();
input.nextLine();
String inputString = input.nextLine();
int qc = input.nextInt();
input.nextLine();
System.out.println();
System.out.println(len + inputString + qc);
for(int i=0;i<qc;i++){
String l = input.next();
int le = input.nextInt();
int ri = input.nextInt();
input.nextLine();
System.out.println(l+le+ri);
}
input.close();
}
}
Here is the sample code which I am using. I know that we need a \r or\n at the end of line to readline from scanner / bufferedreader. But can anyone provide a solution to this issue as input comes from system that is predefined.
BufferedReader would read the last line even if it does not end in a line break. System.in is the culprit, that does its own line buffering.
A native system thing: suppose you pressed a couple of backspaces to change the last number...
The problem is here:
input.nextLine();
String inputString = input.nextLine();
You are consuming a line to just throw it away.
The other thing is: especially when dealing with standard libraries - don't assume that something is broken/doesn't work. In 99,999% of all case the problem is something within your code.
I'm still new to programming and have been trying to learn how to fix this code
im trying to input and record a username and password depending on how many users I input, but when i run it it prints out the "whats your username?" question twice before i'm allowed to give a response. I've narrowed the problem down to the user[i]=in.nextLine() part
public static void main(String[] args){
System.out.println("How many Users?");
Scanner in = new Scanner(System.in);
int x = in.nextInt();
String[] user;
user = new String[x];
String[] pass;
pass = new String[x];
for(int i=0; i<x;i++){
System.out.println("What is your Username?");
user[i] = in.nextLine();
Add in.nextLine(); after int x = in.nextInt(); to consume and ignore the new line character left over by call to nextInt()
When you use a scanner it consume only the bytes needed for the requested token.
If the first call is to get the number of users (nextInt) it reads only the minimum number of digits composing it and leave the \n (new line character) not consuming it.
Because you are asking for the next line on the loop the first nextLine use only the \n.
So the best solution to make your code correct is to add a
in.nextLine();
before the for loop.
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 9 years ago.
Improve this question
public static Student[] getInput(Scanner scanner)throws FileNotFoundException
{
//change the array size by reading the input file
Student[] classList=new Student[10];
int i;
int numberOfStudents = scanner.nextInt();
while(scanner.hasNext())
{
while(numberOfStudents > classList.length)
{
//enlargeList(classList[i]);
}
for(i = 0; i <= classList.length; i++){
String studentId = scanner.nextLine();
int mark = scanner.nextInt();
classList[i] = new Student(studentId, mark);
}
}
return classList;
}
public static void main(String[] args)
{
if (args.length!=1)
{
System.out.println("Usage GradeManager inputFileName");
System.exit(1);
}
Scanner inFile=null;
try{
//do the whole try block in the lab
String fileName = args[0];
//Open a file with FileName and creaste a scanner using it
inFile = new Scanner(new File(fileName));
Student[] classList=getInput(inFile);
}
catch (FileNotFoundException fe)
{
fe.printStackTrace();
}catch(Exception e)
{
e.printStackTrace();
}finally{
if(inFile!=null)
inFile.close();
}
}
So I am trying read from a textfile that is as follows:
9
V0012345 98
V0023456 33
V0024615 51
V0089546 57
V0015348 61
V0054162 69
V0044532 87
V0031597 74
V0074615 78
First line is the number of students in the text file, all others are student number + their grade in the class. I'm trying to import these into the array classList[]. I am very new to java and object oriented stuff, so I'm sorry in advance if my code is garbage. I have omitted the enlargeList method as it works and I've tested it.
Thanks
String studentId = scanner.nextLine();
will read V0012345 98 and then
int mark = scanner.nextInt();
will read V0023456 33 and fail
try:
String line = scanner.nextLine();
//this will ignore empty lines
if(line.equals("")) continue;
String[] lineArray = line.split(" ");
String studentId = lineArray[0];
int mark = Integer.parseInt(lineArray[1]);
There are at least four problems I can see...
First, int numberOfStudents = scanner.nextInt(); won't consume the new line character, this means the next time you try and read something from the scanner, you may get the new line character (if you're reading text) or an exception of you're reading a numeric value.
Try adding scanner.nextLine() after it, for example...
int numberOfStudents = scanner.nextInt();
scanner.nextLine();
You're pre-initializing the array before you know the number of possible lines. This seems weird to me. You know ahead of time how many lines you will need to read, why not use it?
int numberOfStudents = scanner.nextInt();
scanner.nextLine();
Student[] classList = new Student[numberOfStudents];
Next, when reading the student data, you seem to be reading the entire line, the looking for an int value after it...
This would mean you are reading V0012345 98 using scanner.nextLine(), but the next call to scanner.nextInt() will encounter V0023456, which isn't a valid int value.
Instead, read the next line and create a new Scanner to parse it...
Scanner scanLine = new Scanner(line);
String studentId = scanLine.next();
int mark = scanLine.nextInt();
This is just one possible means for doing this, but I wanted to stick with the Scanner usage simply because you seem comfortable with it...
Now, somewhere in your compound loops, something gets messed up and the Scanner is getting out of sync.
Now, because we've initialised our array to the header information we read first, we can remove the compound loop in favor of something like...
while (scanner.hasNextLine() && classList.length < i) {
String line = scanner.nextLine();
Scanner scanLine = new Scanner(line);
String studentId = scanLine.next();
int mark = scanLine.nextInt();
scanLine.close();
classList[i] = new Student(studentId, mark);
i++;
}
Instead. I've left the array length check in just in case the file is lying. This means that the header can report just about any value it wants, but the loop will check for the availability of data in the file AND that we have room to read it...
This all assumes that there are no blank lines in the file you are trying to read, unlike the example you posted. If there is, you would need to add a check in and skip those lines
This question already has answers here:
Java calculator not executing if-statement [duplicate]
(3 answers)
Closed 9 years ago.
In the code below, in the first iteration of the first for loop, boxes[a] is automatically assigned a null value.
The remainder of the iterations are fine (user input is accepted). Only the first has the issue where a null value is automatically assigned.
Does anyone know why this may be? Thank you.
package testing;
import java.util.Scanner;
public class Testing {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Scanner in2 = new Scanner(System.in);
int boxNumber;
boxNumber = in.nextInt();
String[] boxes = new String[boxNumber];
System.out.println(boxNumber);
for(int a=0; a <= boxes.length - 1; a++){
boxes[a] = in.nextLine();
System.out.println(boxes[a]);
}
int packageNumber;
packageNumber = in2.nextInt();
String[] packages = new String[packageNumber];
System.out.println(packageNumber);
for(int n=0; n <= packageNumber - 1; n++){
packages[n] = in.nextLine();
System.out.println(packages[n]);
}
}
}
The scenario fitting the description of what occurs is when you type in a number on the first line, then the rest of the lines are strings for the boxes.
But the nextInt() method doesn't advance past the first newline character, so the first time you call nextLine(), it matches on the rest of the line until the first newline character, "" ( not null).
After the call to nextInt(), insert a call to newLine() before the for loop to bypass the first newline character.
String firstNewLine = in.nextLine();
for(int a=0; a <= boxes.length - 1; a++){
when you did hit enter after entring the first number you also have and empty line that's why nextLine() return empty string, you can use this boxNumber = in2.nextInt(); instead but I would suggest to think of another way, normally you don't need two Scanner instances
Here is my code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String question;
question = in.next();
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
When I try to write "how do you like school?" the answer is always "Que?" but it works fine as "howdoyoulikeschool?"
Should I define the input as something other than String?
in.next() will return space-delimited strings. Use in.nextLine() if you want to read the whole line. After reading the string, use question = question.replaceAll("\\s","") to remove spaces.
Since it's a long time and people keep suggesting to use Scanner#nextLine(), there's another chance that Scanner can take spaces included in input.
Class Scanner
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
You can use Scanner#useDelimiter() to change the delimiter of Scanner to another pattern such as a line feed or something else.
Scanner in = new Scanner(System.in);
in.useDelimiter("\n"); // use LF as the delimiter
String question;
System.out.println("Please input question:");
question = in.next();
// TODO do something with your input such as removing spaces...
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
I found a very weird thing in Java today, so it goes like -
If you are inputting more than 1 thing from the user, say
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
So, it might look like if we run this program, it will ask for these 3 inputs and say our input values are 10, 2.5, "Welcome to java"
The program should print these 3 values as it is, as we have used nextLine() so it shouldn't ignore the text after spaces that we have entered in our variable s
But, the output that you will get is -
10
2.5
And that's it, it doesn't even prompt for the String input.
Now I was reading about it and to be very honest there are still some gaps in my understanding, all I could figure out was after taking the int input and then the double input when we press enter, it considers that as the prompt and ignores the nextLine().
So changing my code to something like this -
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
sc.nextLine();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
does the job perfectly, so it is related to something like "\n" being stored in the keyboard buffer in the previous example which we can bypass using this.
Please if anybody knows help me with an explanation for this.
Instead of
Scanner in = new Scanner(System.in);
String question;
question = in.next();
Type in
Scanner in = new Scanner(System.in);
String question;
question = in.nextLine();
This should be able to take spaces as input.
This is a sample implementation of taking input in java, I added some fault tolerance on just the salary field to show how it's done. If you notice, you also have to close the input stream .. Enjoy :-)
/* AUTHOR: MIKEQ
* DATE: 04/29/2016
* DESCRIPTION: Take input with Java using Scanner Class, Wow, stunningly fun. :-)
* Added example of error check on salary input.
* TESTED: Eclipse Java EE IDE for Web Developers. Version: Mars.2 Release (4.5.2)
*/
import java.util.Scanner;
public class userInputVersion1 {
public static void main(String[] args) {
System.out.println("** Taking in User input **");
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name : ");
String s = input.nextLine(); // getting a String value (full line)
//String s = input.next(); // getting a String value (issues with spaces in line)
System.out.println("Please enter your age : ");
int i = input.nextInt(); // getting an integer
// version with Fault Tolerance:
System.out.println("Please enter your salary : ");
while (!input.hasNextDouble())
{
System.out.println("Invalid input\n Type the double-type number:");
input.next();
}
double d = input.nextDouble(); // need to check the data type?
System.out.printf("\nName %s" +
"\nAge: %d" +
"\nSalary: %f\n", s, i, d);
// close the scanner
System.out.println("Closing Scanner...");
input.close();
System.out.println("Scanner Closed.");
}
}