Using ellipse or ellipsis gone wrong - java

I'm creating a simple program that gets name, age and favorite number/s. The problem is that this exception appears when user chooses to input more than 1 favorite number.
Please help me to solve this problem that still uses ellipse in testing class --> favnum2 method.*
testing class
import java.util.Scanner;
public class testing{
public static Scanner input;
public static void main(String[] args){
boolean choicerepeat=true;
int favnumoftimes;
while(choicerepeat==true){
input = new Scanner(System.in);
testing2 obj1 = new testing2();
String name="";
int age=0;
favnumoftimes=0;
double favnum=0, favnumarr[]=new double[999];
boolean choice1;
System.out.print("What is your name? ");
name = input.nextLine();
System.out.print("What is your age? ");
age = input.nextInt();
obj1.message1(name);
obj1.message2(age);
System.out.print(name+" do you only have one favorite number? (If yes type 'true' else 'false' - NOTE: lowercase only) ");
choice1 = input.nextBoolean();
if(choice1==true)
favnum1();
else{
System.out.println("How many favorite numbers do you have "+name+"? ");
favnumoftimes = input.nextInt();
for(int a=0;a<favnumoftimes;a++){
System.out.print("Enter favorite number "+ (a+1) +": ");
favnumarr[a]=input.nextDouble();
}
for(int a=0;a<favnumarr.length;a++){
favnum2(favnumoftimes, favnumarr[a]);
}
}
System.out.println();
System.out.println("Do you want to restart the program? (true(Yes) else false(No)) ");
choicerepeat = input.nextBoolean();
}
}
public static void favnum1(){
System.out.print("Enter favorite number: ");
double favnumholder1 = input.nextDouble();
System.out.println("Your favorite number is "+favnumholder1+" ." );
}
public static double favnum2(int favnumoftimesholder,double...favtemphold2){
System.out.print("Your favorite numbers are ");
for(int a=0;a<=favnumoftimesholder;a++){
System.out.print(favtemphold2[a]+", ");
}
return 0;
}
}
testing2 class
public class testing2{
public static String message1(String nameholder){
for(int a=0;a<nameholder.length();a++){
char strholder = nameholder.charAt(a);
if(Character.isDigit(a)){
System.out.println("Names don't have numbers... ");
break;
}
else continue;
}
System.out.println("\nHi "+nameholder+"! Welcome to my simple program. ");
return nameholder;
}
public static int message2(int ageholder){
System.out.println("Your age is "+ageholder+" years old? Oh my goodness. ");
System.out.println();
return ageholder;
}
}

The problem is that varargs create new arrays with a length equal to the number of parameters passed. Thus double...favtemphold2 will create a new array favtemphold2 and since you only pass 1 element (favnum2(favnumoftimes, favnumarr[a]);) that array will have length 1.
You might want to either pass more elements or the entire array, i.e. favnum2(favnumoftimes, favnumarr);. Since double... is basically syntactic sugar for double[] they are equal and passing a double array for a double vararg will work.
A warning for future use of varargs though: be carefull with Object... since arrays are objects as well.

Related

How to call strings from other methods into main method?

