Can i take userinput in a method java class? - java

public static void userinput() {
System.out.print("Enter your name : ");
Scanner d = new Scanner(System.in);
String username = d.next();
System.out.print("\nEnter your Age : ");
Scanner a = new Scanner(System.in);
int Age = a.nextInt();
System.out.print("\nEnter your roll number : ");
Scanner b = new Scanner(System.in);
int rollno = b.nextInt();
System.out.print("\nEnter your city : ");
Scanner c = new Scanner(System.in);
String city = c.nextLine();
System.out.println("Hello, " + username + " your age is " + Age + " you live in " + city + " and your roll number is " + rollno);
return (0);
}
Is this the correct way to take input from a user in the method?

Here is the corrected version :
public static void userinput() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name : ");
String username = sanner.nextLine();//as next() reads only a word
System.out.print("\nEnter your Age : ");
int age = Integer.parseInt(scanner.nextLine());//as nextInt() does not read the \n which may cause next string inputs to be null
System.out.print("\nEnter your roll number : ");
int rollno = Integer.parseInt(scanner.nextLine());
System.out.print("\nEnter your city : ");
String city = scanner.nextLine();
System.out.println("Hello, " + username + " your age is " + Age + " you live in " + city + " and your roll number is " + rollno);
//a void function doesn't compulsorily need a return statement
}
Also only one Scanner is enough!

Related

how do I pass a user inputted integer through methods?

Essentially i've isolated the issue, the int numpersons begins as 0. I take a user input to make it a particular number which is the array size, when the second method begins it takes the 0 again and then the array has an out of bounds exception. I want to pass it from one method to the next, or make them more successive, idk how to do this
thanks in advance
import java.util.Scanner;
public class BankApp {
Scanner input = new Scanner(System.in);
int numpersons = 0;
private SavingsAccount[] clients = new SavingsAccount[numpersons];
public BankApp() {
while (numpersons < 1) {
System.out.println("How many people are there?");
numpersons = input.nextInt();
if (numpersons < 1 || 2147483647 < numpersons) {
System.out.println("invalid number, please enter again");
}
}
input.nextLine();
}
public void addClients() {
int i = 0;
while (i < numpersons) {
System.out.println("enter account id " + (i + 1));
String AccountID = input.nextLine();
System.out.println("enter account name " + (i + 1));
String AccountName = input.nextLine();
System.out.println("enter account balance " + (i + 1));
Double AccountBalance = input.nextDouble();
clients[i] = new SavingsAccount(AccountID, AccountName, AccountBalance);
input.nextLine();
i++;
}
}
public void displayClients() {
int i = 0;
while (i < numpersons) {
System.out.println("======================================");
System.out.println("Account ID " + (i + 1) + ": " + clients[i].getID());
System.out.println("Account Name " + (i + 1) + ": " + clients[i].getName());
System.out.println("Account Balance " + (i + 1) + ": " + clients[i].getBalance());
System.out.println("======================================");
i++;
}
}
public static void main(String args[]) {
BankApp ba = new BankApp();
ba.addClients();
ba.displayClients();
}
}

Compiler says cannot find symbol [duplicate]

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 3 years ago.
Compiler throws an exception saying:
Cannot find symbol p and x
This program takes user input and prints as per the loop condition. While compiling it throws an error that it cannot find the symbol.
import java.util.Scanner;
class Puppy{
String name;
String breed;
String gender;
int weight;
int age;
int loud;
void hammer()
{
System.out.println("Enter your Dogs name :");
p[x].name = user_input.next();
System.out.println("Enter your Dogs Breed :");
p[x].breed = user_input.next();
System.out.println("Enter your Dogs Gender :");
p[x].gender = user_input.next();
System.out.println("Enter your Dogs weight in Kg:");
p[x].weight = user_input.nextInt();
System.out.println("Enter your Dogs age :");
p[x].age = user_input.nextInt();
System.out.println("Rate your Dogs Loudness out of 10 :");
p[x].loud = user_input.nextInt();
}
void jammer()
{
System.out.println("Hello my name is" + " " + p[x].name);
System.out.println("I am a" + " " + p[x].breed);
System.out.println("I am" + " " + p[x].age + " " + "years old" + " " + p[x].gender);
System.out.println("I weigh around" + " " + p[x].weight + " " + "kg's");
System.out.println("I sound this loud" + " " + p[x].loud);
}
}
class PuppyTestDrive
{
public static void main(String []args)
{
Scanner user_input = new Scanner(System.in);
int x = 0;
Puppy[] p = new Puppy[4];
while(x < 4)
{
p[x] = new Puppy();
p[x].hammer();
p[x].jammer();
x = x + 1;
}
}
}
Your program should work with the following code:
import java.util.Scanner;
class Puppy{
String name;
String breed;
String gender;
int weight;
int age;
int loud;
void hammer()
{
Scanner user_input = new Scanner(System.in);
System.out.println("Enter your Dogs name :");
this.name = user_input.next();
System.out.println("Enter your Dogs Breed :");
this.breed = user_input.next();
System.out.println("Enter your Dogs Gender :");
this.gender = user_input.next();
System.out.println("Enter your Dogs weight in Kg:");
this.weight = user_input.nextInt();
System.out.println("Enter your Dogs age :");
this.age = user_input.nextInt();
System.out.println("Rate your Dogs Loudness out of 10 :");
this.loud = user_input.nextInt();
}
void jammer()
{
System.out.println("Hello my name is" + " " + this.name);
System.out.println("I am a" + " " + this.breed);
System.out.println("I am" + " " + this.age + " " + "years old" + " " + this.gender);
System.out.println("I weigh around" + " " + this.weight + " " + "kg's");
System.out.println("I sound this loud" + " " + this.loud);
}
}
class PuppyTestDrive {
public static void main(String []args)
{
int x = 0;
Puppy[] p = new Puppy[4];
while(x < 4)
{
p[x] = new Puppy();
p[x].hammer();
p[x].jammer();
x = x + 1;
}
}
}

