I am trying to make this program That uses the scanner method. A user would type their name, then the ScannerToolclass would store that information into the guess string varible. An Object is created in the portation class as ScannerTool cool = new ScannerTool(); for both the justPoints() and post() methods. The portation class takes the objects and store what the user types into a String variable called hope as String hope = cool.scannerT() it then takes what the user types and executes an if statement. I create an object for the portation class and ScannerTool inside the MainTest and then I run it from MainTest class.
My problem is that when I run this program it throws an exception error:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at ScannerTool.scannerT(ScannerTool.java:7)
at portation.justPoints(portation.java:12)
at MainTest.main(MainTest.java:20)
However, when i dont use the portation class and just go from ScannerTool to MainTest with the same code from portation it works. The weird part is that when I do it the original way there are no errors presented at the lines, only when I execute the whole program
What I tried: I tried to change the return types in the methods in portation from int and string to void, that didn't work. I tried looking at the lines that said where the error occured, but that didn't help becuase everything looked correct. Since it's not throwing actual errors on the IDE before running i'm at a loss.
the code:
The code that works:
MainTest
public class MainTest {
public static void main(String [] args) {
ScannerTool scan = new ScannerTool();
//portation damn = new portation ();
System.out.print("What your name my guy? ");
String hope = scan.scannerT();
int points = 0; // taken from the portation class
if (hope.equals("chris")){
points = points + 1;
}else {
points = 0;
}
System.out.println("the name " + hope + " is cool");
if(hope.equals("chris")) {
System.out.println("for your name being chris I award you one point!");
}else {
System.out.println("but, you get no points for that name");
} //taken from the portation class
System.out.println(points);
//damn.post();
//damn.justPoints();
}
}
portation: not in use
ScannerTool:
import java.util.*;
public class ScannerTool {
public String scannerT() {
Scanner message = new Scanner(System.in); //User input
String guess = message.nextLine(); // storing what the user inputted in a string variable
message.close(); //closed the scanner object
return guess; // returned user input
}
}
the code that doesn't work
MaintTest:
public class MainTest {
public static void main(String [] args) {
ScannerTool scan = new ScannerTool();
portation damn = new portation ();
System.out.print("What your name my guy? ");
String hope = scan.scannerT();
damn.post();
damn.justPoints();
}
}
portation:
public class portation {
public void justPoints() {
ScannerTool cool = new ScannerTool(); // created an object from the ScannerTool
String hope = cool.scannerT(); //stored the ScannerTool answer the user inputed from the guess string
int points = 0; //setup the points variable
if (hope.equals("chris")){
points = points + 1;
}else {
points = 0;
}
System.out.println(points);
}
public void post() {
ScannerTool cool = new ScannerTool(); // created an object from the ScannerTool
String hope = cool.scannerT(); //stored the ScannerTool answer the user inputed from the guess string
System.out.println("the name " + hope + " is cool"); //printed what the user typed
if(hope.equals("chris")) {
System.out.println("for your name being chris I award you one point!");
}else {
System.out.println("but, you get no points for that name");
}
}
}
ScannerTool:
import java.util.*;
public class ScannerTool {
public String scannerT() {
Scanner message = new Scanner(System.in); //User input
String guess = message.nextLine(); // storing what the user inputted in a string variable
message.close(); //closed the scanner object
return guess; // returned user input
}
}
when I use the way that doesn't work this is what runs:
What your name my guy? chris
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at ScannerTool.scannerT(ScannerTool.java:7)
at portation.post(portation.java:21)
at MainTest.main(MainTest.java:9)
What would be the answer I'm looking for? I would like to know, why am I getting this error and what do I need to do to fix it?
The problem comes from the fact that System.in is a specific InputStream - it is static and only created once. In your case, you read from it once and immediately close it (when you close the Scanner). When you try to read from a closed stream, it will throw an exception, NoSuchElementException in this case. When working with files it usually isn't a problem because you could always create a new InputStream.
What you need to do here is to make sure you will close the InputStream only when you're done with reading everything. You could make the Scanner variable static, create a new method for closing it and call it only when you're done with reading.
Related
So I am using eclipse to practice coding using java and till now it was doing great, until I wrote this program:
import java.util.*;
public class cars {
String name;
int dom;
Scanner in = new Scanner(System.in);
void takedata()
{
name=in.next();
dom=in.nextInt();
}
void displaydata()
{
System.out.print("Enter the name of the car"+name);
System.out.print("Enter the Date of Manufacture of the car"+dom);
}
public static void main(String[] args)
{
cars x = new cars();
cars y = new cars();
cars z = new cars();
x.takedata();
y.takedata();
z.takedata();
x.displaydata();
y.displaydata();
z.displaydata();
}
}
whenever I am trying to run the code it is showing me nothing.
I need help.
It wont show anything. Your code will wait till you enter the care name. So, first you need to provide input as your takeData() method is getting called before displayData(). Modify your takeData() method as shown below:
void takedata()
{
System.out.println("Enter Name of the Car: ");
name=in.next();
System.out.println("Enter Date of Manufacture: ");
dom=in.nextInt();
}
Then after executing your program your will be able to see below message:
Enter Name of the Car:
so I am currently taking an online coding class. and it has us make two different codes. one called SpaService. and one called CreateSpaService.
From my understanding, these are supposed to work together, to call variable (etc.) but it is not working and I am being hit with syntax errors saying that variables are not declared, but I declared them in the other code.
Am I supposed to put them in the same doc or something? I tried that and it still wouldn't work. Is there some way I have to link the two codes so they work together?
Here are the two codes.
also, do you see any syntax errors?
Thank you so much
import java.util.Scanner;
public class CreateSpaServices
{
public static void main(String[] args)
{
SpaService firstService = new SpaService();
SpaService secondService = new SpaService();
firstService = getData(firstService);
secondService = getData(secondService);
System.out.println("First service details:");
System.out.println(firstService.getServiceDescription() + " $" + firstService.getPrice());
System.out.println("Second service details:");
System.out.println(secondService.getServiceDescrption() + " $" + secondService.getPrice());
}
public static SpaService getData(SpaService service)
{
String service;
double price;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter service >> ");
service = keyboard.nextLine();
System.out.print("Enter price >> ");
price = keyboard.nextDouble();
keyboard.nextLine();
service.setServiceDescription(Service);
service.setPrice(price);
return service;
}
}
//here is other code, im not sure if where I put this, or if I keep it in its own document or in this doc.
public class SpaService
{
private String serviceDescription;
private double price;
public SpaService()
{
serviceDescription = "XXX";
price = 0;
}
public void setServiceDescription(String service)
{
serviceDescription = service;
}
public void setPrice(double servicePrice)
{
price = servicePrice;
}
public String getServiceDescription;
{
return serviceDescription;
}
public double getPrice()
{
return price;
}
}
You want to have the two classes in respective files in the same folder location:
SpaService.java
CreateSpaServices.java
Are you using some kind of IDE or using command prompt to manually compile and execute? IDE make things very simple but they take away some finer learning details for beginners.
Anyway a text file can have one Public class and any number of non-public class. As your both classes are public it should be in different file. Classes are linked to each other via import statement , which must be first line in java class if any.
You should get some compile issues also as I can see this method
public static SpaService getData(SpaService service)
As you are returning service variable which is of type String, but your method signature is expecting SpaService
The other answers are useful for understanding the class structure, but you have an issue with your code issue that is likely causing the majority of your problem.
In the getData method you have two items named service, the SpaService service and String service;, you need to change one of them.
This line is not valid service.setServiceDescription(Service);, you can't refer to Service with a capital S, you need to reference to a valid string.
Here is an example that takes the above into account:
public static SpaService getData(SpaService service)
{
//Create a scanner
Scanner keyboard = new Scanner(System.in);
//Get scanner input
System.out.print("Enter service >> ");
String description = keyboard.nextLine();
//Add input to SpaService object
service.setServiceDescription(description);
//Get scanner input
System.out.print("Enter price >> ");
double price = keyboard.nextDouble();
//Add input to SpaService object
service.setPrice(price);
//Return SpaService object
return service;
}
For better help please edit your question to include the full error.
I am trying to make a to do list that asks you to enter your tasks one by one then display them in order (as in 1. task1, 2. task 2, 3. task 3 etc). But when it displays the tasks it comes back as "0. null" one time instead of listing any of the tasks entered. Here is the script I am using:
1st class
package todolist;
import java.util.ArrayList;
public class ToDoList1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<ToDoList2> list = new ArrayList<ToDoList2>();
System.out.println("Time to make a digital to-do list!");
ToDoList2 n = new ToDoList2();
list.add(n);
System.out.println(ToDoList2.name + "'s to-do list");
System.out.println(ToDoList2.i + ". " + ToDoList2.l);
for(ToDoList2 enhanced : list)
{
System.out.println(ToDoList2.i + ". " + ToDoList2.m);
}
}
}
2nd class
package todolist;
import java.util.Scanner;
public class ToDoList2 {
public static String name;
public static int i;
public static String l;
public static String m;
{
Scanner s = new Scanner(System.in);
System.out.println("First type your name to identify your list in case you lose it");
name = s.nextLine();
System.out.println("Make sure to type \"end\" when you are finished");
System.out.println("Type in the first item on your to-do list");
String l = s.nextLine();
}
public ToDoList2()
{
Scanner s = new Scanner(System.in);
for(int i = 1; i == i; i++)
{
System.out.println("Type in the next item for your to-do list");
String m = s.nextLine();
if("end".equals(m))
{
break;
}
}
}
}
Your code is not correct. ToDoList2 scanning item list from standard input but not storing it. You should do as follow
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class TodoList {
public static String name;
List<String> tasks;
public TodoList(String name) {
this.name = name;
this.tasks = new ArrayList<>();
}
public void addTask(String task) {
this.tasks.add(task);
}
public String toString() {
int i = 1;
StringBuilder stringBuilder = new StringBuilder();
for (String task : tasks) {
stringBuilder.append(i + ". " + task);
stringBuilder.append("\n");
i++;
}
return stringBuilder.toString();
}
}
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("First type your name to identify your list in case you lose it");
String name = s.nextLine();
System.out.println("Make sure to type \"end\" when you are finished");
System.out.println("Type in the first item on your to-do list");
TodoList todoList = new TodoList(name);
String task = null;
while (!(task = s.nextLine()).equals("end")) {
todoList.addTask(task);
System.out.println("Type in the next item for your to-do list");
}
System.out.println(todoList);
}
}
a) Given that each ToDoList2 object is a separate task, I'm not sure why you've made the object class members static?
b) In your ToDoList2 constructor, you've got a for loop that introduces a local variable i which hides the ToDoList2 member variable i. You'd do well to change one of the variable names.
c) In your ToDoList2 constructor, you've got a for loop which is assigning a string returned by the Scanner to a local variable m. Are you sure you want m to be a local variable or do you actually want to assign the returned string to the member variable, m? I'm thinking the latter since the member variable m is never being assigned a value which explains why the code is printing out null.
d) When writing code, it is good practice to use meaningful variable names. Using names like i is OK as an index in a loop but in all other circumstances, you should go for something more descriptive that tells the reader what the variable is storing.
e) Consider making all your ToDoList2 member variables private (and final if possible). Add a print function to the ToDoList2 class to print out the task details. A key principle is Object Oriented Programming is to hide the internals of a class.
I'm a Java newbie and I have this question.
Can I pass a variable to a method multiple times without creating a new object?
For example, if I have a variable x which is the user input, another variable called m and a method were: if x is "h" then m is "example1" else if x is "f" m is "example2".
If I write:
String x = Scanner.next();
And I create the object passing the x variable, when I write,
System.out.println(obj.m);
If the input was h It will print out "example1"
But if write down this after what i showed up:
x = Scanner.next();
System.out.println(obj.m);
Whatever character I write down the output will be "example 1"
If I type "f" the first time the output will be "example2"
But the second system.out.println() will print "example2" eventually if I typed "h" the second time
So is it possible to pass a variable only one time with a value that changes over time without creating a new object?
If I understand your question correctly, then yes, you can pass a variable to a method multiple times without creating a new object. Let's say you create a class like this:
public class Test {
public String m;
public void testMethod(String x) {
if ("h".equals(x)) {
m = "example1";
} else if ("f".equals(x)) {
m = "example2";
} else {
m = "other";
}
}
}
If you created an object from this class in a main method and pass in different values of x as the argument for testMethod(), the value of m would change:
public class MainClass {
public static void main(String[] args) {
Test obj = new Test();
String x = "h";
obj.testMethod(x);
System.out.println(obj.m); // prints example1
x = "f";
obj.testMethod(x);
System.out.println(obj.m); // prints example2
}
}
As I understood your question, I have added a solution that will create the object you mentioned one time and call the method inside it repeatedly as you enter values. This might help you
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ClassOfYourObject object = new ClassOfYourObject();
while (true) {
System.out.print("Enter letter : ");
String x = scanner.next();
object.yourMethodToPrint(x);
}
}
}
class ClassOfYourObject {
void yourMethodToPrint(String value) {
if (value.equals("h")) {
System.out.println("example1");
} else if (value.equals("f")) {
System.out.println("example2");
} else {
System.out.println("Invalid letter");
}
}
}
public class Pig {
private int pigss;
private Pig[] pigs;
public Pig[] pigNumber (int pigss)
{
pigs = new Pig [pigss];
return pigs;
}
Code that includes main method:
public class animals{
public static void main(String[] args){
Pig cool = new Pig();
Scanner keyboard = new Scanner (System.in);
System.out.println("How many pigs are there?");
int pigss = Integer.parseInt( keyboard.nextLine() );
cool.pigNumber(pigss);
//This is where I have trouble. I want to use the array pigs here in the main method, this is what i tried:
Pig[] pigs = cool.pigNumber(pigss);
I then tried to use a for loop and assign values (String) to the index of arrays (pigs[]). But the error that gives me is: cannot convert from String to Pig. Any tips are appreciated. THank you.
for(int j = 0; j < pigs.length; j++)
{
System.out.println("What is the pig " + (j+1) + "'s name");
pigs[j] = keyboard.nextLine();
}
Your pigs will need an attribute to contain the string values you are trying to pass:
public class Pig {
private String name;
public void setName(String n) {
name = n;
}
public String getName() {
return name;
}
Then when you want to assign this string value to your pig:
int indexOfPig = 0; // Or whatever it is supposed to be
pigs[indexOfPig].setName("I am a string");
In java you can only use ints as the indexes of arrays
It is saying 'cannot convert from String to Pig' because you can't do that!
If you want somehow convert a String to a Pig, you are going to need to write some code to do the conversion. For example, you might write a constructor that creates a new Pig from some kind of description. Or you might write a method that looks up a Pig by name or number or something.
It is hard to offer any more concrete advice because you don't tell us what is in the string values ... or how you expect the strings to become pigs. (The only suggestion I have is to try Macrame :-) )
Pig doesn't have a name member or even method that accepts a string. Also you are trying to assign a String(keyboard.nextline() to a Pig(pigs[j].
Add an attribute name to your pig.
class Pig{
public String name:
public void Pig(String name){
this.name = name;
}
}
Then assign a new instance of Pig in the loop.
pigs[j] = new Pig(keyboard.nextLine());
Also get rid of the useless class pigNumber. All you need is an ArrayList of Pigs. The array list can be dynanically sized.
List<Pig> pigs = new ArrayList<Pig>
so your loop could be something like
String name = ""
while(true){
name = keyboard.readline();
if(name== "stop"){
break;
}
pigs.add(new Pig(names);
}
Then getting the number of pigs is a simple
System.out.println(pigs.length());