Hello
I'm new to java and need someone to answer a problem I'm having. I have recently started a project to make a calculator in Java. However i'm having a problem with one prat of my code. Basically i can't call a string off from an method. Ive tried varoius other attemps to fix the problem but to no avail. Here is the code:
package CalculatorCore;
import java.util.Scanner;
public class calculations {
static void firstNumber() {
Scanner firstNum = new Scanner(System.in);
System.out.print("First Number: ");
String n1 = firstNum.next(); //You can see, i put the string in a method
}
static void secondNumber() {
Scanner secondNum = new Scanner(System.in);
System.out.print("Second Number: ");
String n2 = secondNum.next(); //Here too
}
public static void main(String[] args) {
System.out.println("Please Choose one of the following equasions: +, -, * or /");
System.out.println("");
System.out.println("");
mathEquasions();
}
static void mathEquasions() {
Scanner equasions = new Scanner(System.in);
System.out.print("Enter input: ");
String e = equasions.next();
if (e.equals("+")) {
System.out.println("");
System.out.println("Please enter the first number that you want to add");
firstNumber();
System.out.println("");
System.out.println("Now add the second number");
secondNumber();
var plusAnswer = (n1 + n2); /*The problem is situated here, i need to call the
strings from another class*/
System.out.println("");
System.out.println("");
System.out.println("Your answer is...");
firstNumber();.n1
}
}
I've already used methods to make the user inputs compact so if theres no other way should i remove the methods?
You need to return the numbers you retrieved in your both methods. Don't forget to parse them as integers, using nextInt:
public class calculations {
static int firstNumber() {
Scanner firstNum = new Scanner(System.in);
System.out.print("First Number: ");
int n1 = firstNum.nextInt();
return n1;
}
static int secondNumber() {
Scanner secondNum = new Scanner(System.in);
System.out.print("Second Number: ");
int n2 = secondNum.nextInt();
return n2;
}
}
Then, when calling firstNumber or secondNumber, create new variables to store their return values:
public class calculations {
static void mathEquasions() {
Scanner equasions = new Scanner(System.in);
System.out.print("Enter input: ");
String e = equasions.next();
if (e.equals("+")) {
System.out.println("");
System.out.println("Please enter the first number that you want to add");
int n1 = firstNumber();
System.out.println("");
System.out.println("Now add the second number");
int n2 = secondNumber();
var plusAnswer = (n1 + n2);
System.out.println("");
System.out.println("");
System.out.println("Your answer is...");
}
}
}
welcome to SO! When trying something for the first time it's a good practice to make it as simple as you can, and from there gradually use more complex techniques.
In this case everything is in one class already, so as a first step you could try to put all your code back into the main method.
public static void main(String[] args) {
//All your code can come here first in the order they are supposed to to be called.
}
As a second step, when it all works, you can extract the parts where you would duplicate code, into separate methods.
Like here instead of having firstNumber() and secondNumber() you could have just one, with something like:
static int getNumber() {
Scanner scanner = new Scanner(System.in);
System.out.print("Number: ");
int number = scanner.nextInt();
return number;
}
and you can call the same method to get both numbers:
public static void main(String[] args) {
//...
System.out.println("Please enter the first number that you want to add");
int n1 = getNumber(); // Using the same method for both
System.out.println("");
System.out.println("Now add the second number");
int n2 = getNumber(); // Using the same method for both
//...
}
Learning by doing and jumping into the thick of it is one of the best ways to learn. There are tons of good quality materials freely available (eg. on yt) and they can really boost your skills. That's also how I started learning, so good luck!

Object wont initialize - method isn't recognized [duplicate]

This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Closed 2 years ago.
This is the 'Lead' class, when I try to call Leads.primeLead() , I get a
"Non-static method cannot be referenced from a static context" error.
I do understand the error, but I do not understand why when I defined a constructor and initilized an object, I cannot apply the method primeLead() on object lead1 .
How do I solve this?
import java.util.ArrayList;
import java.util.Scanner;
public class Lead extends Main{
String nameLead;
int ageLead;
int phoneLead;
String cityLead;
String email;
String otherNotes;
int indexOfLead = 0;
int i = indexOfLead;
ArrayList<String> names = new ArrayList<String>();
ArrayList<Integer> ages = new ArrayList<Integer>();
ArrayList<Integer> phones = new ArrayList<Integer>();
ArrayList<String> cities = new ArrayList<String>();
ArrayList<String> emails = new ArrayList<String>();
ArrayList<String> notes = new ArrayList<String>();
Scanner leads = new Scanner(System.in);
Lead(){
i = 0;
// Need to create an ArrayList that has all the Arraylists above.
}
Lead lead1 = new Lead();
/* public mainMenuLead(){
System.out.println("Please choose one of the following options");
} */
public static void primeLead(){
i = 0;
System.out.println("============================================");
System.out.println(" Please enter by the following order : ");
System.out.println(" Name, age, phone , city, mail ");
System.out.println("============================================");
System.out.println("Please enter the name of the Lead : ");
names.add(leads.nextLine());
System.out.println("Age? : ");
ages.add(Integer.parseInt(leads.nextLine()));
System.out.println("Phone number? ");
phones.add(Integer.parseInt(leads.nextLine()));
System.out.println("Would you like to add ... ");
System.out.println("1) City? ");
System.out.println("2) Email? ");
System.out.println("3) Notes? ");
if(leads.nextLine().equals("1")){
System.out.println("Please add City: ");
cities.add(leads.nextLine());
} else if (leads.nextLine().equals("2")){
System.out.println("Please add email : ");
emails.add(leads.nextLine());
} else if(leads.nextLine().equals("3")){
System.out.println("Please add any other notes you may have: ");
notes.add(leads.nextLine());
}
}
}
public void primeLead(){
i = 0;
System.out.println("============================================");
System.out.println(" Please enter by the following order : ");
System.out.println(" Name, age, phone , city, mail ");
System.out.println("============================================");
System.out.println("Please enter the name of the Lead : ");
names.add(leads.nextLine());
System.out.println("Age? : ");
ages.add(Integer.parseInt(leads.nextLine()));
System.out.println("Phone number? ");
phones.add(Integer.parseInt(leads.nextLine()));
System.out.println("Would you like to add ... ");
System.out.println("1) City? ");
System.out.println("2) Email? ");
System.out.println("3) Notes? ");
if(leads.nextLine().equals("1")){
System.out.println("Please add City: ");
cities.add(leads.nextLine());
} else if (leads.nextLine().equals("2")){
System.out.println("Please add email : ");
emails.add(leads.nextLine());
} else if(leads.nextLine().equals("3")){
System.out.println("Please add any other notes you may have: ");
notes.add(leads.nextLine());
}
}
}
second file(Where Lead.primeLead() is called:
import java.util.Scanner;
public class Main {
boolean exit = false;
public void runMenu(){
printHeader();
while(!exit){
mainMenu();
int choice = getInput();
performAction(choice);
}
}
private void performAction(int choice){
switch(choice){
case 1:
new Lead();
Lead.primeLead();
case 2:
case 3:
case 4:
case 5:
exit = true;
System.out.println("Bye!");
break;
}
}
public void printHeader(){
System.out.println("===========================================");
System.out.println(" Hello user! ");
System.out.println(" Welcome to our lead ");
System.out.println(" Management tool ");
System.out.println("===========================================");
}
public void mainMenu(){
System.out.println("\nPlease select one of the following options: ");
System.out.println("1) Create a new lead");
System.out.println("2) View all the leads");
System.out.println("3) Connect ");
System.out.println("4) View statistics");
System.out.println("5) Exit ");
}
private int getInput(){ // Scanner takes input from user, returns his choice.
Scanner kb = new Scanner(System.in);
int choice = -1;
while(choice < 0 || choice > 5){
try{
System.out.print("\nEnter your choice: ");
choice = Integer.parseInt(kb.nextLine()); // What is Integer.parseInt ? what is . next line ?
}
catch(NumberFormatException e){
System.out.println("Invalid selection, please try again.");
}
}
return choice;
}
public static void main(String[] args){
Main menu = new Main();
menu.runMenu();
}
}
You create a Lead object and do not use it:
new Lead();
Lead.primeLead();
Instead, you should use the lead object you created:
Lead lead=new Lead();
lead.primeLead();
If you call <ClassName>.<methodName>(<parameters>);, you call a static method that has nothing to do eith the object.
If you call <objectOfTheClass>.<methodName>(<parameters>);, you call a non-static method that is part of the object.
And, as #Andreas points out in the comments, every open curly brace needs to have a closing curley brace at the appropriate position any the other way round.

How to add an exception to account for invalid user input? User should input a name and I need to throw an exception if input is not a name

Brand new to Java, just started last Friday after wrapping up Javascript training. I have an exercise that's asking for the following (I've bolded everything I haven't yet completed):
Provide information about students in a class
Prompt the user to ask about a particular student
Give proper responses according to user-submitted information
Ask if user would like to learn about another student
Account for invalid user input with exceptions
Try to incorporate IndexOutOfBoundsException and
IllegalArgumentException
Make it easy for the user - tell them what information is available
Use parallel arrays to hold the student data
I've scoured StackOverflow for answers, and found a lot of helpful stuff, but it all seems to relate to integers and not strings...though maybe it's just my dumb monkey brain.
I don't believe the "Try to incorporate IndexOutOfBoundsException and
IllegalArgumentException" instruction is a requirement, so don't feel like you have to include those.
Any helpful tips or direction would me much appreciated...and please don't laugh at my code, although constructive criticism is much obliged.
Without further ado:
import java.util.Arrays;
import java.util.Scanner;
public class Students {
private static String[] students = {"John", "Ben", "Lisa", "Stewart", "Cora"};
private static int[] grades = {79, 86, 90, 89, 99};
public static void main(String args[]) {
System.out.println(Arrays.toString(students));
Scanner kb = new Scanner(System.in);
boolean userChoice = true;
String userInput;
String choice;
while(userChoice) {
System.out.println("Please enter a Student's name to get their grade: ");
userInput = kb.nextLine();
getGrades(userInput);
System.out.println("Continue? (y/n)");
choice = kb.nextLine();
if (choice.equalsIgnoreCase("n")) {
userChoice = false;
}
}
kb.close();
}
private static void getGrades(String userInput) {
int length = students.length;
for(int i = 0; i < length; i++) {
if(userInput.equals(students[i])) {
System.out.println(userInput + "'s " + "grade is: " + grades[i]);
}
}
}
}
This is an example of my output:
[John, Ben, Lisa, Stewart, Cora]
Please enter a Student's name to get their grade:
Ben
Ben's grade is: 86
Continue? (y/n)
y
Please enter a Student's name to get their grade:
Lisa
Lisa's grade is: 90
Continue? (y/n)
n
Process finished with exit code 0
By the way, although I just signed up today for help with this problem, this community has been a godsend to me while learning Javascript so this a formal thank you to all you glorious bastards!
Figured it out on my own :P
Ended up creating a list from my students array and using the contains method to compare user input to my list of students, and if input doesn't match a student in the array then it throws an exception and prints "Not a valid student's name" and asks if you want to input another name.
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Students {
private static String[] students = {"John", "Ben", "Lisa", "Stewart", "Cora"};
private static int[] grades = {79, 86, 90, 89, 99};
private static String[] behavior = {"aggressive", "distractable", "attentive", "disruptive", "angelic"};
private static List myList = Arrays.asList(students);
public static void main(String args[]) {
Scanner kb = new Scanner(System.in);
boolean userChoice = true;
String userInput;
String choice;
while(userChoice) {
System.out.println(myList);
System.out.println("Please enter a student's name (case-sensitive) to get their progress report: ");
userInput = kb.nextLine();
try {
if (myList.contains(userInput)) {
getGrades(userInput);
} else {
throw new IllegalArgumentException();
}
} catch (IllegalArgumentException e) {
System.out.println("Not a valid student's name");
}
System.out.println("Would you like to enter another student's name? (y/n)");
choice = kb.nextLine();
if (choice.equalsIgnoreCase("n")) {
userChoice = false;
}
}
}
private static void getGrades(String userInput) {
for(int i = 0; i < students.length; i++) {
if(userInput.equals(students[i])) {
System.out.println(userInput + "'s " + "grade is " + grades[i] + " and they are " + behavior[i]);
}
}
}
}

How can I read any user input from the scanner library?

I'm fairly new to java, so don't think this is some idiot. Anyways, I've been trying to make a program that can read a certain letter from the console and then decide which operation to use, let's say to add. However, I can't get an If loop to read the variable that decides which operator to use, here is the code, and please help.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner user_input = new Scanner( System.in );
int number;
String function;
System.out.println("What Do You Want to Do? (a to add; s to" +
" subrtact; d to divited; m to multiply, and sq to square your nummber.)" );
function = user_input.next();
if (function == "sq"){
System.out.print("Enter your number: ");
number = user_input.nextInt();
System.out.print(number * number);
} else {
System.out.println("Unidentified Function!");
}
}
}
(I made the description shorter so that it would fit).
This is just an example to get you started in the right direction.
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int num1, num2, result;
System.out.println("What Do You Want to Do? (a to add; s to"
+ " subrtact; d to divited; m to multiply, and s to square your nummber.)");
String choice = user_input.next();
// Add
if (Character.isLetter('a')) {
System.out.println("Enter first number: ");
num1 = user_input.nextInt();
System.out.println("Enter second number: ");
num2 = user_input.nextInt();
result = num1 + num2;
System.out.println("Answer: " + result);
}
}
}
If you use hasNext() on a scanner it will wait for an input until you stop the program. Also using equals() is a better way of comparing strings.
while(user_input.hasNext()){
function = user_input.next();
if (function.equals("s")){
System.out.print("Enter your number: ");
number = user_input.nextInt();
System.out.print(number * number);
} else {
System.out.println("Unidentified Function!");
}
}
Scanner s = new Scanner(System.in);
String str = s.nextLine();
int a=s.nextInt();
int b=s.nextInt();
if(str.equals("+"))
c=a+b;
else if(str.equals("-"))
c=a-b;
else if(str.equals("/"))
c=a/b;
// you can add operators as your use
else
System.out.println("Unidentified operator" );
I hope it helps!