Looping program back to ''menu''

I just writed this program, it is to train myself for the upcomming exam this monday.
A thing i would like to add is: after a user is done with one of the exchange options 1/2/3 i would like to give the option to let the user return to the beginning welcome to the money exchange! etc.....
i have tried some a for loop and a while loop but i couldn't get it to work.
Would be cool if after the money exchange process that the user get the option to return to the beginning by typing y or n is this possible?
/* This program is written as a excercise to prep myself for exams.
* In this program the user can:
* 1. Select a currency (other than euro's)
* 2. Input the amount of money
* 3. transfer the amount of currency to euro's
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(" Welcome to the money exchange! \n Please pick one of the currencies by useing 1 / 2 / 3 \n \n 1 = US dollar \n 2 = GB pounds \n 3 = Yen \n ");
System.out.print("Input : ");
DecimalFormat df = new DecimalFormat() ;
df.setMaximumFractionDigits(2);
int choice = input.nextInt() ;
double transfee = 2.41 ;
double USrate = 0.9083 ;
double GBrate = 1.4015 ;
double YENrate = 0.0075 ;
if (choice > 3 || choice < 1) {
System.out.println("Invalid input!...... Please try agian\n");
} else {
if(choice == 1) {
System.out.println("You have choosen for US dollar \n");
System.out.print("Please enter amount US dollar: ");
double USamount = input.nextDouble() ;
double deuros = USamount * USrate ;
double ddisburse = deuros - transfee ;
System.out.print("\nInput amount US dollar:. " + USamount + "\n");
System.out.print("Worth in euro's:........ " + df.format(deuros) + "\n");
System.out.print("Transfer cost:.......... " + transfee + "\n");
System.out.print("Amount to disburse:..... " + df.format(ddisburse) + "\n" );
}else {
if(choice == 2){
System.out.println("You have choosen for GB pounds");
System.out.print("Please enter amount GB ponds: ");
double GBamount = input.nextDouble();
double geuros = GBamount * GBrate ;
double gdisburse = geuros - transfee;
System.out.print("\nInput amount GB pound:. " + GBamount + "\n");
System.out.print("Worth in euro's........ " + df.format(geuros) + "\n");
System.out.print("Transfer cost:......... " + transfee + "\n");
System.out.print("Amount to disburse:.... " + df.format(gdisburse) + "\n");
}else {
if(choice == 3){
System.out.println("You have choosen for Yen");
System.out.print("Please enter amount Yen: ");
double YENamount = input.nextDouble();
double yeuros = YENamount * YENrate ;
double ydisburse = yeuros - transfee ;
System.out.print("\nInput amount Yen:... " + YENamount + "\n");
System.out.print("Worth in euro's..... " + df.format(yeuros) + "\n");
System.out.print("Transfer cost:...... " + transfee + "\n");
System.out.print("Amount to disburse:. " + df.format(ydisburse) + "\n");
}
}
}
}
}
}
You could wrap your program with a while loop, which checks if the user entered 'y' at the end like this:
import java.text.DecimalFormat;
import java.util.Scanner;
class YourClassName
{
public static void main(String[] args)
{
boolean askAgain = true;
while (askAgain)
{
Scanner input = new Scanner(System.in);
System.out.println(
" Welcome to the money exchange! \n Please pick one of the currencies by useing 1 / 2 / 3 \n \n 1 = US dollar \n 2 = GB pounds \n 3 = Yen \n ");
System.out.print("Input : ");
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
int choice = input.nextInt();
double transfee = 2.41;
double USrate = 0.9083;
double GBrate = 1.4015;
double YENrate = 0.0075;
if (choice > 3 || choice < 1)
{
System.out.println("Invalid input!...... Please try agian\n");
} else
{
if (choice == 1)
{
System.out.println("You have choosen for US dollar \n");
System.out.print("Please enter amount US dollar: ");
double USamount = input.nextDouble();
double deuros = USamount * USrate;
double ddisburse = deuros - transfee;
System.out.print(
"\nInput amount US dollar:. " + USamount + "\n");
System.out.print("Worth in euro's:........ "
+ df.format(deuros) + "\n");
System.out.print(
"Transfer cost:.......... " + transfee + "\n");
System.out.print("Amount to disburse:..... "
+ df.format(ddisburse) + "\n");
} else
{
if (choice == 2)
{
System.out.println("You have choosen for GB pounds");
System.out.print("Please enter amount GB ponds: ");
double GBamount = input.nextDouble();
double geuros = GBamount * GBrate;
double gdisburse = geuros - transfee;
System.out.print(
"\nInput amount GB pound:. " + GBamount + "\n");
System.out.print("Worth in euro's........ "
+ df.format(geuros) + "\n");
System.out.print(
"Transfer cost:......... " + transfee + "\n");
System.out.print("Amount to disburse:.... "
+ df.format(gdisburse) + "\n");
} else
{
if (choice == 3)
{
System.out.println("You have choosen for Yen");
System.out.print("Please enter amount Yen: ");
double YENamount = input.nextDouble();
double yeuros = YENamount * YENrate;
double ydisburse = yeuros - transfee;
System.out.print("\nInput amount Yen:... "
+ YENamount + "\n");
System.out.print("Worth in euro's..... "
+ df.format(yeuros) + "\n");
System.out.print(
"Transfer cost:...... " + transfee + "\n");
System.out.print("Amount to disburse:. "
+ df.format(ydisburse) + "\n");
}
}
}
}
System.out.println("Do you want to do another calculation? (y/n)");
String againAnswer = input.next();
askAgain = againAnswer.equalsIgnoreCase("y");
}
}
}
Setting the boolean variable to true first lets you enter the loop. The user will be asked as long as he types an y at the end. Every other character would exit the loop:
String againAnswer = input.next();
askAgain = againAnswer.equalsIgnoreCase("y");
You could also check for explicit n, but that is up to you.
Put the code inside a while loop (while(true)). At the end of each if block
add one nested if.
System.out.print(Do you want to continue?");
if(in.next().equals("Y")) {
continue;
}
And you have add one extra menu(4th) for exit :
if(choice == 4){
break;
}

Java string not showing when run [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 8 years ago.
I can't seem to figure out why the string college doesn't show when I run this. There are no errors when I compile it. What am I doing wrong? Everything else is working. It's probably an easy fix, but I'm new and just starting to learn Java.
import java.util.Scanner;
public class story_a_holloway{
public static void main(String[] args){
String name;
String city;
int age;
String college;
String profession;
String animal;
String petname;
Scanner keyboard = new Scanner(System.in);
// Get name
System.out.print("What is your name? ");
name = keyboard.nextLine();
// Get city
System.out.print("What city do you live in? ");
city = keyboard.nextLine();
// Get age
System.out.print("What is your age? ");
age = keyboard.nextInt();
// Get college
System.out.print("What college do you attend? ");
college = keyboard.nextLine();
keyboard.nextLine();
// Get profession
System.out.print("What is your profession? ");
profession = keyboard.nextLine();
// Get animal
System.out.print("What is your favorite animal? ");
animal = keyboard.nextLine();
// Get pet name
System.out.print("What would you name your pet? ");
petname = keyboard.nextLine();
System.out.println("There once was a person named " + name + " who lived in " + city + ". At the age of " + age + ", " + name + " went to college at " + college + ". " + name + " graduated and went to work as a " + profession + ". Then " + name + " adopted a(n) " + animal + " named " + petname + ". They both lived happily ever after!");
}
}
Call keyboard.nextLine() after age = keyboard.nextInt();.
Currently int value is read as age and college = keyboard.nextLine(); reads the remainder of the line which container your int, which is empty. So the correct form should be:
// Get age
System.out.print("What is your age? ");
age = keyboard.nextInt();
keyboard.nextLine();
// Get college
System.out.print("What college do you attend? ");
college = keyboard.nextLine();
Other possible solution to avoid the extra call to nextLine() is reading the whole line as a String and then parsing that String to an integer, for example:
age = Integer.parseInt(keyboard.nextLine());
Put keyboard.nextLine() after this line:
int age=keyboard.nextInt();
This is a common problem that usually happens when you use nextLine() method after nextInt() method of Scanner class.
What actually happens is that when the user enters an integer at int age = keyboard.nextInt();, the scanner will take the digits only and leave the new-line character \n. So you need to do a trick by calling keyboard.nextLine(); just to discard that new-line character and then you can call String college = keyboard.nextLine(); without any problem.
this is taken from Reading Strings next() and nextLine() Java
The problem with your code is using nextLine() after nextInt() & you have an additional nextLine()
// Get age
System.out.print("What is your age? ");
age = keyboard.nextInt();
// Get college
System.out.print("What college do you attend? ");
college = keyboard.nextLine();
keyboard.nextLine(); --> this line
// Get profession
System.out.print("What is your profession? ");
profession = keyboard.nextLine();
What you should do is :
// Get age
System.out.print("What is your age? ");
age = keyboard.nextInt();
keyboard.nextLine(); -->add this line
// Get college
System.out.print("What college do you attend? ");
college = keyboard.nextLine();
// keyboard.nextLine(); --> remove this line
// Get profession
System.out.print("What is your profession? ");
profession = keyboard.nextLine();
A better way of doing it would be : (read about Integer.pasrseInt(String))
// Get age
System.out.print("What is your age? ");
age = Integer.parseInt(keyboard.nextLine());
import java.util.Scanner;
public class story_a_holloway{
public static void main(String[] args){
String name;
String city;
int age;
String profession;
String animal;
String petname;
String college;
Scanner keyboard = new Scanner(System.in);
// Get name
System.out.print("What is your name? ");
name = keyboard.nextLine();
// Get city
System.out.print("What city do you live in? ");
city = keyboard.nextLine();
// Get age
System.out.print("What is your age? ");
age = Integer.parseInt(keyboard.nextLine());
// Get college
System.out.print("What college do you attend? ");
college = keyboard.nextLine();
// Get profession
System.out.print("What is your profession? ");
profession = keyboard.nextLine();
// Get animal
System.out.print("What is your favorite animal? ");
animal = keyboard.nextLine();
// Get pet name
System.out.print("What would you name your pet? ");
petname = keyboard.nextLine();
System.out.println(college);
System.out.println("There once was a person named " + name + " who lived in " + city + ". At the age of " + age + ", " + name + " went to college at " + college + ". " + name + " graduated and went to work as a " + profession + ". Then " + name + " adopted a(n) " + animal + " named " + petname + ". They both lived happily ever after!");
}
}

Get method returns null

So I tried to make a Hanger program in Java, and when I try to get to output a variable using a get method, it returns null. I first set up a Scanner object, then I set a String to the value the user inputs, then I use a set method to set the String to a new variable, finally, I call that new variable using the get method. It returns null, and I don't know why.
import java.util.Scanner;
public class Hanger
{
public String word;
public Hanger(){}
public void setWord(String new_word)
{
new_word = word;
}
public String getWord()
{
return word;
}
public static void main(String[] args)
{
Scanner input_names = new Scanner(System.in);
Scanner input_word = new Scanner(System.in);
Hanger word1 = new Hanger();
System.out.println("Please enter Player 1's name.");
String name1 = input_names.nextLine();
System.out.println("Please enter Player 2's name.");
String name2 = input_names.nextLine();
System.out.println("Are your names " + name1 + " and " + name2 + "?");
String names_correct = input_names.nextLine();
switch (names_correct)
{
case "no":
{
System.out.println("Please enter Player 1's name.");
name1 = input_names.nextLine();
System.out.println("Please enter Player 2's name.");
name2 = input_names.nextLine();
System.out.println("Are your names " + name1 + " and " + name2 + "?");
names_correct = input_names.nextLine();
}
case "No":
{
System.out.println("Please enter Player 1's name.");
name1 = input_names.nextLine();
System.out.println("Please enter Player 2's name.");
name2 = input_names.nextLine();
System.out.println("Are your names " + name1 + " and " + name2 + "?");
names_correct = input_names.nextLine();
}
default:
{
break;
}
}
System.out.println("Let's begin! " + name1 + ", please type a word that " + name2 + " will try to guess.");
String input_word1 = input_word.nextLine();
word1.setWord(input_word1);
System.out.println("Is " + word1.getWord() + " correct?");
}
}
It should be this.word=new_word in your setWord method of Hanger class

Categories