Import these scanners into another class? - java

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.

Related

Math.pow(x,2) area of square

i am running a code, but i dont seem to be able to get the scanner working, anyone got an idea how?
public class verk34 {
public static void main(String[] args) {
System.out.println(Math.pow(x,2));
}
}
the thing is inserting a number on your own without altering the code.
As per my understanding, you need to add Scanner for taking input from end users and importing the java.util.Scanner statement.
Scanner in = new Scanner(System.in);
int x = in.nextInt();
First, you need to import scanner and Math
import java.util.Scanner
import java.lang.Math
Then If I am understanding correctly the problem, you need to do this in two steps :
-Instantiate a scanner and collect user input as an integer.
Scanner sc = new Scanner(System.in);
System.out.println(" Please enter the square area :");
int userValue = sc.nextInt();
The nextInt method will lock process and wait for a keyboard event before continuing. So enter a nulber with your keyboard.
-Use System.out.println with given value.
System.out.println(Math.pow(userValue,2));

making the user input a name for the class/scanner to store?

im trying to learn Java, meaning that my experience and knowledge is almost none, and i hope you can help me with this:
(The thought i had was like how you can name yourself in videogames, with the option to display the name in future instances without any deeper meaning later on)
import java.util.Scanner;
public class Playername {
public static void main(String[] args) {
public String getName();
Scanner Charname = new Scanner (System.in);
System.out.print ("What is your name?");
Charname.nextLine();
String getName = Charname;
System.out.print (Charname);
}
}
i probably messed this up, reading only the early chapters of a book about java and then trying to use commands and things in way's they were not supposed to be used.
(i wanted to save the name of the scanner and then copypaste it to the String variable)
thank you
PS: The error i get is "cannot convert from scanner to string", basically stating that my question would be how the idea i had can, in the most simplistic way possble, be realised.
Try this
Scanner Charname = new Scanner (System.in);
System.out.print ("What is your name?");
String input = Charname.nextLine();
String getName = input;
System.out.print (input);
You cannot assign scanner object directly to string reference.
You are trying to assign Charname which is a Scanner to a String
What you want to do is to assign Charname.nextLine() which is a String to your variable
Scanner Charname = new Scanner (System.in);
System.out.print ("What is your name?");
String getName = Charname.nextLine();
System.out.print(getName);
Welcome to StackOverflow!
Firstly, I'd like to start you off with some code conventions.
These help others read your code, since even though you may know what is going on; we may not.
Now, for your question.
Scanner scannerName = new Scanner (InputStream inputStream);
This line creates a Scanner object with the InputStream coming from the an input stream, and we name it scannerName. Generally, you want to label your objects what they are, or some abbreviation of that.
Scanner scanner1 = new Scanner(System.in);
This is sufficient for our purposes. Since we want to get information from the System.in inputstream, or console, we use System.in as our InputStream.
Now, this scanner object that we've created can receive input from the console. It does this through the use of methods like
scanner1.nextLine();
The above piece of code returns a String value.
Alone, it's pretty useless. So we'll assign a String object to take and store that value.
String characterName = scanner1.nextLine();
What this does is it sets the String's value to be equivalent to the value of the scanner1's inputstream, after hitting enter.
So if a user enters "Johnathan Nathan", and then presses Enter,the String named characterName will be set to "Johnathan Nathan".
A full working example is:
Scanner scanner1 = new Scanner(System.in);
System.out.println("Please enter your name: ");
String characterName = scanner1.nextLine();
System.out.println("Hello, " + characterName());
This would ask for the person's name, then say hello to them directly after.
Finally, if you have any questions regarding how a class is used, you can always look up the Javadoc of the class you're having problems with.

cannot find symbol error when creating an input object in java

I am new to java and netbeans. I am trying to write a program that requires user input. This is my code:
public class Arrays {
public static void main(String[] args){
}
private double[] readNumbers(){
final Input in = new Input();
System.out.print("How many numbers will you enter?: ");
final int count = in.nextInt();
final double[] list = new double[count];
for (int i = 0; i < count; ++i){
System.out.print("Enter next number: ");
list[i] = in.nextDouble();
}
return list;
}
}
In line final Input in - new Input(); Netbeans underlines Input saying that it cannot find symbol. However I practically copied this code from the textbook so I don't understand what the problem is. I thought maybe I needed to import java.io, but that did not solve the problem. Really sorry if this is a stupid question, but any help would be really appreciated.
Thank you!
Looks like your text book has some class definition that you forgot to import to your project.
If you like to , change your code like,
final Input in = new Input();
to
final Scanner in = new Scanner(System.in);
If you don't want to change your code, then look few pages up and down the pages from where you got this code, you should see Class named Input , some what similar to this :
class Input{
public int nextInt(){
Scanner sc=new Scanner(System.in);
return sc.nextInt();
}
public double nextDouble(){
Scanner sc=new Scanner(System.in);
return sc.nextDouble();
}
}
Which is basically, an extra unnecessary work.
Include that in your project, and it should run fine.
Your code attempts to create an instance of class Input, but you don't include code for class Input. Resolve that (try the previous page in the book!) and your code will probably work.
Input may be a wrapper class for java.util.Scanner:
You could replace:
final Input in = new Input();
with
final Scanner in = new Scanner(System.in);

Whats wrong with my User Input Code?

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();

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