The code is fine, but when I need to take the variables out of the functions and put them into the public static void, it says the variable cannot be found. Anybody know how to solve this issue?
import java.util.*;
public class Greetings {
public static void main(String[] args) {
System.out.println("Greetings, " + String(s) + ". " +
String(j) +"!" + " You are about " + int(z) + " years old");
}
public static String fNameGenerator(String s){
Scanner scan1 = new Scanner(System.in);
System.out.println("Please enter your first name: ");
String first = scan1.next();
s = first.substring(0,1).toUpperCase();
return s;
}
public static String LastName(String j){
Scanner scan2 = new Scanner(System.in);
System.out.println("Please enter you last name: ");
String second = scan2.next();
int x = second.length();
String y = second.substring(0, x).toLowerCase();
j = y.substring(0,1).toUpperCase();
return j;
}
public static int age(int z){
Scanner scan3 = new Scanner(System.in);
System.out.println("Please enter your year of birth: ");
int third = scan3.nextInt();
z = (2015 - third);
return z;
}
}
You are not calling any of the methods, so how do you expect them to return something?
Two things to remember:
just because you wrote return s at the end of a method, it does not mean you can access s outside of this method. There's something called scopes in java, that means that a variable exists only on the scope it's define in- in your case - inside the methods. if you want it to exist outside - take the returned value and do something with it.
declaring the methods does nothing until you actually call them
so in order to access these variables, you need to do something like this:
public static void main(String[] args) {
String s = fNameGenerator();
String j = LastName();
int z = age();
System.out.println("Greetings, " + s + ". " + j +"!" +" You are about " + z + " years old");
}
one more thing you can see that I did there- you don't need to pass anything to your methods, as you are not doing anything with the given values before re-setting them. just make sure you declare the fields inside. for example your age method should look like:
public static int age(){
Scanner scan3 = new Scanner(System.in);
System.out.println("Please enter your year of birth: ");
int third = scan3.nextInt();
int z = (2015 - third);
return z;
}
There is a compile error in your code
System.out.println("Greetings, " + String(s) + ". " + String(j) +"!" +" You are about " + int(z) + " years old");
If you're trying to call the methods then replace
String(s) --> fNameGenerator(s)
String(j) --> LastName(j)
int(z) --> age(z)
Have the s,j,z as the local variables or static members.
or remove the arguments passing to the method as you're getting input from scanner
Related
I know that the question has been asked but I tried to apply what I saw here and got an error.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner get_input = new Scanner(System.in);
System.out.println("Enter your name ");
String name = get_input.nextLine();
boolean is_int = false;
int year_of_birth = 0;
System.out.println("Enter your year of birth");
while (!get_input.hasNextInt()) {
// If the input isn't an int, the loop is supposed to run
// until an int is input.
get_input.hasNextInt();
year_of_birth = get_input.nextInt();
}
//year_of_birth = get_input.nextInt();
System.out.println("Enter the current year");
int current_year=get_input.nextInt();
int age = current_year-year_of_birth;
System.out.println("Your name is " + name + " and you are " + age + " year old.");
get_input.close();
}
}
Without the loop, everything works fine. What is wrong in my code? To be clear, I'm trying to ask for an input until the input can be validated as an integer.
Thanks a lot in advance.
If you would like to skip invalid non-int values, your loop should look like this:
while (!get_input.hasNextInt()) {
// skip invalid input
get_input.next();
}
// here scanner contains good int value
year_of_birth = get_input.nextInt();
This works for me if i understood you correctly. You need to keep checking what value has the scanner, so you need to keep advancind through the scanner while the value is not an integer:
Scanner get_input = new Scanner(System.in);
System.out.println("Enter your name ");
String name = get_input.nextLine();
int year_of_birth = 0;
System.out.println("Enter your year of birth");
while (!get_input.hasNextInt()) { //check if it is not integer
System.out.println("Enter your year of birth"); // ask again
get_input.next(); //advance through the buffer
}
year_of_birth = get_input.nextInt(); //here you get an integer value
int current_year=get_input.nextInt();
int age = current_year-year_of_birth;
System.out.println("Your name is " + name + " and you are " + age + " year old.");
get_input.close();
I am attempting to make this code take each variable, pass it down to the builder method and have it create a full sentence based on what was input by the user. The builder method passes it back to the main method and prints out the complete sentence consisting of "subject + verb + adjective + object + adverb".
Do I need to store each user input into an ArrayList? If so, how do I prompt the user for each new sentence piece? I've tried using for loops, however it just asks me for the first line 5 times, assuming I make the Array[5].
package assignment.pkg4.pkg3.string.input;
import java.util.Scanner;
public class Assignment43StringInput {
private static Scanner scanner = new Scanner( System.in );
public static void main(String[] args) {
System.out.print("Enter a subject: ");
String subject = scanner.nextLine();
System.out.print("Enter a verb: ");
String verb = scanner.nextLine();
System.out.print("Enter an adjective: ");
String adjective = scanner.nextLine();
System.out.print("Enter an object: ");
String object = scanner.nextLine();
System.out.print("Enter an adverb: ");
String adverb = scanner.nextLine();
System.out.print(builder(text));
}
public static String builder(String text) {
String sentence = subject + verb + adjective + object + adverb;
return sentence;
}
}
If I understand your question correctly, you want to use one unique structure instead of one variable for each input. If you know your size is always going to be 5 and will not change, then you can use String[]. Alternatively, you can use a List.
But if you want to know exactly what is what, you might want to give Map a go. I'll explain it with an example:
public class Assignment43StringInput {
private static Scanner scanner = new Scanner( System.in );
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
System.out.print("Enter a subject: ");
map.put("subject", scanner.nextLine());
System.out.print("Enter a verb: ");
map.put("verb", scanner.nextLine());
System.out.print("Enter an adjective: ");
map.put("adjective", scanner.nextLine());
System.out.print("Enter an object: ");
map.put("object", scanner.nextLine());
System.out.print("Enter an adverb: ");
map.put("adverb", scanner.nextLine());
System.out.print(builder(map));
}
public static String builder(Map<String,String> map) {
return map.get("subject") + " " + map.get("verb") + " " + map.get("adjective") + " " + map.get("object") + " " + map.get("adverb");
}
}
This way you can easily reorder your sentence if you need to, and even add more elements to it.
You do not need array or Map or whatever. To properly achieve your requirement, you just need to make your builder (I'd rather call it buildSentence, as method is supposed to be a verb) accept corresponding arguments:
public static String buildSentence(String subject,
String verb,
String adj,
String obj,
String adverb) {
return subject + " " + verb + " "
+ adjective + " " + object + " " + adverb;
}
and you simply call it with your variables passed in correspondingly:
System.out.print(buildSentence(subject, verb, adjective, object, adverb));
Regarding use of Array/ ArrayList/ Map, given you have a very well-defined sets of values to use, you shouldn't use these data structure as they are too versatile and making your code hard to read and error-prone. Declare a simple class to serve for struct-like purpose is a much better choice:
class Sentence {
public String subject;
public String verb;
public String adjective;
public String object;
public String adverb;
}
In your main:
public static void main(String[] args) {
Sentence sentence = new Sentence();
System.out.print("Enter a subject: ");
sentence.subject = scanner.nextLine();
// do the same for other values
System.out.print(buildString(sentence));
}
public static String buildString(Sentence sentence) {
return sentence.subject + " "
+ sentence.verb + " "
+ sentence.adjective + " "
+ sentence.object + " "
+ sentence.adverb;
}
See how much clearer and readable the code become?
A even better change is to move buildString() above as a member method of Sentence.
I wrote this code in Java to create a very simple calculator.
import java.util.Scanner;
public class Addition {
static void Addition() {
Scanner numberOne = new Scanner(System.in);
float x = numberOne.nextFloat();
System.out.println("First Number: " + numberOne.nextLine());
Scanner numberTwo = new Scanner(System.in);
float y = numberTwo.nextFloat();
System.out.println("Second Number: " + numberTwo.nextLine());
float sum = x + y;
System.out.println(sum);
}
}
public class Subtraction {
static void Subtraction() {
Scanner numberOne = new Scanner(System.in);
float x = numberOne.nextFloat();
System.out.println("First Number: " + numberOne.nextLine());
Scanner numberTwo = new Scanner(System.in);
float y = numberTwo.nextFloat();
System.out.println("Second Number: " + numberTwo.nextLine());
float difference = x - y;
System.out.println(difference);
}
}
public class Multiplication {
static void Multiplication() {
Scanner numberOne = new Scanner(System.in);
float x = numberOne.nextFloat();
System.out.println("First Number: " + numberOne.nextLine());
Scanner numberTwo = new Scanner(System.in);
float y = numberTwo.nextFloat();
System.out.println("Second Number: " + numberTwo.nextLine());
float product = x + y;
System.out.println(product);
}
}
public class Division {
static void Addition() {
Scanner numberOne = new Scanner(System.in);
float x = numberOne.nextFloat();
System.out.println("First Number: " + numberOne.nextLine());
Scanner numberTwo = new Scanner(System.in);
float y = numberTwo.nextFloat();
System.out.println("Second Number: " + numberTwo.nextLine());
float quotient = x + y;
System.out.println(quotient);
}
}
public class Calculate {
public static void main(String[] args) {
System.out.println("Calculator");
System.out.println("Choose an operation:");
System.out.println("Addition");
System.out.println("Subtraction");
System.out.println("Multiplication");
System.out.println("Division");
Scanner input = new Scanner(System.in);
String choice = input.nextLine();
if(choice.equals("Addition") {
Addition();
}
else if(choice.equals("Subtraction") {
Subtraction();
}
else if(choice.equals("Mutliplication") {
Mutliplication();
}
else if(choice.equals("Division"){
Division();
}
else {
System.out.println("That wasn't a valid input. Please try again.");
}
}
}
However, when I tried to run it, I got this error message:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error on token ")", ) expected after this token
The method Addition() is undefined for the type Calculate
Syntax error on token ")", ) expected after this token
The method Subtraction() is undefined for the type Calculate
Syntax error on token ")", ) expected after this token
The method Mutliplication() is undefined for the type Calculate
Syntax error on token ")", ) expected after this token
The method Division() is undefined for the type Calculate
at Calculate.main(Calculate.java:14)
I'm a beginner in Java and I'm not quite sure what the error message means. Can someone explain to me what it means and how I do fix it?
You've got a few issues in your code.
Firstly, you don't need a separate class for each method. Just put all the methods together in the same class. That way, you won't need to specify a class name when you call each method.
Secondly, you're missing some ) characters in your if statements. Make sure that each ( character has a matching ). For example, if (choice.equals("Addition")) {.
Thirdly, your multiplication and division methods actually seem to be doing addition. Use * to multiply two numbers, and / to divide them.
Fourth, lose some of those calls to nextLine() and just print the value you've already retrieved. So, for example, System.out.println("First Number: " + numberOne.nextLine()); should be System.out.println("First Number: " + x); and similarly many times in your code.
You have defined your Addition method in your class named Addition.
import static Addition.Addtion();
Change Addition() to Addition.Addition().
You then need to do the same for your other methods. You also are missing a ) on each of your choise tests.
if(choice.equals("Addition")) { // <-- count the open and close parens.
In your Calculate class body, you aren't properly closing your if-statement headers.
if(choice.equals("Addition") {
should be
if(choice.equals("Addition")) { // notice the second closing parenthesee
You have to put a closing parenthesee for every open one you have.
You had a syntax error where you didn't add the necessary close parenthesis for the if statements.
if(choice.equals("Addition") <---- missing parenthesis {
Addition();
}
Solution
if(choice.equals("Addition")) {
Addition();
}
else if(choice.equals("Subtraction")) {
Subtraction();
}
else if(choice.equals("Mutliplication")) {
Mutliplication();
}
else if(choice.equals("Division")){
Division();
}
else {
System.out.println("That wasn't a valid input. Please try again.");
}
You are placing the methods like addition and subtraction in their own classes so Main doesn't know how to call them.
I would say scrap the public classes preceding each math method. Also change your
System.out.println("Second Number: " + numberTwo.nextLine());
to something like:
System.out.println("Second Number: " + y);
If you want it to actually spit out the respective numbers.
This is the line that gives me the error in the title
showChar();
and this is my method for it:
public static char showChar(String best, int pos) {
return best.charAt(pos);
}
this is my whole code:
import java.util.Scanner;
public class StringCode
{
static String input1, input2, s, best;
static int pos;
public static void main(String []args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Please input your first word: ");
input1 = scan.nextLine();
System.out.print("Please input your second word: ");
input2 = scan.nextLine();
compareWords();
if (input1.length() > input2.length()) {
System.out.println("Number of characters in " + input1 + " is " + input1.length());
best = input1;
}
else {
System.out.println("Number of characters in " + input2 + " is " + input2.length());
best = input2;
}
System.out.print("Enter position noting first character is at 0: ");
pos = scan.nextInt();
showChar();
System.out.println("Character at position " + pos + " in " + best + " is: " + s);
}
public static void compareWords()
{
if (input1.length() > input2.length()) {
System.out.println(input1 + " is greater than " + input2);
}
else if (input1.compareTo(input2)==0) {
System.out.println("The first input is equal to second input");
}
else {
System.out.println(input1 + " is not greater than " + input2);
}
}
public static char showChar(String best, int pos) {
return best.charAt(pos);
}
}
also if you have any tips or better way of writing this it would help a lot
thank you and have a nice day
You are not including arguments when calling showChar(); which you have declared to accept a String best and int pos. Your code should be as follows:
showChar(best, pos);
I would also recommend to use scan.close(); towards the end of your main method when there is no longer any more use for the scanner.
My program is supposed to output labels. All of the input works when I run it but the output is wrong and all that it outputs is null, for every part of the label except for the box number.
import javax.swing.JOptionPane;
public class MailOrderpractice {
static String nameAddressArray[] = new String[7];
public static void main(String[] args) {
// declare variables
String nameAddressArray[] = new String[7];
String numBoxesInput;
int numBoxes;
String enterAnother = "Y";
int counter;
getLabelData();
numBoxesInput = JOptionPane.showInputDialog("Enter number of boxes in the order:");
numBoxes = Integer.parseInt(numBoxesInput);
// begin outer loop logic that determines when user is finished entering mail orders
while (enterAnother.equalsIgnoreCase("Y")) {
counter = 1;
// begin the inner loop to display a label and increment the counter
while (counter <= numBoxes) {
System.out.println(nameAddressArray[0] + " " + nameAddressArray[1] + " " + nameAddressArray[2]);
System.out.println(nameAddressArray[3]);
System.out.println(nameAddressArray[4] + ", " + nameAddressArray[5] + " " + nameAddressArray[6]);
System.out.println("Box " + counter + " of " + numBoxes);
System.out.println();
counter = counter + 1;
}
enterAnother = " "; // initialize the variable to something other than "Y" before sending the prompt
enterAnother = JOptionPane.showInputDialog("Do you want to produce more labels? Y or N");
while (!enterAnother.equalsIgnoreCase("Y") && !enterAnother.equalsIgnoreCase("N")) {
enterAnother = JOptionPane.showInputDialog(null, "Invalid Response. Please enter Y or N.",
"DATA ENTRY ERROR", JOptionPane.ERROR_MESSAGE);
} // end while
if (enterAnother.equalsIgnoreCase("Y")) {
getLabelData();
numBoxesInput = JOptionPane.showInputDialog("Enter number of boxes in the order:");
numBoxes = Integer.parseInt(numBoxesInput);
} // end if
} // end while
System.exit(0);
}
public static void getLabelData() {
nameAddressArray[0] = JOptionPane.showInputDialog("Enter title (Mr., Ms., Dr., etc.): ");
nameAddressArray[1] = JOptionPane.showInputDialog("Enter first name: ");
nameAddressArray[2] = JOptionPane.showInputDialog("Enter lastname: ");
nameAddressArray[3] = JOptionPane.showInputDialog("Enter street address: ");
nameAddressArray[4] = JOptionPane.showInputDialog("Enter city: ");
nameAddressArray[5] = JOptionPane.showInputDialog("Enter state (IL, MO, etc.): ");
nameAddressArray[6] = JOptionPane.showInputDialog("Enter zip (e.g., 62025): ");
}
The array nameAddressArray is declared twice. You have a static field
static String nameAddressArray[] = new String[7];
You also have a local variable with the same name in the main method.
String nameAddressArray[] = new String[7];
Your main method is putting values into the second array, whereas your getLabelData method is using the values from the static field, and these are all the initial value (null).
One way to solve this problem is to just get rid of the local variable. Then both parts of the code will use the same array.
Alternatively, you could get rid of the static field, and pass the array as a parameter to the getLabelData method. This is probably a better solution, as mutable static fields are generally not a good idea.
you just need to comment this line into Main method(),
// String nameAddressArray[] = new String[7];