grabbing a String from another method Java - java

I'm trying to return the string "otheruser" from static void Answer2 to my main method.
public static void main(String[] args) {
System.out.println("is there another person with you?");
Scanner Answer2 = new Scanner(System.in);
String answer2 = Answer2.nextLine();
if (answer2.equals("yes")) {
System.out.println("ok then type there name in please");
Answer2();
} else if (answer2.equals("no")) {
System.out.println("ok then good day");
}
System.out.println("how old are you " + Answer2());
}
static void Answer2() {
Scanner otheruser = new Scanner(System.in);
String Otheruser = otheruser.nextLine();
System.out.println("hi " + Otheruser);
}

Instead of printing the string you got from the Scanner, you could return it, so it's available to the rest of the program:
static String answer2() {
Scanner otheruser = new Scanner(System.in);
String otherUser = otheruser.nextLine();
return otherUser;
}

In Java it is common practice to name methods and variables using camel case naming convention
You can not get a return value from the function static void Answer2() because the return type is void, which means it doesn't return anything. You need to change the return type to String to get the value.
As mentioned by Zabuza in the comments, you should not create multiple scanners on the same stream.
Additionally, if you really want to use methods for this you can make them more generic, and use them to get any input.
import java.util.Scanner;
public class Main {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("is there another person with you?");
String answer = getString();
if (answer.equalsIgnoreCase("yes")) {
System.out.println("ok then type their name in please");
String otherUser = getString();
System.out.printf("hi %s. how old are you?%n", otherUser);
int age = getNumber();
System.out.printf("%s is %d years old%n", otherUser, age);
} else {
System.out.println("ok then good day");
}
}
static String getString() {
return scanner.nextLine();
}
static int getNumber() {
return scanner.nextInt();
}
}

Related

Name output shows "null" Java

I am making a game-ish type of thing with three classes, combined. NOT HOMEWORK; hobby.
Codes for three classes:
Runner:
public class CounterGameRunner
{
// instance variables - replace the example below with your own
public static void main(String [] args){
Scanner input = new Scanner(System.in);
CounterGameCounter game = new CounterGameCounter();
System.out.println("You want to play a game I see. What is your name?");
String name = input.next();
game.NameIn(name);
CounterGAME game1 = new CounterGAME();
game1.actual();
}
}
Actual Game:
public class CounterGAME
{
// instance variables - replace the example below with your own
Scanner input = new Scanner(System.in);
int number;
int count=1;
boolean loop = true;
public CounterGAME(){
}
public void actual(){
CounterGameCounter game2 = new CounterGameCounter();
System.out.println("Guess a number between 1 and 101, see how many times you get it!");
number=input.nextInt();
int r = (int)(Math.random() * (100) + 1);
while(loop==true){
if(number < r){
System.out.println("Too small, try again");
number = input.nextInt();
count++;
game2.Counter(count);
} else if(number == r){
System.out.println("Wow, you won! Who'd have thought?");
count++;
game2.Counter(count);
break;
System.out.println(game2.done());
} else if(number > r){
System.out.println("Too large, try again");
number = input.nextInt();
count++;
game2.Counter(count);
}
}
}
}
Counter Class:
public class CounterGameCounter
{
// instance variables - replace the example below with your own
private String Name;
String done1;
int correct;
public CounterGameCounter(){
}
public String NameIn (String nm){
Name = nm;
return Name;
}
public String NameOut(){
return Name;
}
public void Counter(int count){
correct = count;
}
public int getCount(){
return correct;
}
public String done(){
done1 = "Name: " + NameOut() + "\n" +
"Times Answered: " + getCount();
return done1;
}
}
Problem:
The counter works properly and everything else displays and functions properly in the end. However, any name I input in the beginning always shows "null" while running the program. Why?
Your variable names are really confusing, and there are a lot of bad practices in your code, but null in name is because you create a new Counter in CounterGAME:
public void actual(){
// here
CounterGameCounter game2 = new CounterGameCounter();
// more code
}
Change actual to receive a CounterGameCounter:
public void actual(CounterGameCounter game2){
// more code
}
And call it like:
public static void main(String [] args){
Scanner input = new Scanner(System.in);
CounterGameCounter game = new CounterGameCounter();
System.out.println("You want to play a game I see. What is your name?");
String name = input.next();
game.NameIn(name);
CounterGAME game1 = new CounterGAME();
game1.actual(game);
// more stuff
}
FREE TIPS:
use String getName() and void setName(String)
start variable, object and attribute names with lowercase
String name;
Object object;
Variable names must be representative and descriptive
CounterGameCounter counterGameCounter = new CounterGameCounter();
This is also applicable to Object names:
GameCounter gameCounter = new CounterGameCounter();
try this:
String name = input.nextLine();
instead of:
String name = input.next();

