user input using while loop to store data - java

Can you please tell me what is wrong with the following java code.
I am trying to collect input from the user through Scanner class object then store it in an array by using while but it would be infinite loop if i don't supply a break condition , so i thought to break when the input equals "q", but it didn't work.
import java.util.*;
public class ProjectOne{
public static void main (String []arg){
ArrayList one = new ArrayList();
Scanner input = new Scanner(System.in);
System.out.println("Enter");
String x = input.next();
while ( input.hasNext()){
if (x !="q"){
one.add(input);
}
if (x == "q")
{
break;
}
System.out.println(one);
}
}
}

You don't compare String with ==. Use .equals() like
if (!x.equals("q")){
and
if (x.equals("q"))
Note : I think that you aren't using Scanner correctly. You take the input, but keep checking x, instead of the input.

Do not compare strings like x =="q"
USE .equals function in java for string comparison.
Replace your code with: x.equals("q") for x =="q" and !x.equals("q") for x !="q"

You are not reading updated value from Scanner. Below is updated code for your reference after correcting formatting and other errors. Also, instead of == sign, use equals() method for string comparison -
import java.util.*;
public class ProjectOne{
public static void main (String []arg ){
ArrayList one = new ArrayList();
Scanner input = new Scanner(System.in);
System.out.println("Enter");
String x = null;
while ( input.hasNext()) {
x = input.next();
if (!x.equals("q")) {
one.add(x);
}
if (x.equals("q")){
break;
}
}
System.out.println(one);
}

Scanner reads everything before your ENTER - the whole line you input.
I think that is what you need:
import java.util.ArrayList;
import java.util.Scanner;
public class ProjectOne
{ public static void main (String []arg ){
ArrayList one = new ArrayList();
Scanner input = new Scanner(System.in);
System.out.println("Enter");
String pattern;
String x = input.next();
while (true){
String line = input.next();
if(line.contains("q"))break;
else{
x = x + " " + line;
}
}
System.out.println(x);
}

Related

How to take multi-line input in Java

I'm trying to take multi-line user input in Java and split the lines into an array, I need this to solve a problem for an online judge. I'm using a Scanner to take input. I cant determine the end of input. I always get an infinite loop, since I don't know the size of input (i.e number of lines)
Terminating input with an empty String (clicking enter) is still an infinite loop. Code provided below.
public static void main(String[] args) {
ArrayList<String> in = new ArrayList<String>();
Scanner s = new Scanner(System.in);
while (s.hasNextLine() == true){
in.add(s.nextLine());
//infinite loop
}
}
I'm not even sure why the loop executes the first time. I believe the hasNextLine() should be false the first time ,since no input was taken yet. Any help or clarification appreciated.
You could use the empty line as a loop-breaker:
while (s.hasNextLine()){ //no need for "== true"
String read = s.nextLine();
if(read == null || read.isEmpty()){ //if the line is empty
break; //exit the loop
}
in.add(read);
[...]
}
You could end the loop with something like below. Here, the String "END" (case-insenstive) is used to signify end of the multi-line content:
public static void main(String[] args) {
ArrayList<String> in = new ArrayList<String>();
Scanner s = new Scanner(System.in);
while (s.hasNextLine()) {
String line = s.nextLine();
in.add(line);
if (line != null && line.equalsIgnoreCase("END")) {
System.out.println("Output list : " + in);
break;
}
}
}
You can use this code. It returns when the user press Enter on an empty line.
import java.util.Scanner;
import java.util.ArrayList;
public class Main {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
ArrayList<String> arrayLines = new ArrayList<>();
String line;
while(true){
line = scanner.nextLine();
if(line.equals("")){
break;
}
else {
System.out.println(line);
arrayLines.add(line);
}
}
System.out.println(arrayLines);
}
}
Best
You can do somthing like this:
while (s.hasNextLine() == true){
String line = s.nextLine();
if ("".equals(line)) {
break;
}
in.add(line);
//infinite loop
}

Knapsack Solution using Recursion and Array

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().

Collections.reverse method not reversing entry

My code below is supposed to accept an integer from the user, and then print whatever integer they enter in reverse order. I am getting no errors, but when I run this program the integer is not being printed in reverse. Can someone please help me figure out why?
import java.util.*;
public class ReverseDigits {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String response;
System.out.println("Please enter a whole number.");
response = sc.next();
reverseDigit(response);
}
public static void reverseDigit(String digit) {
ArrayList al = new ArrayList();
al.add(digit);
Collections.reverse(al);
System.out.println("Your number in reverse order is: " + al);
}
}
You misinterpreted what Collections.reverse does. This method reverses the list that you gave, not its content. Since you called this method with a list having a single element, the result will be the same list.
If you want to reverse a String, please refer to this question.
As a side-note: do not use raw types like ArrayList, this will get into trouble. Prefer the type-safe way ArrayList<String>.
Try this code.
ArrayList al = new ArrayList();
al.add(new StringBuffer(digit).reverse().toString());
If you have a collection of one, it is the same in reverse order as forward.
If you want to reverse the string representation of an integer, you can use StringBuilder to reverse the digits.
StringBuilder sb = new StringBuilder();
sb.append(digits);
sb.reverse();
System.out.println("Your number in reverse order is: "+ sb);
If you want to reverse a String why are you adding it to a list ?
Use this :
String s = sc.next();
StringBuilder sb = new StringBuilder(s);
System.out.println(sb.reverse());
The reverse(List<?>) method is used to reverse the order of the elements in the specified list. Since there is only one item in your collection, reverse order is same as the initial list. You can use the below code as you are trying to reverse an integer.
package com.stackoverflow.answer;
import java.util.*;
public class ReverseDigits {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter a whole number: ");
int number = scanner.nextInt();
System.out.println(String.format("Your number in reverse order is: %d", reverse(number)));
scanner.close();
}
public static int reverse(int x) {
return reverse(x, 0);
}
private static int reverse(int x, int y) {
return x == 0 ? y : reverse(x / 10, y * 10 + x % 10);
}
}

