My goal is to implement a method named add that receives a reference to a Scanner object associated with a stream of input consisting of integers only. The method reads all the integers remaining to be read from the stream and returns their sum.
So if the input were 3 51 204 17 1040, the returned value would be 1315. The method must not use a loop of any kind (for, while, do-while t accomplish its job).
My attempt is shown below:
public void add(Scanner scanner){
Scanner input = new Scanner(System.input);
String s = input.nextLine();
String[] numbers = str.split(" ")
int[] ints = new int[numbers.length];
}
The specific issue that I am running into is the conversion of the string array into an integer array.
Since you can't use a loop of any kind, I think you are supposed to use recursion. You need to actually return a value. Presumably an int. Something like check if there is an int. If so, read it and recursively add any other int(s); Otherwise, return 0. Like,
public int add(Scanner input){
if (input.hasNextInt()) {
return input.nextInt() + add(input);
}
return 0;
}
Related
I want to read in five numbers from the console. To convert the input strings into int[x] for each number i tried to use a for loop. But it turns out that #1 incrementation is dead code and #2 my array is not initialized, even though i just did.
I'm on my first Java practices and would be happy to hear some advices.
My code:
public static void main(String[] args) throws IOException {
System.out.println("Type in five Numbers");
int [] array;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
for(int x=0; x<5; x++){
String eingabe = br.readLine();
array[x] = Integer.parseInt(eingabe);
break;
}
reserve(array); }
First off, you didn't initialize your array, you only declared an array variable (named array). I highly suggest reading and practicing this fundamental concept of Java before proceeding further, because otherwise you will likely be confused later on. You can read more about the terms declaration, initialization, and assignment here.
Another issue, as Andrew pointed out, is that you used the keyword break in your first iteration of the loop. This keyword terminates a block of code, so your loop will only run once and then exit for good.
This code can be greatly simplified with a Scanner. A Scanner reads input from a specified location. The scanner's constructor accepts two inputs: System.in, for the default input device on your computer (keyboard), or a File object, such as a file on your computer.
Scanners, by default, have their delimeter set to the whitespace. A delimeter specifies the boundary between successive tokens, so if you input 2 3 5 5, for example, and then run a loop and invoke the scanVarName.nextInt() method, it will ignore the white spaces and treat each integer in that single line as its own token.
So if I understand correctly, you want to read input from the user (who will presumably enter integers) and you want to store these in an integer array, correct? You can do so using the following code if you know how many integers the user will enter. You can first prompt them to tell you how many integers they plan to enter:
// this declares the array
int[] array;
// declares and initializes a Scanner object
Scanner scan = new Scanner(System.in);
System.out.print("Number of integers: ");
int numIntegers = scan.nextInt();
// this initializes the array
array = new int[numIntegers];
System.out.print("Enter the " + numIntegers + " integers: ");
for( int i = 0; i < numIntegers; i ++)
{
// assigns values to array's elements
array[i] = scan.nextInt();
}
// closes the scanner
scan.close();
You can then use a for-each loop to run through the items in your array and print them out to confirm that the above code works as intended.
This is the original prompt:
Write program that gets a comma-delimited String of integers (e.g. “4,8,16,32,…”) from the user at the command line and then converts the String to an ArrayList of Integers (using the wrapper class) with each element containing one of the input integers in sequence. Finally, use a for loop to output the integers to the command line, each on a separate line.
import java.util.Scanner;
import java.util.ArrayList;
public class Parser {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
ArrayList<String> myInts = new ArrayList<String>();
String integers = "";
System.out.print("Enter a list of delimited integers: ");
integers = scnr.nextLine();
for (int i = 0; i < myInts.size(); i++) {
integers = myInts.get(i);
myInts.add(integers);
System.out.println(myInts);
}
}
}
I was able to get it to where it accepts the list of delimited integers, but I'm stuck on the converting piece of it and the for loop, specifically printing each number to a separate line.
The easiest way to convert this string would be to split it according to the comma and apply Integer.valueOf to each element:
List<Integer> converted = Arrays.stream(integers.split(","))
.map(Integer::valueOf)
.collect(Collectors.toList());
Printing them, assuming you have to use a for loop, would just mean looping over them and printing each one individually:
for (Integer i : converted) {
System.out.println(i);
}
If you don't absolutely have to use a for loop, this could also be done much more elegantly with streams, even without storing to a temporary list:
Arrays.stream(integers.split(","))
.map(Integer::valueOf)
.forEach(System.out::println);
First, you can convert the input string to String[], by using the split method: input.split(","). This will give you an array where the elements are strings which were separated by ",".
And then, to convert a String to an Integer wrapper, you can use:
Integer i = Integer.valueOf(str);
Integer i = Integer.parseInt(str)
myInts is empty, your data is in integers.
I suggest that you search about the fonction : split (from String)
I have this major head wrecker of a assignment and I am really lost of how to go at it. The assignment is as follows:
Write a recursive method in Java public static String reverse(Scanner scan), the scanner object contains numbers and the numbers are supposed to be returned in reverse order as a string. And here's the tricky part, you're not allowed to use arrays, lists or string it's only suppose to declare one single variable.
The input of reverse(new Scanner("20 33 40") for example should return:
" 40 33 20".
I would know how to go at it if it wasn't because of the restraints. I really don't know how I am suppose to solve this. I'm pretty new at programming and I know some of you are against helping out with assignments, I would just appreciate any pointers.
First possibility use String
You can use directly the String as your data structure. Adding at the beginning instead of at the end when you read a new number.
Basically with a code like:
String str = "";
while (yourcondition) {
str = scanner.nextInt() + " " + str;
}
return str;
Second possibility use StringBuffer or StringBuilder
StringBuilder str = new StringBuilder();
while (yourcondition) {
str.insert(0, " ").insert(0, scanner.nextInt());
}
return str.toString();
Third possibility use recursion:
public String read(String str, Scanner scanner) {
if (testExitCondition) {
return str;
}
return scanner.nextInt() + " " + str;
}
// Called with System.out.println(read("", scanner));
Note
The first solution use String creating many instances of String, but having only one reference to it.
The second solution use existing classes that internally uses arrays to operate on strings.
The third leave to the JVM the reference to the created String, so no explicit reference to the string is present in the code. This is the only that don't have explicit variable declarations (only in the signature of method, not outside).
You can use scanner.hasNext() with a while loop. Use StringBuilder to collect prepaired data.
Scanner scanner = new Scanner("12 52 10");
StringBuilder builder = new StringBuilder();
while (scanner.hasNext()) {
builder.insert(0, scanner.next()).insert(0, " ");
}
builder.replace(0, 1, "");
System.out.println(builder.toString());
In your limit , you get the result then output the string in reverse order.
public static void main(String[] args) {
Scanner scanner = new Scanner("20 33 40");
System.err.println(scan(scanner));
}
public static String scan(Scanner scanner) {
if (scanner.hasNext()) {
String next = scanner.next();
String result = scan(scanner);
return result.isEmpty() ? next : result + " " + next;
}
return "";
}
Writing recursive methods is a must-learn for each programming school. The technique is always the same:
Check whether the end condition has been reached and return the initial value (in math we speak of a neutral element).
Split some part of the input, call the recursive method with the remainig input, then assemble the result of that call with the previously split part.
According to that common algorithm, you have to implement your method this way:
public static String reverse(Scanner scan) {
if (scan.hasNextInt()) { // check whether to continue or not
int number = scan.nextInt(); // split part
return reverse(scan) + " " + number; // assemble this part and the rest
} else {
return ""; // return an initial or base value (the neutral element)
}
}
The call to scan.nextInt() must be done before calling the recursion, as otherwise the next number would not have split.
You only wanted pointers...
You must write a recursive function String reverse(Scanner scanner) that returns the numbers in reverse order. The point of this assignment would be to get you to grok recursion, which can be like thinking backwards.
You get passed a Scanner in the first run of your reverse() function with the following contents:
"20 33 40"
So, read an integer from your Scanner:
int value = scanner.readInt();
Your field value would contain the integer 20 and the scanner object would now seem to contain just this:
"33 40"
So, assuming that you had a reverse function that would output " 40 33" then you could just paste value in behind it and get " 40 33 20".
Recursion is pretending that your function already does what it should do and calling yourself with smaller versions of your input until you get to the trivial version. Your first call is with "20 33 40", the second call with "33 40", the third call "40" and the last with "".
The last call where you get passed in "" is easy. You just check for that and return "".
The other calls are not that hard either. You just read an int, and paste it together with the output from the recursive call to reverse.
I need to check the array to see if the user input is already present, and display a message as to whether it is or isn't there. The first part is working, but I tried to create a method for the word check, and I'm not sure if I'm on the right path or not, cheers.
import java.util.Scanner;
public class InputLoop {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String array[] = new String[10];
int num = array.length, i = 0;
System.out.println("Enter a word");
for (i = 0; i < num; i++) {
while (scan.hasNextInt()) // while non-integers are present...
{
scan.next(); // ...read and discard input, then prompt again
System.out.println("Bad input. Enter a word");
}
array[i] = scan.next();
WordCheck();
}
}
public void WordCheck(String[] i) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter another word");
if (scan.next().equals(array[i])) {
System.out.println("The word has been found");
} else {
System.out.println("The word has not been found");
}
}
}
Right. You've clearly gone down a bad thought process, so let's just clear the slate and have a re-think.
Step one: You want to take some user input
Step two: Compare it with all previous user inputs to see if it's present.
If it is present, return a message indicating that value has been inputted.
otherwise ignore the input and continue execution
Repeat step one.
The solution
So, let's review what you've got, and how you need to change it.
public static void main(String[] args)
If I were you, I would avoid calling methods directly from here. If you do, every method will need to be static, which is a pointless adjustment in scope for the functionality of your class. Create a new instance of your class, inside the main method, and move this code to the class' constructor. This will remove the need to make every single method static.
Scanner scan = new Scanner(System.in);
String array[] = new String[10];
Okay, so you've created a scanner object that takes input from the System.in stream. That's a reasonable thing to do when taking input from the keyboard. You've also created an array to contain each item. If you only want the user to be able to type in 10 values, then this is fine. Personally, I would use an ArrayList, because it means you can take in as many user inputs as the user desires.
Secondly, you want a function to compare the input, with all other inputs. What you have at the moment clearly isn't working, so let's have another go at it.
You will need some input, userInput, and a collection to compare it against, allInputs.
allInputs needs to be accessible from any point in the program, so it's probably wise to make it into a field, rather than a local variable.
Then, because you're comparing userInput against all values, you're going to need a foreach loop:
for(String s : allInputs)
{
if(s.equals(userInput))
{
// Output message code.
}
}
Now the trick is fitting this inside a loop that works with this program. That is up to you.
One simple solution is to use a Set:
Set<String> words = new HashSet<String>();
Add words with the add() method and check if a word is already added with contains(word) method.
EDIT
If you must use Arrays you can keep the array sorted and do a binary search:
Arrays.sort(words);
boolean isAlreadyAdded = Arrays.binarySearch(words, newWord) >= 0;
You're going to have to loop through the entire array and check if scan.next() equals any of them - if so return true - as such:
String toCheck = scan.next();
for (String string : i) { //For each String (string) in i
if (toCheck.equals(i)) {
System.out.println("The word has been found");
return;
}
}
System.out.println("The word has not been found");
This supposes you call WordCheck(), passing the array to it - this method also has to be static for you to call it from the main() method.
You can use the arraylist.contains("name") method to check if there is a duplicate user entry.
I am trying to split a user inputed set, such as { 1 2 3 4 }, as a string, into an array list so that when I print out the array list it will read {1, 2, 3, 5}. Here is my code so far. I am not really sure how the Scanner.next() method works, but I am attempting to use it. This is for a small portion of my program. Actually it's like the beginning.
import java.util.Scanner;
import java.util.ArrayList;
public class practice {
public static void main (String[]args){
Scanner stdIn = new Scanner (System.in);
String set;
String set2 = "";
System.out.print("Enter set:");
set = stdIn.nextLine();
if(set.charAt(0) == '{'){
for(int i =1; i<set.length(); i++){
set2 += set.charAt(i);
}
}
else if(set.charAt(1) == '{'){
for(int i = 2; i <set.length();i++){
set2 += set.charAt(i);
}
}
System.out.print(set2);
ArrayList<Integer> array = new ArrayList<Integer>();
while(stdIn.next() != "}"){
set2 = stdIn.next();
array.add(Integer.parseInt(set2));
}
System.out.print(array);
}
}
You should use the String.split(String) and String.replaceAll(String, String) methods in String in order to do a lot of what your code currently does.
You can get the user input as you are currently doing it, with stdIn.nextLine();, but afterward, you can do the string processing in an easier way.
First, you should remove the unnecessary characters, and end up with just a sequence of numbers separated by spaces.
You can do this by simply calling the replaceAll method, and provide the regular expression, which is really simple in this case.
Then you can call the String.split method to find each element in the set.
String in = stdIn.nextLine();
// Need to escape the characters because
// these characters mean something special in regular expressions
String filtered = userInput.replaceAll("(\\[\\{\\}\\],"," ");
String[] numbers = filtered.split("\\s+");
ArrayList <Integer> myNumbers = new ArrayList <Integer> ( numbers.length );
for ( String number : numbers )
myNumbers.add ( Integer.parseInt ( number ) );
UPDATE
If you need to use a scanner, you can use a scanner for the String that has been filtered
Scanner s = new Scanner ( filtered );
ArrayList <Integer> myNumbers = new ArrayList < Integer > ();
while ( s.hasNext() )
{
myNumbers.add(s.nextInt());
}
Perhaps you should use Java's split method on a string.
EDIT:
If you are required to use scanner, you might want to start off something like:
String input = "foobar";
Scanner s = new Scanner(input);
and then probably iterate on s using a while loop and the hasNext method. Inside this loop, you will possibly need to use one of the next methods in Java's scanner api to work with each token as string. If you only want to print things out, then you don't really need to add tokens to an arraylist. You can directly use System.out.print(). In any case, its well worth working this out on your own and exploring the scanner api.
You could shorten your while statement by taking in straight "ints" instead of actually passing then converting strings, like:
while (stdIn.next() != '}') {
array.add(stdIn.nextInt());
}
However, you'd require some error handling to make sure you actually got ints just in case your user passed in something else. However, if you're wanting to print the integers as strings it may be better to use an String array instead of an Integer array.