Input variable created at Main is a different value to that created in Method

I have created a method that gets input from the user. However, my issue is that when I attempt to return the value of the method, it continuously asks for a new number as input. Instead, I want it to ask for a number once, then return it.
For example: the following code illustrates what I want to achieve without a method, but including it within a method causes difficulties:
Working Code Inside Main:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int age;
System.out.print("Enter Age: ");
age = input.nextInt();
System.out.print("/nYou're " + age + " years of age.");
}
However, when I try to do this within a method, I have difficulties:
Code Inside Method:
public static int getAge() {
Scanner input = new Scanner(System.in);
int number;
number = input.nextInt()
return number;
}
The issue is, whenever I try print System.out.print(getAge()); it asks for a number each time. Why does the first code allow me to print age without asking for a new number, but calling the method to print the number causes issues and continues to ask for a new number.
Effectively, I just want to call that method, ask for a number to input once, then call that method to return the number that the user has entered.
Its not just about having code to do job, but also about design. I would recommend below approach, features are:
A utility class and a generic method promptUserInput to prompt the user for input, passing your message
It will return a String object, convert it into other objects as required.
If you want to access it from other methods/classes, then store as instance variable, else simply use it to print or whatever is your plan.
You can handle the Scanner object to close it once everything is done, and parent thread is ready to die, for that you will need some change.
P.S.: My intention is not simply providing chunk of codes but make you think how to design. So, you may need to some change as per your requirement, scenarios and as you test.
Code:
public class UserTest {
public static void main(String[] args) {
User user = new User();
user.promptUserAge();
user.printUserAge(user.getUserAge());
//DO something.
user.printUserAge(user.getUserAge());
user.promptUserAge();
user.printUserAge(user.getUserAge());
}
}
public class User {
private int userAge = 0;
public void promptUserAge() {
String userInput = AppUtils.promptUserInput("Enter Age: ");
userAge = new Integer(userInput);
}
public int getUserAge(){
return userAge;
}
public void printUserAge(int age){
System.out.print("\nYou're " + age + " years of age.");
}
}
public class AppUtils {
public static String promptUserInput(String message) {
Scanner input = new Scanner(System.in);
System.out.println(message);
String userInput = input.next();
return userInput;
}
}
Your issue is that every time you call getAge() it is going to create a new scanner and try to get input again. Instead, when you return your number from getAge() the first time, save the value in a variable that you can reuse.
Something like this:
int age = getAge();
System.out.print("your age is " + age + " years of age");
You could store the user input in a class member variable, and reuse it later on.
import java.util.Scanner;
public class MyClass {
private int age = -1;
public static void main(String[] args) {
MyClass o = new MyClass();
o.getAge();
System.out.print("\nYou're " + o.getAge() + " years of age.");
}
public int getAge() {
if (age == -1) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Age: ");
age = input.nextInt();
}
return age;
}
}

how to get data from other methods?

