I wanna store at most 10 numbers but after I ran the programe, I couldn't print the name and the sentence of "The system is full!!" when the numbers exceed 10. How can I correct it?
public static void saveContact(String name, int number) {
nameRec[nameCounter]= name;
nameCounter++;
boolean full = false;
int i = 0;
while(i<=9) {
full = true;
break;
}
i++;
if(!full) {
System.out.println("The System is full!!!");
}else {
System.out.println("Enter the phone number:");
}
System.out.println("Saving the number of\n" + name+ ":" + number);
}
public static String[] nameRec = new String[10];
private static int nameCounter;
public static void saveContact(String name, int number) {
if (nameCounter >= 10) {
System.out.println("The System is full!!!");
} else {
System.out.println("Saving the number of\n" + name + ":" + number);
nameRec[nameCounter++] = name;
}
}
You can build condition just from nameCounter to satisfy your goal.
Variable i is never getting incremented inside the while loop. Also where have namerec & nameCounter been declared. They might be class attributes. If not you have to declare them in a suitable place.
Related
I'm creating an array of objects where the search should be by Linear method and Binary method.
The issue is how to traverse the array with the appropriate data type and compare.
public class FoodMain {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
Food[] foodlist = new Food[3];
//Initialising food objects array
for (int i = 0; i < foodlist.length; i++) {
foodlist[i] = new Food(Food.getId(), Food.getDescription(), Food.getIngredients(), Food.getSellingPrice());
}
FoodMain foodObj = new FoodMain();
foodObj.show(foodlist);
System.out.print("Enter the search value: ");
int value = sc.nextInt();
for(int j=0; j < foodlist.length; j++) {
// Error on line Incompatible operand types Food and int
if(foodlist[j] == value) {
System.out.println("The value " + value + " is at index " + j);
break;
}
else {
System.out.println("Value not in array!!!");
break;
}
}
}
screenshot of object array to be searched
Array Objects
Here is the code for Food class
package foodObjectArray;
import java.util.Scanner;
public class Food {
static Scanner sc = new Scanner(System.in);
public int id;
public String description;
public String ingredients;
public double sellingPrice;
// Food Class constructor
public Food(int id, String description, String ingredients, double sellingPrice) {
super();
this.id = id;
this.description = description;
this.ingredients = ingredients;
this.sellingPrice = sellingPrice;
}
public static int getId() {
System.out.println("Input food ID");
return sc.nextInt();
}
public static String getDescription() {
System.out.println("Input food description");
return sc.next();
}
public static String getIngredients() {
System.out.println("Enter the Ingredients");
return sc.next();
}
public static double getSellingPrice() {
System.out.println("Input food Price");
return sc.nextDouble();
}
hope that this might help in my explanation
Let's ignore all of the other problems, and just focus on your linear search. Let's assume you are searching by id.
for(int j=0; j < foodlist.length; j++) {
if(foodlist[j].id == value) {
System.out.println("The value " + value + " is at index " + j);
break;
}
else {
System.out.println("Value not in array!!!");
break;
}
}
}
The else branch will break the loop if the first item is not a match. It's not going to search the entire array. It's really is just looking at the first item in the array.
You need to remove the else branch and use a flag (boolean) or some other variable to indicate found.
int foundIndex = -1; //-1 means not found.
for(int j=0; j < foodlist.length; j++) {
if(foodlist[j].id == value) {
foundIdex = j;
break;
}
}
if (indexFound > -1)
System.out.println("Found at " + indexFound);
else
System.out.println("Not found.");
There's at least a couple of errors here.
Firstly don't you want if(foodlist[j].id == value) {? The will relieve the incompatible operands. You need to specify the field you're trying to match.
The style police will hate your code and demand you define getters and setters. But you don't have let them in without a warrant. ;)
Also when you've fixed that your code will output 'Value not in array!!!' for every item not matching the search value.
You need to move the 'not found' check outside the the for-loop. But let's take this one step at a time.
I am having trouble getting the right output. I am trying to get my program to do the following: display all multiples of the starting value for as many multiples as the 2nd parameter states.
I don't understand why I am not getting the correct answers when I compile the program. Can someone explain what I did wrong and how to correct?
import java.util.Scanner;
public class Proj3
{
public static void main(String[] args)
{
int iNumMultiples; //holds input by user
int iStartingValue; //holds input by user
int iVal; //holds the multiples
System.out.print("\nEnter integer for multiples and the number of multiples: ");
iStartingValue = kb.nextInt();
iNumMultiples = kb.nextInt();
System.out.print("\nThe first " + iNumMultiples + " multiples of " + iStartingValue + " are: " + iVal);
}
}
public class MyMath
{
//+displayMultiples(startingValue:int, numMultiples:int):void
public static void displayMultiples(int startingValue, int numMultiples)
{
int Val = 0;
for (int i=0; i<=numMultiples; i++)
{
Val += startingValue;
System.out.print("\n" + Val);
}
}
}
Not sure what kb is, you haven't defined it. You actually have to call your displayMultiples method. Not sure why you are breaking this into multiple classes.
public class MyProj {
public static void main(String[] args)
{
int iNumMultiples; //holds input by user
int iStartingValue; //holds input by user
int iVal; //holds the multiples
//System.out.println("Enter integer for multiples and the number of multiples: ");
iStartingValue = 5;
iNumMultiples = 5;
System.out.println("The first " + iNumMultiples + " multiples of " + iStartingValue);
displayMultiples(iStartingValue, iNumMultiples);
}
//+displayMultiples(startingValue:int, numMultiples:int):void
public static void displayMultiples(int startingValue, int numMultiples)
{
int val = 0;
for (int i=0; i<=numMultiples; i++)
{
val += startingValue;
System.out.println(val);
}
}
}
I am currently working on an assignment that requires me to create a "bottle class" for a pre-made "bottle demo" file my professor made. This is the description of the assignment:
Write a Bottle class. The class has these 14 methods: read(), set(int), >set(Bottle), get(), and(Bottle), subtract(Bottle), multiply(Bottle), >divide(Bottle), add(int), subtract(int), multiply(int), divide(int), >equals(Bottle), and toString(). The toString() method will be given in class. All >add, subtract, multiply, and divide methods return a Bottle. Your Bottle class >must guarantee bottles always have a positive value and never exceed a maximum >number chosen by you. These numbers are declared as constants of the class. Each >method wit ha parameter must be examined to determine if the upper or lower bound >could be violated. Consider each method carefully and test only the conditions >that could be violated.
And here is the demo code:
public static void main(String[] args) {
int x;
bottle bottle1 = new bottle();
bottle bottle2 = new bottle();
bottle bottle3 = new bottle();
bottle bottle4 = new bottle();
bottle bottle5 = new bottle();
System.out.println("please enter a number for bottle1:");
bottle1.read(); // affected my max and min
System.out.println("Bottle1 is this value " + bottle1 + ".");
System.out.println("Please enter a number for bottle2:");
bottle2.read(); // affected by max and min
bottle3.set(0);
bottle3 = bottle3.add(bottle1);
bottle3 = bottle3.add(bottle2);
bottle3 = bottle3.divide(2);
System.out.println("The 2 bottle average is: " + bottle3 + ".");
System.out.print("Subtracting bottle1 from bottle2 is: " );
bottle3 = bottle2.subtract(bottle1);
System.out.println( bottle3);
bottle3 = bottle2.divide(bottle1);
System.out.println("Dividing bottle2 with bottle1 is: " + bottle3 + ".");
if (bottle1.equals(bottle2))
{
System.out.println("Bottle1 and bottle2 are equal.");
}
else
{
System.out.println("Bottle1 and bottle2 are not equal.");
}
System.out.println("Bottle4 is now given the value of 10 with the set() method.");
bottle4.set(10);
System.out.println("The value of bottle4 is " + bottle4 + ".");
System.out.println("Bottle4 is now multiplied with bottle1. The value is placed in bottle5.");
bottle5 = bottle1.multiply(bottle4);
System.out.println("The value of bottle5 is " + bottle5 + ".");
System.out.println("Enter an integer to add to the value bottle1 has.");
System.out.println("The sum will be put in bottle3.");
Scanner keyboard = new Scanner(System.in);
x = keyboard.nextInt();
bottle3 = bottle1.add(x);
System.out.println("Adding your number " + x +
" to bottle1 gives a new Bottle with " + bottle3 + " in it.");
System.out.print("Adding the number " + bottle2 + " which is the number" +
" in bottle2 to the\nnumber in ");
bottle2 = bottle1.add(bottle2);
System.out.println("bottle1 which is " + bottle1 +" gives " + bottle2 + ".");
}
}
And this is the code I have made so far:
public class bottle {
Scanner scan = new Scanner(System.in);
private int value;
public void Bottle() {
value = 0;
}
public void read() {
value = scan.nextInt();
}
public void set(bottle) {
value = bottle1.value;
}
public void set(int bottle1) {
value = bottle1;
}
public bottle add(bottle) {
value = value + bottle1.value;
}
public bottle subtract(bottle) {
}
public bottle multiply(bottle) {
}
public bottle divide(bottle) {
}
public bottle add(int bottle) {
}
public bottle subtract(int bottle) {
}
public bottle multiply(int bottle) {
}
public bottle divide(int bottle) {
value = value / bottle;
}
public String toString() {
String name = null;
return name;
}
public boolean equals(bottle bottle) {
if (this == bottle) {
return true;
}
else {
return false;
}
}
}
What I need help on is how do I get my methods to work? ( add(int), divide(bottle), divide(int), etc)
And for there to be a max and min for values the user can input, I know that it can be placed at the top of the class code, but how do I make it so that every time the user inputs a number and the math outputs that the max and min will be checked every time to see if any number violates the set rule?
My I know my class code is missing many key components (I think return methods for the math parts) but I am struggling to stay sane trying to figure out what to do. Any help would be greatly appreciated and thanks in advance.
I will also answer any questions that you might have to the best of my ability.
EDIT: I have remade my code after reading the chapter about classes in my textbook and my knowledge is a bit better than before. Here is my new code:
Scanner scan = new Scanner(System.in);
private int value;
private int max = 100;
private int min = 0;
public bottle() {
// sets default value as zero
this.value = 0;
}
public void read() {
value = scan.nextInt();
}
public void set(int value) {
this.value = value;
}
public int add(bottle) {
if (this.value + bottle < this.max && this.value + bottle > this.min)
return this.value + bottle;
else
System.out.println("Please enter another number");
int x = scan.nextInt();
return add(x);
// the few lines above checks to see if the number violates the max and min
}
public int subtract(bottle) {
if (this.value - bottle < this.max && this.value - bottle > this.min)
return this.value - bottle;
else
System.out.println("Please enter another number");
int x = scan.nextInt();
return subtract(x);
}
// though there is this error under the word bottle in the parentheses
public int multiply(bottle) {
if (this.value * bottle < this.max && this.value * bottle > this.min)
return this.value * bottle;
else
System.out.println("Please enter another number");
int x = scan.nextInt();
return multiply(x);
}
public int divide(bottle) {
if (this.value / bottle < this.max && this.value / bottle > this.min)
return this.value / bottle;
else
System.out.println("Please enter another number");
int x = scan.nextInt();
return divide(x);
}
// the String toString method, format as shown by the professor.
public String toString()
{
return this.max + " " + this.min + " " + this.value;
Though I still have 4 errors in my class which is the word bottle inside the parentheses after my add, subtract, multiply, and divide method. Thus the demo file has 8 errors which are all the math methods. I am not sure what to do because "bottle" is an object right? Then how do I add 2 bottles together, or am I taking the wrong approach?
It looks like you're almost on the right track. These will help:
https://www.tutorialspoint.com/java/java_object_classes.htm
https://www.tutorialspoint.com/java/java_methods.htm
Pay attention to what an instance is and also how passing in arguments to methods works along with returning.
I tried different things in my code, but I always get errors.
The instructions for the program is that I need to have a function (besides from main) that receives arguments for an array of integer values and a second argument telling the desire value to look in the array by the user.
It must also return how many times the desire value is repeated on the array.
The errors are related to the counter and also some are in the main function.
I think I am not returning the counter value correctly.
This is my current code:
import java.util.Scanner;
import java.util.Arrays;
public class ArregloBusqueda2
{
static int findRepetition(int listOfValues[], int targetValue, int counter)
{
int i;
boolean found = false;
for(i=0; i<listOfValues.length; i++)
{
while((counter < listOfValues.length))
{
if(listOfValues[i] == targetValue)
{
counter = counter + 1;
}
}
}
return counter;
}
public static int main(String[] args)
{
Scanner input = new Scanner (System.in);
int targetValue;
int listOfValues[] = {1,6,3,8,5,8,3,4,8,3};
System.out.println("Please enter the desire number to look for: ");
targetValue=input.nextInt();
findRepetition(targetValue, counter);
if(counter != 0)
{
System.out.println("The frequency of the number " + targetValue + " is: " + counter);
}
else
{
System.out.println ("The number " + targetValue + " is not contained in the array list");
}
}
}
Multiple issues in your code.
public static int main(String[] args) should be public static
void main(String[] args)
findRepetition takes three arguments,
but you are passing two agruments
counter variable is not declared
Logical flaw, while((counter < listOfValues.length)) will keep on executing if counter value is less than listOfValues.
static int findRepetition(int listOfValues[], int targetValue) {
int i;
int counter = 0;
for (i = 0; i < listOfValues.length; i++) {
if (listOfValues[i] == targetValue) {
counter = counter + 1;
}
}
return counter;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int targetValue;
int listOfValues[] = { 1, 6, 3, 8, 5, 8, 3, 4, 8, 3 };
System.out.println("Please enter the desire number to look for: ");
targetValue = input.nextInt();
int counter = findRepetition(listOfValues, targetValue);
if (counter != 0) {
System.out.println("The frequency of the number " + targetValue + " is: " + counter);
} else {
System.out.println("The number " + targetValue + " is not contained in the array list");
}
}
You made your method accept three parameters.
static int findRepetition(int listOfValues[], int targetValue, int counter)
Ask yourself - do you want to "pass in a counter", or only return it? The instructions say the latter.
When you call this method, you are not providing the correct inputs.
findRepetition(targetValue, counter);
What about the listOfValues? You want to findReptition on listOfValues for targetValue, right? So provide the correct parameters into that method call.
Again, you likely do not need the counter passed-in. Because Java is always pass-by-value
Rather, you want to return counter, as you have written. You are looking for this.
int counter = findRepetition(listOfValues, targetValue);
Fixing the remainder of the code is a learning exercise.
You are not calling findRepetition() with required parameters, findRepetition method takes 3 arguments, but you are passing only 2 arguments.
This is my Code that I have so far:
import java.util.*;
public class VoteRecorder
{
// Variables and instance variables
public static String nameCandidatePresident1;
public static String nameCandidatePresident2;
public static String nameCandidateVicePresident1;
public static String nameCandidateVicePresident2;
public static int votesCandidatePresident1;
public static int votesCandidatePresident2;
public static int votesCandidateVicePresident1;
public static int votesCandidateVicePresident2;
private int myVoteForPresident;
private int myVoteForVicePresident;
public VoteRecorder()
{
nameCandidatePresident1 = "null";
nameCandidatePresident2 = "null";
nameCandidateVicePresident1 = "null";
nameCandidateVicePresident2 = "null";
votesCandidatePresident1 = 0;
votesCandidatePresident2 = 0;
votesCandidateVicePresident1 = 0;
votesCandidateVicePresident2 = 0;
myVoteForPresident = 0;
myVoteForVicePresident = 0;
}
public void setCandidatesPresident(String name1, String name2)
{
nameCandidatePresident1 = name1;
nameCandidatePresident2 = name2;
}
public void setCandidatesVicePresident(String name1, String name2)
{
nameCandidateVicePresident1 = name1;
nameCandidateVicePresident2 = name2;
}
public static void resetVotes()
{
votesCandidatePresident1 = 0;
votesCandidatePresident2 = 0;
votesCandidateVicePresident1 = 0;
votesCandidateVicePresident2 = 0;
}
public static String getCurrentVotePresident()
{
return nameCandidatePresident1 + ":" + votesCandidatePresident1 + "\n" +
nameCandidatePresident2 + ":" + votesCandidatePresident2;
}
public static String getCurrentVoteVicePresident()
{
return nameCandidateVicePresident1 + ":" + votesCandidateVicePresident1 + "\n" +
nameCandidateVicePresident2 + ":" + votesCandidateVicePresident2;
}
public void getAndConfirmVotes()
{
}
private String getVotes()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("please vote for a President or vice president " + nameCandidatePresident1 + ", " + nameCandidatePresident2 + ", " + nameCandidateVicePresident1
+ " or " + nameCandidateVicePresident2);
String presidentVote = keyboard.nextLine();
if (presidentVote.equalsIgnoreCase(nameCandidatePresident1))
return nameCandidatePresident1;
if(presidentVote.equalsIgnoreCase(nameCandidatePresident2))
return nameCandidatePresident1;
System.out.println("please vote for a Vice president " + nameCandidateVicePresident1 + " or" + nameCandidateVicePresident2);
String vicePresidentVote = keyboard.nextLine();
if(vicePresidentVote.equalsIgnoreCase(nameCandidateVicePresident1))
return nameCandidateVicePresident1;
if(vicePresidentVote.equalsIgnoreCase(nameCandidateVicePresident2))
return nameCandidateVicePresident2;
else
return "not a valid vote";
}
private boolean confirmVotes()
{
System.out.println("Your vote for President is:");
System.out.println("your vote for Vice President is:");
System.out.println("Is this correct? Yes or No?");
Scanner keyboard = new Scanner(System.in);
String answer = keyboard.nextLine();
if (answer.equalsIgnoreCase("Yes"))
return true;
else
return false;
}
private void recordVote()
{
puscode: If confirmVotes returns true, take the nameCandidate, and ++ to votesCandidate of the same type
Copy this If statement four times, one for each of the candidates, 2 president and 2 vp.
Else or If confirmvotes returns false, put output saying that the votes were not confirmed.
}
}
Say i had all this code, lets look at the method getVotes() and confrimVotes(), in getVotes() the user picks a candidate and than that candidate is returned. How would i get that return statement to show up else where in other methods? like in confirmVote() i want to do this
System.out.println("Your vote for President is: (PresidentialCandidate return statement");
But how can i do that?
This is not a direct answer to your question, but I think your code could be made a lot simpler by harnessing some of the power of object-oriented programming.
You are storing multiple types of information about 4 candidates for different positions as separate variables, and it's making your class very unwieldy.
A (in my opinion) better approach would be to have e.g. a Candidate class to store information about a single candidate, and then your classes could look as follows:
class Candidate {
String Name;
int votes;
}
class VoteRecorder {
Candidate[] presidents;
Candidate[] vicePresidents;
Candidate myVoteForPresident; //Or even make these both ints.
Candidate myVoteForVicePresident;
}
The classes can be further refined, but this will be a start. Any time you see multiple pieces of information that describe the same entity being repeated multiple times, it's a good indication that you could simplify your life by adding a class to represent them together instead.
Edit (to answer question specifically):
If you want to do effectively the following:
System.out.println("Your vote for President is: (PresidentialCandidate return statement");
You can write something like this:
String voteResult = getVotes();
System.out.println("Your vote for President is: " + voteResult);
Or in one line:
System.out.println("Your vote for President is: " + getVotes());
Each time you run this code though, it will prompt the user for input. If you want to save the result until next time as well, you will have to save it to an attribute, e.g. by having a string in your class, and assigning the value to it first. Then just use that later instead of the local variable voteResult.