Storing object in array in Java

Here is a simple program. I am assigned to store the objects in an array. But as I am a beginner student so i dont know how to store objects in array. Could somebody please help me with this question?
import java.util.Scanner;
public class MainExample {
public static void main(String[] args) {
double length;
double width;
double price_per_sqyd;
double price_for_padding;
double price_for_installation;
String input;
double final_price;
boolean repeat = true;
Scanner keyboard = new Scanner(System.in);
while (repeat)
{
System.out.println("\n" +"What is the length of the room?: ");
length = keyboard.nextInt();
System.out.println("What is the width of the room?: ");
width = keyboard.nextInt();
System.out.println("What is the price of the carpet per square yard?: ");
price_per_sqyd = keyboard.nextDouble();
System.out.println("What is the price for the padding?: ");
price_for_padding = keyboard.nextDouble();
System.out.println("What is the price of the installation?: ");
price_for_installation = keyboard.nextDouble();
keyboard.nextLine();
System.out.println( "\n" + "Type 'yes' or 'no' if this is correct: ");
input = keyboard.nextLine();
if ("yes".equals(input))
repeat = true;
else
repeat = false;
}
}
}
you would need to create a class to hold the attributes like so. Create a constructor to initialize these values.
public class Room{
double length;
double width;
double price_per_sqyd;
double price_for_padding;
double price_for_installation;
String input;
double final_price;
boolean repeat = true;
}
then in your main method/driver class create an array with the type of this class and store relevant objects.
Room arr=new Room[100];
int count=0;
while (repeat)
{
System.out.println("\n" +"What is the length of the room?: ");
length = keyboard.nextInt();
System.out.println("What is the width of the room?: ");
width = keyboard.nextInt();
System.out.println("What is the price of the carpet per square yard?: ");
price_per_sqyd = keyboard.nextDouble();
System.out.println("What is the price for the padding?: ");
price_for_padding = keyboard.nextDouble();
System.out.println("What is the price of the installation?: ");
price_for_installation = keyboard.nextDouble();
keyboard.nextLine();
System.out.println( "\n" + "Type 'yes' or 'no' if this is correct: ");
input = keyboard.nextLine();
arr[count]=new Room(length,width,price1,price2,price3,price4);//call to the constructor
if ("yes".equals(input))
repeat = true;
count++;
else
repeat = false;
}
}
Although not very elegant, a quick solution for this toy program would be to make a "Room" class with the various properties like "length", "width", "price_per_sqft" etc. Then you can set specific property of each room object and store the "room" objects in an array of "Room".
What are you trying to store in an array? The different final_price values?
Regardless, because you don't know how many times your loop will run, you probably need an ArrayList. You could create this by adding ArrayList <Double> prices = new ArrayList <Double> ();
Then, add a line at the end of your loop that stores the correct variable to the ArrayList. For example: prices.add(final_price);
If final_price is not what you are trying to store, then just replace it with the variable you do want to store.
Also, don't forget that if you do use an ArrayList, you will need the correct import statement at the top of your code: import java.util.ArrayList;

Categories

Resources