System.out.print() reads Scanner incorrectly - java

I was trying to code this program for one of my classes and I ran into a problem with my output. It is supposed to read whatever I have typed in for the Scanner input. However, the output skips the first word and I'm not really sure why. You can ignore most of the declarations of variables in the main method. Those are useful just for the rest of the program.
public static void main(String[] args) {
String fullName;
int anniversaryM;
int anniversaryY;
int periodHours;
String jobTitle;
double payRate;
int monthsWorked;
double vacationHours;
double grossPay;
double retirement;
double taxWithholding;
double netPay;
Scanner in = new Scanner(System.in);
fullName = inputLine(in, "Enter your full name:");
System.out.print(fullName);
}
public static double inputNumber(Scanner input, String prompt) {
Scanner in = new Scanner(System.in);
in.nextDouble();
return in.nextDouble();
}
public static String inputLine(Scanner input, String prompt) {
Scanner in = new Scanner(System.in);
System.out.println(prompt);
in.next();
return in.next();
}
public static double calcPercentage(double grossPay, double retirement) {
Scanner in = new Scanner(System.in);
in.nextDouble();
return in.nextDouble();
}
Output:
Enter your full name:
John Doe
Doe

You have a double call to in.next(). Just remove it and you should be OK. Additionally, note that you're passing the Scanner to the method, so you shouldn't create a new inside the method:
public static String inputLine(Scanner input, String prompt) {
System.out.println(prompt);
return input.nextLine();
}

I think your problem is the in.next(); return in.next();. in which case it will call the reader two times, if you want to return the value of the in.next(); you should put it in a container and return that container or just go straight return in.next();

Related

How to avoid using the dummy lines?

I'm fairly new to programming so I'm currently stuck on figuring out how to make my code work cleaner. As of right now there are some random dummy lines in my code to make sure i dont skip part certain part of the loops. I was wondering if there are any ways to avoid it.
public static void main(String arg[]) {
String CandidateID;
String Name;
String Option1;
int Test1;
int Test2;
String dummy;
Scanner sc = new Scanner(System.in);
ArrayList<TestResult> StudentResults = new ArrayList<TestResult>();
do {
dummy = sc.nextLine();
System.out.println("Enter student data? y/n");
Option1 = sc.nextLine();
if (Option1.equals("y")) {
System.out.println("Enter Candidate ID:");
CandidateID = sc.nextLine();
System.out.println("Enter Name:");
Name = sc.nextLine();
System.out.println("Enter Test 1:");
Test1 = sc.nextInt();
System.out.println("Enter Test 2:");
Test2 = sc.nextInt();
TestResult TestResult = new TestResult(CandidateID, Name, Test1, Test2);
StudentResults.add(TestResult);
}
}
while (!Option1.equals("n"));
If you don't use the value inside the dummy variable, you can just execute sc.nextLine(); without assigning its return value to a variable.
It'll have the same effect, because the function is still being called.

new Scanner not waiting for input

When executed, the following code will not wait for user input:
private int getInt(){
Scanner sc = new Scanner(System.in);
int result = 0;
while (sc.hasNext()){
System.out.println("There is a token");
if (sc.hasNextInt()){
result = sc.nextInt();
} else {
sc.next();
}
}
System.out.println("There is not a token");
sc.close();
return result;
}
I am calling this function immediately after calling another functions that gets a string rather than an int. This functions works correctly.
private String getString(String prompt, String pattern, String errorMessage){
System.out.println(prompt);
Scanner sc = new Scanner(System.in);
while (!sc.hasNext(pattern)){
System.out.println(errorMessage);
sc.next();
System.out.println(prompt);
}
String result = sc.next();
sc.close();
return result;
}
I have seen other similar questions where people try to read in data using multiple methods in succession, normally nextLine() then nextInt and don't consume the end of the token first, but I don't think this is what's happening here.
The programme doesn't wait for user input and just skips straight to the debugging line "There is not a token". Any help would be appreciated!
The calling code is as follows:
System.out.printf("Hello %s, you are %d and were born in %d. You are %s tall", m.getString(), m.getInt(), m.getBirthYear(), m.convertHeight(m.getHeight()));
This code:
public class ScannerDemo {
public static void main (String[] args) {
ScannerDemo m = new ScannerDemo();
Scanner sc = new Scanner(System.in);
System.out.printf(
"Hello %s, you are %d and were born in %d. You are %s tall",
m.getString(sc), m.getInt(sc), m.getInt(sc), m.getString(sc));
sc.close();
}
private int getInt (Scanner sc) {
int result = sc.nextInt();
return result;
}
private String getString (Scanner sc) {
String result = sc.next();
return result;
}
}
When given this input:
Hector
53
1968
5'8"
Produces the following output:
Hello Hector, you are 53 and were born in 1968. You are 5'8" tall
The main problem is calling sc.close() inside each method. When you close this method, you actually close the input stream associated with the Scanner object and once you close it, there is no way to reopen it. I also took out all unnecessary code. You can insert the prompts as needed.

Confusion with scanner class -> nextLine()

I have written a basic code to read different data types. But I can not enter the string as input. What am I missing ?
public class Main {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int integer = read.nextInt();
double Double = read.nextDouble();
String string = read.nextLine();
System.out.printf("String: %s\nDouble: %f\nInt: %d",string,Double,integer);
}
}
You must "eat up" the newline character left over from the double.
Scanner read = new Scanner(System.in);
int integer = read.nextInt();
double Double = read.nextDouble();
read.nextLine();
String string = read.nextLine();
System.out.printf("String: %s\nDouble: %f\nInt: %d",string,Double,integer);
The problem is that after nextDouble() there is still a newline character out there so the scanner reads the next line which has nothing in it...