does anyone know how to get the counters value transfered after it is increased? so if you awnser it right it changes to one in the next method?
package swag;
import java.util.Scanner;
public class Main {
public static void enter(){
System.out.print("welcome to the impossibe game! Press enter to start.");
Scanner input = new Scanner(System.in);
String enter = input.nextLine();
if (enter.equals("")){
System.out.println(" Level one");
}else{
System.out.println("Please press enter");
}
}
public static void firstlevel(){
System.out.println("What is the tenth digit of PI?");
Scanner input = new Scanner(System.in);
int awnser = input.nextInt();
int awnser1 = 5;
int counter = 0;
if (awnser == awnser1 ){
System.out.println("Correct!");
counter++;
System.out.println(" Score: " +counter + "/1");
}else{
System.out.println("Wrong!");
System.out.println(" Score:"+ counter+"/1");
}
}
public static void secondlevel(){
System.out.println("a king and queen get on a boat. then the boat sinks. how many people are alive");
Scanner input = new Scanner(System.in);
String awnser = input.nextLine();
if (awnser.equals("two ")){
System.out.println(" Correct!");
}
}
public static void main(String args[]){
enter();
firstlevel();
}
}
Ah, the way you have defined counter, it can only be seen in firstLevel.
Best thing to do is make it a 'class variable'. To do that:
Delete int counter = 0; from the firstLevel method.
Add static int counter = 0; on the very next line after public class Main {
So the start of your class should look like:
public class Main {
static int counter = 0;
Now counter will be visible in all methods.
I would highly recommend not using a static counter, as suggested by others. Static mutable objects tend to violate the principle of object oriented programming. If you separate the functionality of your game into methods, you'll have a much more beautiful main method:
public static void main(String args[]) {
// Lets create a new Game object. it will keep track of the counter itself!
Game game = new Game();
// Then we only have to call the methods defined below..
game.enter();
game.firstLevel();
game.secondlevel();
}
Now the code for the class Game containing all the logic:
public class Game {
// Some static final members. they are not meant to change throughout the execution of the program!
// The advantage of defining INDENTAION just once, is that you can easily change it in one place and it will always be consistent!
private static final String INDENTAION = "\t\t";
private static final int TOTAL_POINTS = 2;
// We can use the same scanner object in each method!
private Scanner input = new Scanner(System.in);
// Just like the counter. it will be accessible in each method and refer to the same integer!
private int counter = 0;
public void enter() {
System.out.print("welcome to the impossibe game! Press enter to start.");
Scanner input = new Scanner(System.in);
String enter = input.nextLine();
if (enter.equals("")) {
System.out.println(INDENTAION + "Level one");
} else {
// I am not sure why you put this here, but I'll leave it in for now
System.out.println("Please press enter");
}
}
// We put that code into seperate methods, since it will get called multiple times!
private void answerCorrect() {
System.out.println("Correct!");
counter++;
printScore();
}
private void answerWrong() {
System.out.println("Wrong!");
printScore();
}
private void printScore() {
System.out.println(INDENTAION + "Score: " + counter +"/"+ TOTAL_POINTS);
}
public void firstLevel() {
System.out.println("What is the tenth digit of PI?");
int awnser = input.nextInt();
if (awnser == 5) {
answerCorrect();
}else{
answerWrong();
}
}
public void secondlevel() {
System.out.println("a king and queen get on a boat. then the boat sinks. how many people are alive");
String awnser = input.nextLine();
if (awnser.equals("two") || awnser.equals("2")) {
answerCorrect();
} else {
answerWrong();
}
}
}

string whitespace throwing errors in a object array

i am trying to enter a book title "hoopa doopa"into my object array. when i try it throws a java.util.InputMismatchException.If i enter a string that has no spaces like"hoopa" the code will run fine all of the way through. What is causing this and how can I fix it? please help thanks
import java.io.*;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int counter = 0;
int numberOfProducts=0; //variable for when the user is asked to enter input the number of products to be entered
do { //this will validate the user input
System.out.println("How many products would you like to enter");
while (!input.hasNextInt()) {
System.out.println("That's not a number!");
input.next(); // this is important!
}
numberOfProducts = input.nextInt();
} while (numberOfProducts <= 0);
//end of the do while loop
Products[] products;
products = new Products[numberOfProducts+4];//create a array the size of the user input that was gathered
for (int i=0;i<numberOfProducts;i++)
{
products[i+4]= new Products(); // create each actual Person
System.out.println("What is the product #: ");
products[i+4].setItemNumber(input.nextInt());
System.out.println("What is the book name: ");
products[i+4].setNameOfProduct(input.next());
System.out.println("How many are in stock: ");
products[i+4].setUnitsInStock(input.nextInt());
System.out.println("What is the cost of the Item: ");
products[i+4].setPrice(input.nextDouble());
counter++;
}
products[0] = new Products(0001,"The Red Rose",1,29.99);
products[1] = new Products(0002,"The Bible",3,11.99);
products[2] = new Products(0003,"End of the Programm",2,29.99);
products[3] = new Products(0004,"WHAT!!! the....",1,129.99);
//____________________________________________________________4 products that are already made
for (int i=0;i<numberOfProducts+4;i++)
{
System.out.println(products[i].toString());
input.nextLine();
}
}
}
this is the other class
import java.text.NumberFormat;
public class Products
{
private int itemNumber;
private String nameOfProduct;
private int unitsInStock;
private double unitPrice;
public Products()
{
itemNumber = 0;
nameOfProduct = null;
unitsInStock = 0;
unitPrice = 0.0;
}
public Products(int num,String name,int inStock,double price)
{
itemNumber = num;
nameOfProduct = name;
unitsInStock = inStock;
unitPrice = price;
}
public int getItemNumber()
{
return itemNumber;
}
public void setItemNumber(int newValue)
{
itemNumber=newValue;
}
//----------------------------------------------
public String getNameOfProduct()
{
return nameOfProduct;
}
public void setNameOfProduct(String newValue)
{
nameOfProduct=newValue;
}
//----------------------------------------------
public int getUnitsInStock()
{
return unitsInStock;
}
public void setUnitsInStock(int newValue)
{
unitsInStock = newValue;
}
//-----------------------------------------------
public double getPrice()
{
return unitPrice;
}
public void setPrice(double newValue)
{
unitPrice = newValue;
}
//_______________________________________________
public double calculateTotalItemValue() //method that uses quantity on hand and price part3 1.A
{
return getUnitsInStock()* getPrice();
}//end of method
#Override
public String toString()
{
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
return"\nItem Number: "+getItemNumber() +
"\nItem Name: "+getNameOfProduct()+
"\nItem Quantity: " +getUnitsInStock()+
"\nItemPrice:" +currencyFormat.format(getPrice())
+"\nValue of Inventory: " +currencyFormat.format(this.calculateTotalItemValue());//part3 1.B
}
}
The Scanner sees the space in the book name as a delimiter since you are using the next() method. So when you go to read the nextInt() for the stock amount, the Scanner index is after the space in the book name String, and pulls in the remaining String data, which doesn't convert to an int. Instead, try something like this:
System.out.println("What is the book name: ");
input.nextLine();
products[i+4].setNameOfProduct(input.nextLine());
If you do not add the input.nextLine();, then it will appear as though the book name prompt gets skipped.
Scanner input = new Scanner(System.in);
Actually you are using scanner to get input and by default scanner delimiter is space. So you have to change the default delimiter of your code.
I think this is your problem:
products[i+4].setNameOfProduct(input.next());
What input.next() does is it reads the input from the user, until it reaches white space (the space between hoopa doopa). The function then passes hoopa to the setNameOfProduct method, and then passes doopa to the nextInt function, which gives a runtime error.
To fix your problem I would code
products[i+4].setNameOfProduct(input.nextLine());
Edit:
nextLine() function passes all characters up to the carriage return
Problem :
products[i+4].setNameOfProduct(input.next());
Solution 1 :
Just create another Scanner object for reading input with spaces
Scanner sc1=new Scanner(System.in);
products[i+4].setNameOfProduct(sc1.nextLine());
Solution 2 :
Or to use same scanner object
input.nextLine(); //Include this line before getting input string
products[i+4].setNameOfProduct(input.nextLine());

