Whats wrong with my User Input Code? - java

Everytime I use this code:
import java.util.*;
public class Main{
public static void main (String args []){
System.out.println("What is your name?");
Scanner name = new Scanner (System.in);
System.out.println("Hello," + name);
}
}
It just gives me random letters like:
Hello,java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match valid=false][need input=false]
Please someone help.

Because what you are doing is actually just printing out the Scanner's toString method since in your code, the object name is actually an instance of Scanner, which is NOT a string.
You need to call the method to actually read the user input.
What you need to do is do something like this
import java.util.*;
public class Main{
public static void main (String args []){
System.out.println("What is your name?");
Scanner scanner = new Scanner (System.in);
String name = scanner.next();
System.out.println("Hello," + name);
}
}

Scanner name = new Scanner (System.in);
Using this you have created an scan reference. Use this to read the name like
String str = name.next();
Read about Scanner class for more details.

You are printing reference of Scanner.
If you want to input an integer, Write
Scanner in = new Scanner(System.in);
int n = in.nextInt();
If you want to input a string, write
Scanner in = new Scanner(System.in);
String n = in.next();

Related

Import these scanners into another class?

Again I am very new to Java, and I have this code here:
package Final;
import java.util.Scanner;
public class Position {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner MyPos = new Scanner(System.in);
System.out.println(" Enter Position: ");
String Pos = MyPos.nextLine();
System.out.println("Position: "+Pos);
Scanner MyMains = new Scanner(System.in);
System.out.println("Enter Mains: ");
String Mains1 = MyMains.nextLine();
System.out.println("Mains: "+Mains1);
Scanner WScore = new Scanner(System.in);
System.out.println("Enter Ward Score: ");
String score = WScore.nextLine();
System.out.println(" Average Ward Score is:"+score);
}
}
I was curious if there was a way to possibly import all 3 of my scanners to another class without moving all the actual code from this class? The class I'm trying to move it to is a class called "Player.java". There aren't any problems with my code, but additional input is always appreciate to help me understand and improve my code!
You don't need a new scanner for each variable. What you do need to do is close() a scanner when you are done using it.
You are thinking of the Scanner itself being associated with a variable - when in fact it is associated with System.in...
So, every time you want another variable, just do:
Scanner sc = new Scanner(System.in);
String firstThing = sc.nextLine();
String secondThing = sc.nextLine();
sc.close(); // Do this when you're done storing input from System.in!
Once you have declared your scanner. I'm not sure why you would want to pass the scanner to another class. What you can do easily is pass the variables that you grab from your scanner into a player object.
Just do Player p1 = new Player(stringYouScanned); assuming that you have your constructor in your Player class accept a String.
Or, look up getter and setter methods. Then you can do something like: `p1.setPosition(4);' (you could replace 4 with an int you scanned in, you get the idea).
If for some reason you want to scan input from within the Player, I'd just initialize a new Scanner, but make sure you are doing sc.close(); after you are done processing your input.

Whats the difference between two multiple user input programs? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
import java.util.Scanner;
public class HelloWorld{
public static void main(String args[]){
Scanner dd = new Scanner(System.in);
System.out.println("Enter name");
String b = dd.nextLine();
System.out.println("Enter num");
int num = dd.nextInt();
}
}
And
import java.util.Scanner;
public class HelloWorld{
public static void main(String args[]){
Scanner dd = new Scanner(System.in);
System.out.println("Enter num");
int num = dd.nextInt();
System.out.println("Enter name");
String b = dd.nextLine();
}
}
Why the latter doesn't work peoperly(doesn't let me enter name), while the first one does?
I have made up a new version without that annoying "Scanner scan = new Scanner".
And what about this solution? What cons may it have?
import java.util.Scanner;
public class HelloWorld{
public static void main(String args[]){
System.out.println("Enter num");
int i = new Scanner(System.in).nextInt();
System.out.println("Enter name");
String b = new Scanner(System.in).nextLine();
}
}
The second program expects an Int first and then a name. And hence might be erroring out when a name is entered.
In the second case, nextInt() does not scan over the newline character that the user inputs when pressing the Return key.
In the first case, nextLine() is encountered first so the problem doesn't manifest itself.
The moral of the story is to always use nextLine() and parse the resulting string accordingly. Use something like Integer#parseInt to convert a string to an integer.

Trying to break up a string into list

I'm trying to convert a String into a List. I'm getting the string by user input, but whenever I run my code, and it gives me this:
Enter a number: java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match valid=false][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q�\E][infinity string=\Q∞\E]
This is my code
public class ch3_15 {
public static void main(String[] args) {
int compNum, user_hund, user_ten, user_one, comp_hund, comp_ten, comp_one;
String s;
//user input
System.out.print("Enter a number: ");
Scanner input1 = new Scanner(System.in);
s = input1.toString();
//generating random number
compNum = (int) Math.random() * 1000;
System.out.println(s);
//finding the hundreds, tens, and ones place of the user number
List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));
}
}
This is not error. It is expected behavior since you used
Scanner input1 = new Scanner(System.in);
s = input1.toString();
...
System.out.println(s);
and toString() returns String representing of object on which this method was invoked (in this case instance of Scanner).
If you want to use that Scanner to read line from user you should write
s = input1.nextLine();
// ^^^^^^^^
Your problem is that you don't read the next String from the console, but rather convert the Scanner to a String, which you then print.
What you want to use is Scanner.nextLine(), instead of toString().
Also, this is not a runtime error, but simply a wrong output.
you should use scanner.nextLine() to read next line that use enters.
Your current code is printing the toString() method of the scanner object and that is not a runtime error and is an expected behaviour.
//user input
System.out.print("Enter a number: ");
Scanner input1 = new Scanner(System.in);
s = input1.nextLine();
You are not advancing from your current line; the method to use in this case is nextLine() from the class Scanner; So the code would be something like:
System.out.print("Enter a number: ");
Scanner input1 = new Scanner(System.in);
s = input1.nextLine();
String aux = s.toString(); // To return the string representation from the sc
nextLine() method from Java API 7 => This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.**/

Why does it not ask me for input?

import java.util.Scanner;
class Tutorial {
public static void main (String args[]){
System.out.println("Who goes there?");
Scanner name = new Scanner(System.in); ## I am asking for input form user but it does not take imput
if (name.equals("me") || name.equals("Me") ){
System.out.println("Well, good for you smartass.");
}else System.out.println("Well good meet");
}
}
Why does the program run the else and not ask for my input?
You should read your input by using scanner.nextLine():
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
if (name.equals("me") || name.equals("Me"))
{
System.out.println("Well, good for you smartass.");
} else {
System.out.println("Well good meet");
}
scanner.close();
You merely created a Scanner but did not tell it to read something from the standard input. You can do that by calling scanner.next() to read a token scanner.nextLine() to read a line, etc. As well you are comparing a Scanner to a String in the if-statement.
import java.util.Scanner;
class Tutorial {
public static void main (String args[]){
System.out.println("Who goes there?");
Scanner s = new Scanner(System.in);
String name = s.next(); // get the token
if (name.equals("me") || name.equals("Me") ){
System.out.println("Well, good for you smartass.");
} else System.out.println("Well good meet");
}
}
You've only created an instance of the Scanner object. You need to invoke a method such as Scanner#nextLine() to read input and then compare the read value to "me" or "Me".
Example:
Scanner name = new Scanner(System.in);
String input = name.nextLine();
if (...) // Compare input to something here.
You might want to use String#equalsIgnoreCase for case-insensitive matching too.

copyValueOf in Java?

import java.util.Scanner;
public class CourseSplitter {
public static void main(String args[]){
Scanner keyboard = new Scanner(System.in);
char[] course; //course code format: ABCDE##
String code;
//int num;
System.out.println("Input Course: ");
course = keyboard.next();
System.out.println(course);
code = String.copyValueOf(course, 0, 4);
System.out.println(code);
}
}
I don't know how I should let the user input the course when I'm using a character array instead of string. In short, how do I use the "scanner" on character arrays?
The instruction is the user will input a course code in the format: ABCDE##
Then, the program must split it into the course name and the course number. So, I had to use the copyValueOf method but it doesn't seem to work because from all the articles I read online, they used a char[] array but initialized the array with some value. So I was wondering how I could use the scanner on character arrays.
Why not just read a string from the scanner and then call String.toCharArray? It's not even clear why you need a char array here...
Why not just read a string directly with scanner.nextLine?
import java.util.Scanner;
public class CourseSplitter {
public static void main(String args[]){
Scanner keyboard = new Scanner(System.in);
System.out.println("Input Course: ");
String course = keyboard.nextLine();
System.out.println(course);
String code = course.substring(0, 5); //You put 4 but it left out the last letter in the course name. I changed it to 5 and it worked but I'm confused since the index always start with 0.
System.out.println(code);
String num = course.substring(5, 6);
System.out.println(num);
}
}

Categories

Resources