I would like to know the best possible way to modify this code. Instead of adding the integers to an array in the code itself, I would like the user to input the different weights and the capacity via keyboard.
Now I am currently having compiling errors when inserting the data. I believe the problem lies within the for loop.
import java.util.*;
public class NN01276494 {
public static ArrayList <Double> sack = new ArrayList <Double> ();
public static void main(String [] args){
Scanner in = new Scanner (System.in);
int i =0;
for(i = 0; i<sack.length; i++){
System.out.println("Enter Capacity");
sack.size(in.nextDouble());
}
while (in.hasNextDouble()){
System.out.print("Enter weights");
sack.add(in.nextDouble());
i++;
}
}
public static Boolean knapsackproblem(double targetWeight, int index)
{
Boolean complete = false;
if(index == sack.size()) return false;
if(sack.get(index) == targetWeight)
{
System.out.print("Answer: " + sack.get(index) + " ");
complete = true;
}; //DONE
if(sack.get(index) < targetWeight)
{
complete = knapsackproblem(targetWeight-sack.get(index), index+1);
if(complete) System.out.print(sack.get(index) + " ");
for(int i = index+1; i < sack.size(); i++)
{
if(!complete) complete = knapsackproblem(targetWeight, i);
}
}
if(sack.get(index) > targetWeight) complete =
knapsackproblem(targetWeight, index+1);
return complete;
}
}
The most common way to accept user input in java is the Scanner class. This allows your users to input into the console, and your program to use their input. Here is the javadoc that details scanners in detail, but here's all you need to do to accept integer inputs from your users:
First, import the scanner dictionary so you can use it.
import java.util.Scanner;
This will give you access to the Scanner library. To construct the scanner, you need to specify an input stream in the declaration. To make the console this input stream, declare it like so:
Scanner nameOfScanner = new Scanner(System.in);
Now, to get the integers for the array, use the method .nextInt() as many times as you want. Make sure to ask the user separately for each input, and if you want the user to be able to control the size of the array, you can also ask the user for that. Just in case you don't know, you can declare an array to have a certain size, but not specify what is going to be in each location until later like so:
int[] nameOfArray = new int[sizeOfArray];
On a separate note, I noticed that you had a semicolon after the closing bracket of your if statement in the middle of the knapsackproblem() method. I don't know if that's a typo in your question or actually in your code, but it really shouldn't be there.
I hope this helps, and good luck coding!
I've modified your code so user can input the array via an ArrayList :-using ArrayList user can input data without regard to length just enter as many values as you want then at the end type any letter for ex:[Out] then your method should start working :).
import java.util.*;
public class knapsack {
public static void main(String [] args){
Scanner in = new Scanner (System.in);
System.out.println("Enter Capacity");
int y = in.nextInt();
double [] sack = new double [y];
System.out.println("enter values");
for (int i =0;i<y;i++){
sack[i]=in.nextDouble();
}
}
public static Boolean knapsackproblem(double targetWeight, int index ,
double [] sack)
{
Boolean complete = false;
if(index == sack.length) return false;
if(sack[index] == targetWeight)
{
System.out.print("Answer: " + sack[index] + " ");
complete = true;
}; //DONE
if(sack[index] < targetWeight)
{
complete = knapsackproblem(targetWeight-sack[index], index+1,sack);
//keep going
if(complete) System.out.print(sack[index] + " ");
for(int i = index+1; i < sack.length; i++)
{
if(!complete) complete = knapsackproblem(targetWeight, i,sack);
}
}
if(sack[index] > targetWeight) complete = knapsackproblem(targetWeight,
index+1,sack);
return complete;
}
}
Hope it helps.Also I've fixed your recursion since you wrote knapsack( instead of knapsackproblem(.ArrayList comes from java,util package which also includes the Scanner class I just got them all using * ArrayList is a class that has its own methods like .size() and .add().
Related
At the start of the code the user determines a number of keywords and the keyword strings themselves, they place this into an array. Lets say the user says 3 keywords and they are "music", "sports" and "memes". After all this, say the user inputs in the program "I like sports". I simply want the program to respond with "Let's talk about sports" after recognising that the user said sports which is in the array that the user has essentially created.
I want to reference a string the user has predetermined then print it along with a message
I can see the potential of this working using for loops and going through every article until you find a match, I haven't done much work with booleans yet so I just need some assistance punching out the code then learning from it
this all has to happen inside a while loop so when that's done they can use a different keyword and get the same boring response
thanks
note: I don't actually have any of this code I want in my program yet, this code is just to show you kind of how it fits into the greater scheme of things.
import java.util.Scanner;
public class Assignment1 {
public static void main(String[] args) {
String kwArray[];
String UserMessage;
String Target = "";
int numKw = 0;
Scanner input = new Scanner(System.in);
System.out.println("How many keywords do you want?");
numKw = input.nextInt();
kwArray = new String[numKw];
System.out.print(System.lineSeparator());
input.nextLine();
for (int i = 0; i < numKw; i++) {
System.out.println("Enter keyword " + (i + 1) + ": ");
kwArray[i] = input.nextLine();// Read another string
}
for (int i = 0; i < numKw; i++) {
kwArray[i] = kwArray[i].toLowerCase();
}
int x = 0;
while (x == 0) {
System.out.println("Hey I'm a chatbot! Why don't you say something to me!");
System.out.println("These are the keywords you gave me");
for (String i : kwArray) {
System.out.print(i);
System.out.print(", ");
}
System.out.print(System.lineSeparator());
System.out.println("Or you can terminate the program by typing goodbye");
UserMessage = input.nextLine();
// Gives the user opportunity to type in their desired message
UserMessage = UserMessage.toLowerCase();
if (UserMessage.contains("?")) {
System.out.println("I will be asking the questions!");
}
if (UserMessage.contains("goodbye")) {
x = 1;
}
}
input.close();
}
}
If I am getting the question right, you want to check whether an element exists in the submitted keywords and want to reference it back if you further processing.
For this, instead of an array you could use a HashSet which can check the existence any element in O(1).
Updated the code, but I still feel your query is the same what I understood, putting the exact example of your use case below:
Scanner input = new Scanner(System.in);
Set<String> set = new HashSet<String>();
int keywords = input.nextInt();
for (int i=0; i<keywords; i++) {
//add to set set like:
set.add(input.readLine());
}
String userComment = input.readLine();
String[] userCommentWords = userComment.split(" ");
//you can iterate over the words in comment and check it in the set
for (int i=0; i<userCommentWords.length; i++) {
String word = userCommentWords[i];
if (set.contains(word)) {
System.out.println("Let's talk about "+word);
}
}
I have a question to do in my Java class, and it asks me to write a program that takes in n numbers from the user and outputs the average of them. I know I could do it a much simpler way, just by asking the user to enter the amount of values (s)he needs to enter at the beginning, but I want to create the program so the user doesn't necessarily have to know the number of values at the beginning.
So for this, I create an array of 100 length (which hopefully covers the amount the user needs to enter) inside a for loop (rendering that 100 length array null after the loop, so the program doesn't become too memory heavy) and running a counter trough each iteration. Once the user enters stop, the loop ends, and the values entered into the 100 length array gets transferred to an array the size of the count.
Here is the code:
import java.util.*;
import java.lang.*;
public class main
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
//Question 1
System.out.println("Enter your numbers. (Enter 'Stop' when you're done)");
int temp = 0;
String uInput = "";
char stopper;
int count = 0;
double total = 0;
int a = 0;
boolean inStop = true;
for (boolean stop = false; stop != true;)
{
int array [] = new int [100];
if (inStop == true)
{
System.out.println("point 5");
System.out.print("Input: ");
uInput = input.nextLine(); //reads user input
}
try //empty input repeater
{
System.out.println("point 1");
try //dealing with letters in string instead of numbers
{
System.out.println("point 2");
temp = Integer.parseInt(uInput); //converts string to int
array[count] = temp;
count++;
System.out.println(inStop);
if (inStop == false) //executes when stop has been reached
{
System.out.println("point 3");
int numberArray [] = new int [count]; //fills final array
for (int i = 0; i < count; i++)
{
numberArray[i] = array[i];
}
for (a = 0; a < numberArray.length; a++)
{
total = total + numberArray[a];
}
total = total / a;
stop = true; //ends parent loop
}
}
catch (NumberFormatException e) //catches letters in string and checks for stop
{
System.out.println("point 4");
stopper = uInput.charAt(0);
stopper = Character.toUpperCase(stopper);
if (stopper == 'S')
{
inStop = false;
System.out.println("point 6");
}
}
}
catch (StringIndexOutOfBoundsException e)
{
}
}
System.out.println("The average of the values entered is: " + total + ".");
}
}
The problem is, as you can see there are numerous numbered printouts that indicate (to me) where the program is at the moment. All runs fine, except for point 3. Point 3 for some reason doesn't execute whatsoever. No matter what I do. Now, the problem lies on line 34, temp = Integer.valueOf(uInput); //converts string to int
If I put in a print function directly after that line, that position doesn't print onto the screen. I believe there are no syntax or logic errors with that part, and so does my lecturer, however the code still doesn't execute and the program loops infinitely afterwards. Something is breaking either temp or uInput in that line and we cannot figure out what. I have compiled and ran the code through a different compiler to what I initially used and even tried in the Command Prompt with the same results (so it is not the IDE causing the issue).
Any insight we may have missed would be appreciated. Thanks.
p.s.: don't knock my lecturer, he didn't write the code, and it isn't that easily readable. He could easily know what the problem is, if not for any error in my explanations or his interpretations of how my program is meant to run.
I think that the reason you are having a problem identifying the issue is because of your code structure.
You have mixed the logic for informing the use, with the logic for reading the inputs, and calculating.
If your main method only deal with informing the user, and relies on another method to calculate the average,and another to read the user's input everything will be easier to read, follow and see that you are parsing "stop" as an int.
public static void main(String[] args) {
System.out.println("instructions");
int[] all = readUserInputs();
double ave = calculateAverage(all);
System.out.println("message " + ave);
}
private static double calculateAverage(int[] numbers) {
// I will leave it to you to fill this out
return yourValue;
}
private static String readUserInputs() {
Scanner input;// as above
int[] values; // is an array best? What about a List?
for (int i = 0; ; i++) {
String line = input.nextLine();
if ("stop".equals(line) {
break;
}
//try to parse and put into array/list
}
return values;
}
Hopefully you will find this easier to read and work with,I have left a few gaps for you to fill in.
I am trying to pass an array from one method to another method and then copy the contents of that array into a new array. I am having trouble with the syntax to accomplish that task.
Does anyone have some reference material that I could read about this topic or maybe a helpful tip that I could apply?
I apologize if this is a noob question, but I have only been messing with Java for 3-4 weeks part time.
I know that Java uses pass by value, but what where I'm getting lost is...should I invoke the sourceArray before copying it to the targetArray?
My goal here is not to be just handed an answer, I need to understand WHY.
Thanks...in advance.
package cit130mhmw08_laginess;
import java.util.Scanner;
public class CIT130MHMW08_Laginess
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter the total number of dealers: ");
int numDealers = input.nextInt();
numDealers = numberOfDealers(numDealers);
System.out.printf("%nPlease enter the required data for each of your dealers:");
dataCalculation(numDealers);
}//main
//METHOD 1
public static int numberOfDealers(int dealers)
{
int results;
Scanner input = new Scanner(System.in);
while(dealers < 0 || dealers > 30)
{
System.out.printf("%nEnter a valid number of dealers: ");
dealers = input.nextInt();
}
results = dealers;
return results;
}//number of dealers methods
//METHOD 2
public static void dataCalculation(int data)
{
String[] dealerNames = new String[data];
Scanner input = new Scanner(System.in);
System.out.printf("%nEnter the names of the dealers:%n ");
for(int i = 0; i < data; i++)
{
String names =input.nextLine();
dealerNames[i]= names;
}
int[] dealerSales = new int[data];
System.out.printf("%nEnter their sales totals: %n");
for(int i = 0; i < data; i++)
{
int sales = input.nextInt();
dealerSales[i] = sales;
}
for(int i = 0; i < data; i++)
{
System.out.println(" " + dealerNames[i]);
System.out.println(" " + dealerSales[i]);
}
//gather the required input data.
//Perform the appropriate data validation here.
}//data calculations
//METHOD 3
public static int commission(int data)
{
//Create array
int[] commissionRate = new int[dealerSales];
//Copy dealerSales array into commissionRate
System.arraycopy(dealerSales, 0, commissionRate, 0, dealerSales.length);
//calculate the commission array.
//$1 - $5,000...8%
//$5,001 to $15,000...15%
//$15,001...20%
//
}//commission method
}//class
If you want to copy an array, you can use the Arrays.copyOf(origin, length) method. It takes 2 arguments, first one is the array from which the data is supposed to be copied and second is the length of the new array, and import java.util.Arrays.
-See the link for more info https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#copyOf(int[],%20int)
This question already has answers here:
Get specific ArrayList item
(8 answers)
Closed 7 years ago.
The code is trying to take String entries, add them to an array and then stop when no text is written (user just presses enter). Then it is meant to display all of the String items in the array thus far on new lines.
The error in my title is coming up on my if query, and I'm additionally getting error's reading the value 'x' in the for loop as a variable (cannot find symbol).
Can anyone help me out
import java.util.Scanner;
import java.util.ArrayList;
public class FirstPart {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ArrayList<String> tillEmpty = new ArrayList<String>();
int i = 0;
while (true) {
System.out.print("Type a word: ");
tillEmpty.add(reader.nextLine());
if (tillEmpty[i].isEmpty()) {
break;
} else {
i++;
}
}
System.out.println("You typed the following words: ");
for (x = 0; x < tillEmpty.size; x++){
System.out.println(tillEmpty.get(x));
}
}
}
The error message is telling you exactly what is wrong. You've got an ArrayList and are trying to treat it as if it were an array. It isn't, and you can't use array indices, [i] on it. Instead use the get(...) method as any tutorial will tell you (and which I strongly recommend that you read -- Google can help you find one).
Your tillEmpty is not an array but an arraylist...you have to use tillEmpty.get(i).isEmpty instead of tillEmpty[i]
You missed int in your for loop:
for (int x = 0; x < tillEmpty.size; x++){
System.out.println(tillEmpty.get(x));
}
You are accessing list as Array, use below code, this should work:
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ArrayList<String> tillEmpty = new ArrayList<String>();
int i = 0;
while (true) {
System.out.print("Type a word: ");
tillEmpty.add(reader.nextLine());
if (tillEmpty.isEmpty()) {
break;
} else {
i++;
}
}
System.out.println("You typed the following words: ");
for (int x = 0; x < tillEmpty.size(); x++){
System.out.println(tillEmpty.get(x));
}
}
in my java class we were learning about arrays and this question came up. I have tried to solve it and can't seem to fulfill the requirements. I can read in the user inputs and have it limited to only 5 elements (one of the other requirements), also the values have to be between 10 and 100 I have also done that. But I cannot seem to "not print" the duplicate values. The array accepts the duplicate values. They don't have to be taken out, just not printed. Here is my code so far:
import java.util.Arrays;
import java.util.Scanner;
public class ArrayTest {
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int size = 5;
int InpNum[] = new int[size];
for (int i = 0; i < InpNum.length; i++){
while (InpNum[i] <= i){
System.out.println("Please type a number between 10 and 100: ");
InpNum[i] = in.nextInt();
while (InpNum[i] < 10 || InpNum[i] > 100){
System.out.println("Error: Please type an integer between 10 and 100: ");
InpNum[i] = in.nextInt();
}
Arrays.sort(InpNum);
System.out.println(Arrays.toString(InpNum));
}
while (Search(InpNum, i) == true){
System.out.println("ERROR: Please enter a number that is not a duplicate of the other numbers you have entered");
InpNum[i] = in.nextInt();
}
}
}
// I can't seem to implement the method below in a useful manner.
public static boolean Search(int InpNum[], int searchedNum) {
for(int i : InpNum) {
if (i == searchedNum) {
return true;
}
}
return false;
}
}
I would consider restructuring your application.
Instead of placing the number the user inputs into the array immediately, store it in a local variable. Then run all the checks you need to run, and add it to the array only if it passes all of them.
You should only have one while loop in the whole program (the outer one). All those others are greatly confusing the issue and making the problem much harder than it has to be.
So, in psudo-code:
int index = 0;
while (true)
{
int num = in.nextInt();
// if not between 10 and 100, continue
// if it would make the array larger than 5, continue
// (or perhaps break out of the loop, since we've filled the array)
// if it is already in the array, continue
// all the checks passed, so add it to the array!
InpNum[index++] = num;
}
As a side note, what you really need is a Set. This is a collection which is guaranteed to have no duplicates and allows you to answer the question "do I contain this value?" in an efficient manner using the method Set.contains( Object ).
So I would create a TreeSet or HashSet and put every number the user types into it. Your Search function would then simply be a one liner calling contains( searchedNum ) on your set.
A lazy way is to just create a second array that can hold the values as you go.
Loop through the input array and put the current element into the new array IF that array doesn't have that element already.
Then replace the old array with the weened out one.
Easiest way
So what I do is first ask the number. Then save the number in a variable before entering it inside the array. Then I check if that number is already in it wih search. If it is I ask for a new number. If it is not I check if it is between 10 and 100, if it is not I ask for a new. I fit is I enter It inside the array. I have to check where an empty place is because the sort mixes up the array everytime
import java.util.Arrays;
import java.util.Scanner;
public class ArrayTest
{
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int size = 5;
int InpNum[] = new int[size];
for (int i = 0; i < InpNum.length; i++){
System.out.println("Please type a number between 10 and 100: ");
int number = in.nextInt();
//while (InpNum[i] <= i){
while (Search(InpNum, number) == true){
System.out.println("ERROR: Please enter a number that is not a duplicate of the other numbers you have entered");
number = in.nextInt();
}
while (number < 10 || number > 100){
System.out.println("Error: Please type an integer between 10 and 100: ");
number = in.nextInt();
}
int counter = 0;
for (int j = 0; j < InpNum.length && counter == 0; j++){
if(InpNum[j] == 0){
InpNum[j] = number;
counter++;
}
}
Arrays.sort(InpNum);
System.out.println(Arrays.toString(InpNum));
//}
}
}
// I can't seem to implement the method below in a useful manner.
public static boolean Search(int InpNum[], int searchedNum) {
for (int i = 0; i < InpNum.length; i++){
if (InpNum[i] == searchedNum) {
return true;
}
}
return false;
}
}