Running a loop again and passing the control to Main class in Java after output

I am trying to make a simple JAVA program that will help a user select a car of his choice.
public class CarSelector {
static CarSelector start = new CarSelector();
public String BodyType(String a){
String hatchBack, SUV, MUV, compactSedan, sedan, saloon, miniVan, convertible, hybrid, coupe;
if(a.equalsIgnoreCase("a")){
hatchBack = "polo";
System.out.println("We recommend: " +hatchBack);
}
String b = "";
if(a.equalsIgnoreCase("b")){
SUV = "Fortuner";
System.out.println("We recommend: " +SUV);
}
if(a.equalsIgnoreCase("c")){
compactSedan = "Amaze";
System.out.println("We recommend: " +compactSedan);
}
if(a.equalsIgnoreCase("d")){
sedan = "Vento";
System.out.println("We recommend: " +sedan);
}
if(a.equalsIgnoreCase("e")){
saloon = "Corolla";
System.out.println("We recommend: " +saloon);
}
if(a.equalsIgnoreCase("f")){
MUV = "Innova";
System.out.println("We recommend: " +MUV);
}
else{
System.out.println("Incorrect choice.");
System.out.println(a);
//start.BodyType(a);
return null;
}
System.out.println("We recommend: " +a);
return null ;
}
public int PriceRange(){
int price5 = 5;
int price10 = 10;
int price15 = 15;
int price20 = 20;
int price25 = 25;
int price30 = 30;
return 0 ;
}
public String SegmentBest(){
//string type of the best cars within price range
return null;
}
public int OnRoadPrice(){
//return int of on road price
return 0;
}
public String Manufacturer(){
//all manufacturers with their models available
String Toyota, Volkswagen, Honda;
String i1= "Toyota";
String i2= "Volkswagen";
String i3= "Honda";
return null;
}
public int SeatingCapacity(){
//return integer seating capacity
return 0;
}
public String ReviewLink(){
return null;
}
public String LatestReleases(){
return null;
}
public String FuelType(){
return null;
}
public static void main (String[] args){
Scanner input = new Scanner(System.in);
String option;
System.out.println("Welcome to car selector: ");
System.out.println("Choose according to: ");
System.out.println("A:Body Type");
System.out.println("B: Manufacturer");
System.out.println("C: Price Range");
option = input.nextLine();
if( option.equalsIgnoreCase("a")){
System.out.println("A: Hatchback");
System.out.println("B: SUV");
System.out.println("C: MUV");
System.out.println("D: Sedan");
System.out.println("E: Saloon");
System.out.println("F: Compact Sedan");
String optionA = input.nextLine();
start.BodyType(optionA);
}
}
}
The code is simple. A walkthrough: The main class will prompt the user to make a choice of how he wants to choose a car. Given option "A" as a choice will run the first method. Here are my queries
Within the BodyType method, I would like to run the set of IF statements again if the user enters anything other than a,b,c,d,e,f
How can I hand the control back to the main class (run a specific code from MAIN method) and also start a method from another method (from BodyType to PriceRange). I hope I was clear. Thanks, Cheers!
you can play it now...
import java.util.Scanner;
public class CarSelector {
static CarSelector start = new CarSelector();
static String[] bodytypes = new String[]{"hatchBack", "SUV", "MUV", "compactSedan", "sedan",
"saloon", "miniVan", "convertible", "hybrid", "coupe"};
static String[] manufacturers = new String[]{"Toyota", "Volkswagen", "Honda"};
private String getBodyType(int bt) {
if(bt >= bodytypes.length){
System.err.println("Incorrect choice.");
return null;
}else{
System.out.println("We recommend: " + bodytypes[bt]);
return bodytypes[bt];
}
}
public static String getManufacturer(int mf) {
if(mf >= manufacturers.length){
System.err.println("Incorrect choice.");
return null;
}else{
System.out.println("We recommend: " + manufacturers[mf]);
return manufacturers[mf];
}
}
public static void main(String[] args) {
String bodyType = "";
String manufacturer = "";
Scanner input = new Scanner(System.in);
String option;
System.out.println("Welcome to car selector: ");
System.out.println("Choose according to: ");
pringSelectType();
option = input.nextLine();
while(!option.equalsIgnoreCase("o")){
if (option.equalsIgnoreCase("a")) {
for(int a = 0; a < bodytypes.length ; a++){
System.out.println(a+": "+ bodytypes[a]);
}
option = input.nextLine();
bodyType = start.getBodyType(Integer.parseInt(option));
pringSelectType();
option = input.nextLine();
}else if (option.equalsIgnoreCase("b")) {
for(int a = 0; a < manufacturers.length ; a++){
System.out.println(a+": "+ manufacturers[a]);
}
option = input.nextLine();
manufacturer = getManufacturer(Integer.parseInt(option));
pringSelectType();
option = input.nextLine();
}else{
option = input.nextLine();
System.err.println(("input a right choice"));
pringSelectType();
option = input.nextLine();
}
}
System.out.println("");
System.out.println("it's your choice below: ");
System.out.println("bodyType : "+ bodyType);
System.out.println("manufacturer : "+ manufacturer);
}
private static void pringSelectType() {
System.out.println("A:Body Type");
System.out.println("B: Manufacturer");
System.out.println("C: Price Range");
}
}
i delete some unused method,and change some code.
i don't make any note,cause i think it's easy enough..
if u have some problem,comment it,i will see.
PS:when u want to over the select system,input o.it will be done.

Categories

Resources