How to add user input into an ArrayList until a keyword triggers it to stop?

So I'm trying to write a Java program that allows a user to input words at the command line. The program should stop accepting words when the user enters "STOP". Store the words in an ArrayList. The word STOP should not be stored in the list.
Next, print the size of the list, followed by the contents of the list.
Then, remove the first and last words stored in the list, but only if the list has a length greater than two. Finally, reprint the contents of the list.
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class t2_lesson1_template {
public static void main (String str[]) throws IOException
{
ArrayList<String> list = new ArrayList<String>();
Scanner scan = new Scanner(System.in);
do
{
System.out.println("What would you like to add to the list?");
String input = scan.nextLine();
list.add(input);
}
while( scan.nextLine() != "STOP");
if ( list.size() < 2)
{
System.out.println(list);
System.out.println(list.size());
}
else
{
list.remove(0);
list.remove(list.size()-1);
System.out.println(list);
System.out.println(list.size());
}
}
}
It keeps on prompting the question, but never recognizes when "STOP" is the input. If somebody could please help me figure out what's wrong, it'd help a lot. Thank you!
In line:
scan.nextLine() != "STOP"
you compare references to two objects. If you need to compare objects you should use equals() method of Object.
Read about equals() in the documentation.
But there is another problem in your code. You read next line twice.
In loop and in while(...) statement.
Try this:
System.out.println("What would you like to add to the list?");
String input = scan.nextLine();
while(!input.equals("STOP"))
{
list.add(input);
input = scan.nextLine();
}
Change scan.nextLine() != "STOP" to while(!scan.nextLine().equalsIgnoreCase("stop")); and try.
Reason :
The String Literal "STOP" will not be be same as the String value "STOP" entered from the keyboard (in your case). == compares references. You have to check value of 2 Strings not references.
Try the below code:-
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class t2_lesson1_template {
public static void main(String str[]) throws IOException {
ArrayList<String> list = new ArrayList<String>();
Scanner scan = new Scanner(System.in);
System.out.println("What would you like to add to the list?");
String input = scan.nextLine();
while (!input.equals("STOP")) { // compare string using equals(Object o) method
list.add(input);
System.out.println("What would you like to add to the list?");
input = scan.nextLine();
}
System.out.println("Size of list = " + list.size());
System.out.println("Input list:-\n" + list);
if (list.size() > 2) {
list.remove(0);
list.remove(list.size() - 1);
System.out.println("List after removing first and last eliment:-\n" + list);
}
}
}
import java.io.*;
import static java.lang.System.*;
import java.util.Scanner;
import java.lang.Math;
import java.util.ArrayList;
public class U7_L1_Activity_One{
public static void main (String str[]) throws IOException {
ArrayList<String> list = new ArrayList<String>();
Scanner scan = new Scanner(System.in);
System.out.println("Please enter words, enter STOP to stop the loop.");
String input = scan.nextLine();
while (!input.equals("STOP")) { // compare string using equals(Object o) method
list.add(input);
input = scan.nextLine();
}
System.out.println(list.size());
System.out.println(list);
// System.out.println("Size of list = " + list.size());
//System.out.println("Input list:-\n" + list);
if (list.size() > 2) {
list.remove(0);
list.remove(list.size() - 1);
System.out.println(list);
// System.out.println("List after removing first and last eliment:-\n" + list);
}
System.out.println(list);
}
}

