So I'm a beginner in Java right now and I've been playing around with strings a bit. Now I'd like to give the user an input choice "Enter a or b: " and give an output based on either "a" or "b"
The Code:
int a = 18;
int b = 22;
Scanner user_input = new Scanner (System.in);
String first_name;
System.out.println("Enter your first name: ");
first_name = user_input.next();
String last_name;
System.out.println("Enter your last name: ");
last_name = user_input.next();
String full_name;
full_name = first_name + " " + last_name;
System.out.println("You are: " + full_name);
String age;
System.out.println("Enter a or b: ");
age = user_input.next();
String age_a;
System.out.println("Your age is 18");
age = user_input(a);
I was also thinking maybe a function could be used like:
if(user_input = a)
{
System.out.println("Your age is 18.");
}
Once you have age you must check the value, but as it is a String you MUST use String.equals()
if (age.equals("a"))
System.out.println("Your age is 18");
else
System.out.println("Your age is 22");
If you want to check the answer is ONLY a or b use a while loop to repeat the question until answer is the desired:
String age;
while (!age.equals("a") || !age.equals("b")) {
// ask for age
}
You can use an if with "string".equals("other_string") to compare them:
int a = 18;
int b = 22;
Scanner user_input = new Scanner (System.in);
System.out.println("Enter your first name: ");
String first_name = user_input.next();
System.out.println("Enter your last name: ");
String last_name = user_input.next();
String full_name = first_name + " " + last_name;
System.out.println("You are: " + full_name);
System.out.println("Enter a or b: ");
String ageChoice = user_input.next();
String age = null;
if(ageChoice.equals("a")){
age = String.valueOf(a);
}
else if(ageChoice.equals("b")){
age = String.valueOf(b);
}
System.out.println("Your age is: " + age);
Related
I have the error of bad operand types for binary operator '<' I'm not sure how to fix it. I'm very new to coding so I only really know the basics.
import java.util.Scanner;
public class HowOldAreYou
{
public static void main(String args[])
{
int myAge = 16;
Scanner user_input = new Scanner(System.in);
String userName;
System.out.print("What is your name? ");
userName = user_input.next();
String userAge;
System.out.print("How old are you? ");
userAge = user_input.next();
System.out.println("-----------------------");
System.out.print("Your name is: " + userName);
System.out.println();
System.out.print("You are " + userAge + " years old.");
System.out.println();
System.out.println("You are older than me: " + (myAge < userAge));
}
}
You cant compare String to int , you need to get a int from the user and not a string , int is used for numbers that do not start with 0, for example age / price / year:
int myAge = 16;
Scanner user_input = new Scanner(System.in);
String userName;
System.out.print("What is your name? ");
userName = user_input.next();
int userAge;
System.out.print("How old are you? ");
userAge = user_input.nextInt();
System.out.println("-----------------------");
System.out.print("Your name is: " + userName);
System.out.println();
System.out.print("You are " + userAge + " years old.");
System.out.println();
System.out.println("You are older than me: " + (myAge < userAge));
Output :
What is your name? Pluto
How old are you? 20
-----------------------
Your name is: Pluto
You are 20 years old.
You are older than me: true
So your issue if you are comparing an integer with a string, which cannot compare directly. The change I made should resolve this
public class HowOldAreYou
{
public static void main(String args[])
{
int myAge = 16;
Scanner user_input = new Scanner(System.in);
String userName;
System.out.print("What is your name? ");
userName = user_input.next();
**int userAge;**
System.out.print("How old are you? ");
**userAge = Integer.parseInt(user_input.next());**
System.out.println("-----------------------");
System.out.print("Your name is: " + userName);
System.out.println();
System.out.print("You are " + userAge + " years old.");
System.out.println();
System.out.println("You are older than me: " + (myAge < userAge));
}
}
How do I change this code to make it get Age from Local Date instead of using "what is the current year"?
this is what i have so far:
//----------------------------------------------------------------
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
try {
System.out.println("Please enter your name: ");
String name = input.nextLine();
System.out.println("Please enter your birth date: ");
String date = input.nextLine();
System.out.println("please enter your birth month:");
String month = input.nextLine();
System.out.println("please enter your birth year:");
String year = input.nextLine();
System.out.println("please enter current year:");
String cYear = input.nextLine();
int bDate = Integer.parseInt(date);
int bMonth = Integer.parseInt(month);
int bYear = Integer.parseInt(year);
int ccYear = Integer.parseInt(cYear);
int age = ccYear - bYear;
int totalMonth = 12;
int yourMonth = totalMonth - bMonth;
System.out.println(" Hi " + name + " your are " + age + " years ");
} catch(Exception e) {
System.out.println("");
}
}
It's possible to get the current year using the standard Calendar API.
int year = Calendar.getInstance().get(Calendar.YEAR);
From there, you just need to plug that into the right place in your code.
Here's my code, it's at the bottom that I don't know what to do to format it properly, I tried using printf but it keeps giving me errors whenever I try to reformat it and it doesn't want to go through, does anyone have any suggestions as to how to get the users' first and last name under "users", their balance under "balance and etc?
package mybalances;
import java.util.Scanner;
import static oracle.jrockit.jfr.events.Bits.doubleValue;
/**
*
* #author carroyo108
*/
public class MyBalances {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
//first user
System.out.print("Enter user 1 first name:");
String firstFirst = keyboard.nextLine();
System.out.print("Enter user 1 last name: ");
String firstLast = keyboard.nextLine();
System.out.print("User 1, Account 1 Name: ");
String firstaccountOne = keyboard.nextLine();
System.out.print("User 1, Account 1 Balance: ");
double firstbalanceOne = keyboard.nextDouble();
System.out.print("User 1, Account 2 Name: ");
String firstaccountTwo = keyboard.nextLine();
keyboard.nextLine();
System.out.print("User 1, Account 2 Balance: ");
double firstbalanceTwo = keyboard.nextDouble();
keyboard.nextLine();
System.out.print("\n");
System.out.print("User 2 First Name: ");
String secondFirst = keyboard.nextLine();
System.out.print("User 2 Last Name: ");
String secondLast = keyboard.nextLine();
System.out.print("User 2, Account 1 Name: ");
String secondaccountOne = keyboard.nextLine();
System.out.print("User 2 Account 1 Balance: ");
double secondbalanceOne = keyboard.nextDouble();
System.out.print("User 2, Account 2 Name: ");
String secondaccountTwo = keyboard.nextLine();
keyboard.nextLine();
System.out.print("User 2, Account 2 Balance: ");
double secondbalanceTwo = keyboard.nextDouble();
System.out.print("\n");
//Third user inputs
System.out.print("User 3 First Name: ");
String thirdFirst = keyboard.nextLine();
keyboard.nextLine();
System.out.print("User 3 Last Name: ");
String thirdLast = keyboard.nextLine();
System.out.print("User 3, Account 1 Name: ");
String thirdaccountOne = keyboard.nextLine();
System.out.print("User 3, Account 1 Balance: ");
double thirdbalanceOne = keyboard.nextDouble();
System.out.print("User 3, Account 2 Name: ");
String thirdaccountTwo = keyboard.nextLine();
keyboard.nextLine();
System.out.print("User 3, Account 2 Balance: ");
double thirdbalanceTwo = keyboard.nextDouble();
keyboard.nextLine();
System.out.print("\n");
double firstusertotalCost = ((firstbalanceOne + firstbalanceTwo) / 2);
double secondusertotalCost = ((secondbalanceTwo + secondbalanceTwo) / 2);
double thirdusertotalCost = ((thirdbalanceTwo + thirdbalanceTwo) / 2);
System.out.printf("Users" + " " + "Account" + " " + "Balance" + " " + "Account" + " " + "Balance" + " " + "Average" + " " + "Status\n");
System.out.printf(("%5d",10) + firstLast,firstFirst);
}
}
You can use string concatenation by overloading the '+' operator
System.out.print("Users" + firstFirst + " " + firstLast + " Account " + firstaccountOne);
Your code shows very poor practices as there is a lot of repeating code. I would suggest using a loop condition (while/for loop) and try store your inputs from the user in a data structure like an array.
I am getting null output along when i am getting to string method in my program output.
//Main Method
package studentDatabaseApp;
import java.util.Scanner;
public class StudentDatabaseApp {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter number of Students: ");
int numOfStudents = scan.nextInt();
Student[] students = new Student[numOfStudents];
for(int n =0; n < numOfStudents; n++) {
students[n] = new Student();
students[n].enroll();
students[n].payTution();
}
for(int n =0; n < numOfStudents; n++) {
System.out.println(students[n].toString());
}
}
}
//Student Class Code
package studentDatabaseApp;
import java.util.Scanner;
public class Student {
private String firstName;
private String lastName;
private int gradeYear = 0;
private String studentID;
private String courses;
private static int courseCost = 600;
private int tutionBalance = 0;
private static int id = 1000;
//Constructor to enter student name and year for each student
public Student() {
Scanner scan = new Scanner(System.in);
System.out.print("Enter Student First Name: ");
this.firstName = scan.nextLine();
System.out.print("Enter Student Last Name: ");
this.lastName = scan.nextLine();
System.out.print("1 - Freshmen\n2 - Sophmore\n3 - Junior\n4 - Senior\nEnter Student Grade Year: ");
this.gradeYear = scan.nextInt();
//Setting student id
setStudentID();
}
//Unique id and student grade level
private void setStudentID() {
id++;
this.studentID = gradeYear + "" + id;
}
//Create courses so student can enroll
public void enroll() {
do {
System.out.print("Enter course to enroll (Q to Quit): ");
Scanner in = new Scanner(System.in);
String course = in.nextLine();
if(!course.equals("Q")) {
courses = courses + ", " + course;
tutionBalance = tutionBalance + courseCost;
}
else {
break;
}
}while(1 != 0);
}
//Student should able to view their balance and pay the tution
public void viewBalance() {
System.out.println("BALANCE TOTAL: " + tutionBalance);
}
//Total balance
public void payTution() {
viewBalance();
Scanner scan = new Scanner(System.in);
System.out.print("\nEnter your payment: ");
int tutionPaid = scan.nextInt();
tutionBalance = tutionBalance - tutionPaid;
viewBalance();
}
//Student status with their name, ID, course enrolled and balance
#Override
public String toString() {
return "\nSTUDENT NAME: " + firstName + " " + lastName +
"\nGRADE LEVEL: " + gradeYear + " " + "\nSTUDENT ID: " + studentID +
"\nCOURSES ENROLLED: " + courses +
"\nTUTION BALANCE: " + tutionBalance;
}
}
//Console Output
Enter number of Students: 1
Enter Student First Name: bilal
Enter Student Last Name: mujahid
1 - Freshmen
2 - Sophmore
3 - Junior
4 - Senior
Enter Student Grade Year: 4
Enter course to enroll (Q to Quit): Eng 101
Enter course to enroll (Q to Quit): Math 101
Enter course to enroll (Q to Quit): Q
BALANCE TOTAL: 1200
Enter your payment: 1000
BALANCE TOTAL: 200
STUDENT NAME: bilal mujahid
GRADE LEVEL: 4
STUDENT ID: 41001
COURSES ENROLLED: null, Eng 101, Math 101
TUTION BALANCE: 200
The problem is with
private String courses;
You use
courses = courses + course;
Courses is null since it is never initialized. Try changing it to
private String courses = “”;
(This will cause it to have a extra comma in the beginning which you can easily just substring off)
Initialise it with course the first time
if(!course.equals("Q")) {
courses = coursers == null ? course : courses + ", " + course;
...
In my code I am to input multiple students and have a method check to see if any of the students are repeated (by checking ID number) but I cant seem to be able to set multiple students with my current code and save them. From my current code is there any way to be able to set multiple students or will I have to change my code completely
import java.util.Scanner;
public class Registrar
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String string1 = " ";
while(string1 != "1")
{
System.out.println("Please input full name name of student: ");
string1 = input.next(); // user input of name
if (string1 != "0"){
break;
}
System.out.println("Please input Student ID (if done enter 0): ");
String string2 = input.next(); // user input of ID
System.out.println("Please input Students Credits: ");
int inputCredits = input.nextInt(); // User input of Credits
System.out.println("Please input Student's Total Grade Points Earned: ");
double getPoints = input.nextDouble();
double GPA = getPoints/inputCredits; //User input of Grade Points Earned and Divide by Credits to get GPA
Student first = new Student(string1, string2, inputCredits, GPA);
System.out.println( "Name: " + first.getName() + "\nUser ID: " + first.getId() + "\nCredits: " + first.getCredits() + "\nGrade Point Average: " + first.getGradePoints() );
}
}
}
This is my Student Class
public class Student {
private String name;
private String idnum;
private int credits;
private double gradePoints;
public Student(String n, String id, int c, double gp){
name = n;
idnum = id;
credits = c;
gradePoints = gp;
}
public String getName(){
return name;
}
public String getId(){
return idnum;
}
public int getCredits(){
return credits;
}
public double getGradePoints(){
return gradePoints;
}
}
Try this code. better implementation with collection.
Scanner input = new Scanner(System.in);
String string1 = " ";
System.out.println("Number of students to be entered");
int s = input.nextInt();
List<Student> studentList = new ArrayList<Student>();
for(int i = 0; i<s; i++) {
System.out.println("Please input full name of student: ");
string1 = input.next(); // user input of name
System.out.println("Please input Student ID (if done enter 0): ");
String string2 = input.next(); // user input of ID
System.out.println("Please input Students Credits: ");
int inputCredits = input.nextInt(); // User input of Credits
System.out.println("Please input Student's Total Grade Points Earned: ");
double getPoints = input.nextDouble();
double GPA = getPoints/inputCredits; //User input of Grade Points Earned and Divide by Credits to get GPA
Student student = new Student(string1, string2, inputCredits, GPA);
System.out.println( "Name: " + first.getName() + "\nUser ID: " + first.getId() + "\nCredits: " + first.getCredits() + "\nGrade Point Average: " + first.getGradePoints() );
studentList.add(student);
}
You can take a user input(How many student you want to save and run a loope to take details of input. The rough code will be like this:
System.out.println("Enter how many student you want to enter");
int s = input.nextInt();
for(int i = 0; i<s; i++) {
//Code for take details of user
}
//Then you can print the details of student in similar way.