Using a scanner-method for multiple set methods within class

I am trying to create scanner methods within my class Address so I do not have to repeat the scanner code in every single method where I want user input. What I'm having problem with is that this method only seems to return my instance variable values and not the scanner inputs from the user when I run these two set methods in a test program of an instance of my Address class.
How can I do this? I do not want to repeat the scr.nextInt() etc in every single method.
//Scanner method for integer inputs from user.
public int scanInt(){
int userInt = scr.nextInt();
scr.nextLine();
return userInt;
}
//Scanner method for string inputs from user
public String scanLine(){
String userString = scr.nextLine();
return userString;
}
//in these methods below (and others) I want to use the above scanner methods so I don't have to repeat the code for scanner inputs in every single method.
public void setStreet(){
System.out.println("Skriv in gata: ");
scanLine();
}
public void setStreetNr(){
System.out.println("Skriv in gatunummer: ");
scanInt();
}
public void setStreet(){
System.out.println("Skriv in gata: ");
street = scanLine();
}
Sounds like you are testing your class with BlueJ or some other program. If that's the case, try this class.
import java.util.Scanner;
public class Address
{
String street;
int streetNr;
Scanner scr = new Scanner(System.in);
//Scanner method for integer inputs from user.
public int scanInt()
{
int userInt = scr.nextInt();
scr.nextLine();
return userInt;
}
//Scanner method for string inputs from user
public String scanLine()
{
String userString = scr.nextLine();
return userString;
}
public void setStreet()
{
System.out.println("Skriv in gata: ");
street = scanLine();
}
public void setStreetNr()
{
System.out.println("Skriv in gatunummer: ");
streetNr = scanInt();
}
}
This should work as you describe. Create an instance of the class, call both methods and inspect your object's parameters. This code assigns your inputs to a variable for each method.

whats wrong with my calculator code

package calculator;
import java.util.*;
public class calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Calculator");
System.out.println("Enter a number");
double firstNumber = in.nextDouble();
System.out.println("Enter another number");
double secondNumber = in.nextDouble();
System.out.println("Enter the letter for 'm'ultiply 's'ubtract 'a'dd or 'd'ivide");
String wantedProcess = in.nextLine();
String multiply = "m";
String subtract = "s";
String add = "a";
String divide = "d";
if(wantedProcess.equals(multiply))
{
double product = firstNumber * secondNumber;
System.out.println("=" + product);
}
}
}
so this is the calculator i was making but after i enter two numbers i cant type m s a or d. what am i doing wrong?
if(wantedProcess.equals(multiply))
You missed the second brace at the end. Now look: if you enter "m" for multiply and then compare String "m" with String "Multiply" how do you expect them to be equal? Compare only first letters, for example, using String.charAt() method.
What's more, I guess you'd be better off using Scanner's next() method, rather than nextLine(). Check their docummentation here: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()
change this if(wantedProcess.equals(multiply) to if(wantedProcess.equals(multiply))
you missed out )
Edit: Then
You need to create a new Scanner object again
Scanner inF = new Scanner(System.in);
String wantedProcess = inF.nextLine();

Categories

Resources