Program not replacing letters

I am currently learning how to use Array lists in Java and i am stuck on a simple but annoying problem..
import java.util.*;
public class ReplacingALetter
{
public static void main (String[] args)
{
String word = "Banana";
List underscore = new ArrayList(word.length());
int i;
for (i=0; i<word.length(); i++)
{
underscore.add(i, "x");
}
System.out.print(underscore);
System.out.println();
System.out.print("Enter a letter: ");
Scanner sc = new Scanner(System.in);
String letter = sc.nextLine();
if (sc.equals("B"))
{
underscore.set(word.indexOf("B"),"B");
}
System.out.print(underscore);
}
}
For some reason it is not substituting the first x in the array 'underscore' with the letter B :/
The Output of that code is [ x x x x x x ]
But when i enter this code:
import java.util.*;
public class ReplacingALetter
{
public static void main (String[] args)
{
String word = "Banana";
List underscore = new ArrayList(word.length());
int i;
for (i=0; i<word.length(); i++)
{
underscore.add(i, "x");
}
System.out.print(underscore);
System.out.println();
System.out.println("Switching First x with B: ");
underscore.set(word.indexOf("B"),"B");
System.out.print(underscore);
}
}
It works Perfectly and the output is [ B x x x x x ]
Can't figure out what i'm doing wrong....
The only difference I spotted in your 2 examples is, that one uses a if condition:
if (sc.equals("B")) {
underscore.set(word.indexOf("B"),"B");
}
whereas the other one executes
underscore.set(word.indexOf("B"),"B");
unconditionally. Your sc is a java.util.Scanner, "B" is a string. They can't be equal, so the method is never called in your first example.
if (sc.equals("B")) this condition is always false because sc is not an object of class String.
You should change your code to:
if (letter.equals("B")) {
underscore.set(word.indexOf("B"),"B");
}
if (letter.equals("B"))
{
underscore.set(word.indexOf("B"),"B");
}
you have to check if letter is equal to B not sc is equal to B.
String letter = sc.nextLine();
if (letter.equals("B"))
{
underscore.set(word.indexOf("B"),"B");
}
Modify this snippet
Scanner sc = new Scanner(System.in);
String letter = sc.nextLine();
if (sc.equals("B"))
{
underscore.set(word.indexOf("B"),"B");
}
to
Scanner sc = new Scanner(System.in);
String letter = sc.nextLine();
if (letter.equals("B"))
{
underscore.set(word.indexOf("B"),"B");
}
In the former you are comparing Scanner object with the string "B" which will never be equal.
In the latter it compares the string read from standard input to "B".

Categories

Resources