I must read few Int Vector. I put it to ArrayList.
Methods to read have own class.
In main function i create object and start method readMy which is to be put in the list of values which are entered on one line separated by a space. The problem is that after the number of loops ends, it is not completed. how can I leave this loop except ctrl + d.
public class Wektory
{
List<Integer> wektor = new ArrayList<Integer>();
public Wektory(){}
public void readMy()
{
Scanner C=new Scanner(System.in);
while(C.hasNextInt())
wektor.add(C.nextInt());
}
}
I checked the contents of the list and it is correct
I don't know if i did understand your point but you can do something like this:
Scanner C=new Scanner(System.in);
boolean quit = false;
while (!quit){
System.out.println("please enter the values : \r");
if(C.hasNextInt()){
int value = C.nextInt();
C.nextLine();
wektor.add(value);
}
// to end you can do this or you can break directly :
if(wektor.size() >= 10){
System.out.println("the loop has been ended");
quit =true;
}
}
You can use a unique int value to exit the scanner e.g. -1
public class Wektory
{
List<Integer> wektor = new ArrayList<Integer>();
public Wektory(){}
public void readMy()
{
Scanner C=new Scanner(System.in);
while(C.hasNextInt()){
int val = C.nextInt();
if(val==-1){
break;
}
wektor.add(C.nextInt());
}
}
}
Related
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().
I'm trying to print the value of z as output but My code doesn't finish execution..it reaches the line "here" but never reachs the last line "z is ".
i'm guessing s = sc.nextInt(); is the problem.
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int x = 0;
int y = 0;
int z = 0;
int u = 0;
int n = sc.nextInt();
int s = sc.nextInt();
while(sc.hasNextInt()) {
if(s != -1){
y = s;
if(sc.hasNextInt()){
s = sc.nextInt();
}
}
while(s == -1){
x++;
System.out.println("s is "+s);
z = Math.abs(y - x) + u;
System.out.println("s is "+s);
System.out.println("x is " + x+ " y is "+ y+" z is "+z);
if(sc.hasNextInt()){
s = sc.nextInt();
System.out.println("s33 is "+s);
}
}
if(z != 0){
u = z;
}
x = 0;
y = 0;
System.out.println("here");
}
System.out.println("z is" +z);
}
}
Thanks.
Its not going in infinite loop but instead you already have two values stored in Scanner which you are checking with hasNextInt(). Hence its always true and waits for next input to check. If you go with entering Int values it will be in same while loop. Enter non-integer like String to go out of while loop and your program will end.
Actually You are waiting for input in both while loops and hence its waiting for your input.
Problem
You are using a Scanner on the system input stream System.in. That means sc.hasNextInt() tries to get the next value from the underlying stream, which is System.in. However, this stream will just prompt you for new input and return it to the Scanner. Once the Scanner receives a newline character, it checks, if the sequence before is an int or not. In case you only hit enter, the sequence is empty, hence ignored. It is not the loop that is indefinitely executed if you hit enter repeatedly, your code is stuck at sc.hasNextInt(), which gets no new token (because of the empty sequence), and asks the underlying stream again and again.
However, if you enter anything but an int, like 0.2 or abc... the Scanner will return false, as the sequence is not empty and not an int.
Solution
If you want to keep your code as it is and you want that hasNextInt() returns false when you hit enter (only newline), you can wrap your Scanner in this wrapper:
import java.util.Scanner;
public class ScannerWrapper {
private Scanner scanner;
private Integer current;
public ScannerWrapper(Scanner scanner) {
this.scanner = scanner;
}
public boolean hasNextInt() {
// Current is not null, if method is called multiple
// times, the value was checked already, it is an integer
if (current != null) {
return true;
} else {
// Reads line including newline character
String nextLine = scanner.nextLine();
try {
// Try to covert the input to an integer
current = Integer.parseInt(nextLine);
return true;
} catch (NumberFormatException e) {
// Input is not an integer
return false;
}
}
}
public int nextInt() {
// Used the already checked value or request new input
if (current != null) {
int next = current;
current = null;
return next;
} else {
int next = scanner.nextInt();
// Consume the newline character
scanner.nextLine();
return next;
}
}
}
This class reads complete lines and converts them into int, if possible. As you cannot push back the last token you have read with a Scanner, this class stores it temporarily, so multiple calls to hasNextInt() do not skip values. In your method just add:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ScannerWrapper sc = new ScannerWrapper(scanner);
int x = 0;
// Rest of your code...
}
I created an array of three integers that I ask input to the user, then I return that array and instantiated the class, but I don't have access to the array items:
import java.util.Scanner;
public class Input {
public static int[] getInput() {
Scanner sc = new Scanner (System.in);
int choice[] = new int[3];
System.out.println("Type the options: ");
System.out.println("Plate: ");
choice[0] = sc.nextInt();
System.out.println("Dessert: ");
choice[1] = sc.nextInt();
System.out.println("Drink: ");
choice[2] = sc.nextInt();
return choice;
}
}
Main class:
public class Main
{
public static void main (String [] args) {
Menu menu = new Menu();
Input input = new Input();
menu.ShowMenu();
Input.getInput();
//I want to compare choice[0] here
if (input.getInput() == 1) {
//code block
}
Do I need to write a method to the three choices? I just want to pass the three user inputs to use in the Main class if's and else's.
Instead of Input.getInput(), write int[] arr=Input.getInput(). You have to store the result of the Method in a variable.
You can than access the Elements with arr[index], index starting with 0, for example a[0]
Save the return value in a variable.
int[] choices = Input.getInput();
if (choices[0] == 1) {
...
}
int[] inputs = Input.getInput();
if (inputs[0] == 1) { ... }
That is an array and is static... so you can save this declaration:
Input input = new Input();
and you must only do:
if (Input.getInput()[0] == 1) {
//code block
}
How to get an user input using scanner class and use it inside method to process, and obtain output?
Example : You get two numbers from the user and pass it to 4 methods to get its value after addition, subtraction, multiplication, division.
The scanner should be in main class and not inside every method.
Here is my code, it's in basic form. I want to get input from the user and process it inside the methods and get the result:
class Calc{
public static void main(String[] args){
add();
sub();
mul();
div();
{
void Add() {
int a=5,b=10;
sum=a+b;
System.out.println(sum);
}
void sub() {
int a=5,b=10;
sub=a=b;
System.out.println(sub);
}
void mul() {
int a=5,b=10;
mul=a*b;
System.out.println(mul);
}
void div() {
int a=5,b=10;
div=a/b;
System.out.println(div);
}
}
}
}
Simply use the array or nextInt() method to get the number of input and passed it to your method.
For e.g. If you are supposed two take two input at time
Scanner sc = new Scanner(System.in);
int[] integers = new int[2];
for(int i = 0; i < 2; i++)
{
integers[i] = sc.nextInt();
}
Now use the integers array to get the value from index and passed it to your method
You can get input by using new Scanner(System.in), as follows:
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
add(a,b);
sub(a,b);
multiply(a,b);
divide(a,b);
I'm writing some Java code that'll make a guessing game, where a random number is generated based on your maximum value and you have to guess the correct number. You can also set the amount of attempts you can get. This is where the problem occurs.You see, you can set a number of attempts in number form or write out "unlimited". I have an example of the code that does this here with comments to help you out:
import java.util.Scanner;
public class Game{
public static int processMaxAttempts;
public static Scanner maxAttempts;
public static String processMaxAttempts2;
public static void main(String args[]){
//Prints out text
System.out.println("Fill in your maximum attempts OR write \"unlimited\".");
//Creates a scanner
maxAttempts = new Scanner(System.in);
//Looks at the scanner "maxAttempts" and reads its integer value
processMaxAttempts = maxAttempts.nextInt();
//Looks at the scanner "maxAttempts" and reads its string value
processMaxAttempts2 = maxAttempts.nextLine();
//Prints out "unlimited" if "maxAttempts" has a string value and "set" if it has an integer value
if(processMaxAttempts2.equals("unlimited")){
System.out.println("unlimited");
}else{
System.out.println("set");
}//Close else
}//Close main method
}//Close class
What happens is a get an error that says this:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:857)
at java.util.Scanner.next(Scanner.java:1478)
at java.util.Scanner.nextInt(Scanner.java:2108)
at java.util.Scanner.nextInt(Scanner.java:2067)
at com.pixelparkour.windows.MainGameWindow.main(MainGameWindow.java:34)
That error targets this line of code:
processMaxAttempts = maxAttempts.nextInt();
So... yeah. I have no idea. I'm very new to Java (I've been learning it for only 3 days) and I'm a bit helpless. I'd love to know what my problem is so I can apply to it the future and program some cool games!
You need to put a check on content type before reading the content.
What you need is :
if(maxAttempts.hasNextInt()){ // this will check if there is an integer to read from scanner
processMaxAttempts = maxAttempts.nextInt();
} else {
processMaxAttempts2 = maxAttempts.nextLine();
}
if(processMaxAttempts2!=null && processMaxAttempts2.equals("unlimited")){
System.out.println("unlimited");
}else{
System.out.println("set");
}
I think this is what you are looking for
public class Test
{
private int guessableNumber;
private Integer maxAttempts;
public Test()
{
maxAttempts = 0;
}
public void doYourStuff(){
Scanner scan = new Scanner(System.in);
Random random = new Random();
System.out.println("Please enter your amount of guesses or type unlimited for unlimited guesses");
String s = scan.next();
if(s.toUpperCase().equals("UNLIMITED")){
guessableNumber = random.nextInt(100);
}
else {
try{
maxAttempts = Integer.parseInt(s);
guessableNumber = random.nextInt(100) + Integer.parseInt(s);
}catch(Exception e){
System.out.println("You did not enter a valid number for max attempts");
}
}
int counter = 0;
System.out.println("Type in a guess");
while(scan.nextInt() != guessableNumber && counter <=maxAttempts){
System.out.println("You did not guess correctly try again");
++counter;
}
if(counter > maxAttempts){
System.out.println("You have exceeded your max attempts");
}
else {
System.out.println("Correct you guessed the correct number: "+ guessableNumber);
}
}
public static void main(String[] args)
{
Test test = new Test();
test.doYourStuff();
}
}
One little trick that always works for me is just going ahead and making a second scanner, i.e. num and text, that way you can always have one looking for int values and the other dealing with the Strings.