So, this is basically what I have to do:
Ask the user to enter as many ints as they want, and tell them to type “done” when they are done entering the numbers.
Store these numbers in a data structure. (Think carefully about which one to use.)
Write a method that computes the sum of all the elements in the data structure.
Write a method that finds the smallest positive number in the data structure (return 9999 if there aren’t any positive numbers).
Call these methods on the data structure with the user’s numbers.
I have already written some of the code, but it's taking me no where.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
if (in.hasNextInt())
System.out.println(in.nextInt());
else
in.next();
}
}
}
By using the Java8 stream we could write this more efficiently and in a fewer lines of code than using the equivalent for loop.
import java.util.*;
class Main {
// Returns an array containing all inputted integers.
public static int[] getInts() {
List<Integer> list = new ArrayList<Integer>();
System.out.println("Enter integers or done to exit and press enter: ");
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
if (in.hasNextInt())
list.add(in.nextInt());
else if (in.next().equals("done"))
break;
}
return list.stream().mapToInt(i->i).toArray();
}
// Returns the sum of the integers, if the array is empty it returns 0.
public static int sum(int[] arr) {
return Arrays.stream(arr).sum();
}
// Returns 9999 if the array is empty or only has negative integers.
public static int min(int[] arr) {
return Arrays.stream(arr).filter(i -> i > 0).min().orElse(9999);
}
public static void main(String[] args) {
int[] arr = getInts();
System.out.println(Arrays.toString(arr));
System.out.println(sum(arr));
System.out.println(min(arr));
}
}
Output:
Enter integers or done to exit and press enter:
5 3 1 done // Our Input.
[5, 3, 1]
9
1
Here is a change that will lead you into the right direction:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
if (in.hasNextInt()) {
addNumber(in.nextInt());
} else {
final String string = in.next();
if ("done".equals(string.toLowerCase())) {
compute();
} else {
System.err.println("Invalid input " + string + ". Aborting...");
}
return;
}
}
}
private static void compute() {
// Do your magic here
}
private static void addNumber(int number) {
// Change this to code that stores the number
System.out.println(number);
}
EDIT: Some insight in what has changed. The very basic structure you had was alright. I mean, you got the right idea. I added the addNumber() method that will be called every time you get a number in the input. Now, inside that method you can write code for storing the value in a set or list maybe.
Then, if the input doesn't get a integer we just get whatever it is as a string a compare to "done". If it's equal we call compute() method. Inside that method you should write code that computed whatever calculation you are requested to do. Using the values in the set/list.
If the string isn't "done" we consider that an error.
Related
I realized the issue was due to me creating a new scanner/reader object(the new scanner has a blank input), the issue still persists - how do I use the same input stream for both methods (or) how do I use the same scanner reader for both methods
Original question: how to pass on the main method input stream to called method
So I'm taking in formatted input which is like this from geek for geeks (this is important to my error)
1
4
1 2 3 4
And I am using scanner class to read the numbers into variables. This is my code
// code to print reverse of input string after reading the length of the string and no. of testcases
class Main {
public static void main (String[] args) {
int i,t,n;
String x,y;
Scanner scan = new Scanner(System.in);
try {
t=scan.nextInt();
scan.nextLine();
REV rv=new REV();
for (i=0;i<t;i++){
rv.reverse();
}
}catch (Exception e){
return;
}
}
}
class REV{
public void reverse(){
int i,a[],n;
Scanner scan = new Scanner(System.in);
try {
n=scan.nextInt();
scan.nextLine()
a= new int[n];
for (i=n-1;i>=0;i--){
a[i]=scan.nextInt();
}
System.out.println(a[i]);
}catch(Exception E){
return;
}
}
}
I get no output for this (java.util.NoSuchElementException if I don't use try and catch)
I am able to read the variables in the main method but my input stream becomes empty for the new method
I verified this by using nextLine() both in the main() method and reverse() method as shown
public static void main (String[] args) {
int t,n;
String x,y,z;
t=scan.nextInt();
x=scan.nextLine();
n=scan.nextInt(); //to eat up the n input
y=scan.nextLine();
z=scan.nextLine();
System.out.println(x+y);
....
}
output-
141 2 3 4
and
public void reverse(int n){
....
String k,j;
k = scan.nextLine(); //replacing n- to check what n=scanInt() reads
j= scan.nextLine();
System.out.println(x +y);
....
}
Output is blank again (java.util.NoSuchElementException)
I think this means the input stream is empty for the reverse() method.
So how do I pass on the main() input to reverse()
Note: 1. if I don't use try{} and catch{} it gives me java.util.NoSuchElementException
I'm aware I have made the code needlessly a little complicated, this is due to me trying to solve this problem
I got the try{} and catch{} solution from here, but it doesn't solve my empty input problem
4.This made me understand the empty input exception
Create a method instead of making an Object of a class and then calling the method. (Unless you want it that way).
Create a single static Scanner and use it everywhere.
private static Scanner scanner = new Scanner(System.in)
To print an array use System.out.println(Arrays.toString(a));.
Reductant use of scanner.nextLine() after Scanner.nextInt.
import java.util.Arrays;
import java.util.Scanner;
class Main {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int i, t, n;
String x, y;
t = scanner.nextInt();
for (i = 0; i < t; i++) {
reverse();
}
}
private static void reverse() {
int i;
int[] a;
int n;
n = scanner.nextInt();
a = new int[n];
for (i = n - 1; i >= 0; i--) {
a[i] = scanner.nextInt();
}
System.out.println(Arrays.toString(a));
}
}
Is this your desired output?
I need the user to enter an integer input, check whether it starts by 0 and tell the user to enter another integer if that is the case
I tried parsing the integer input to a string, that works but only once. The string cannot be edited when program loops
I think the solution should not at all involve strings because i need the program to loop and check over and over until the input is valid (ie has no leading zeroes)
Splitting each digit of the int into an array does not work also because the ways i found pass by string.
public static void main(String[] args){
Scanner key = new Scanner(System.in);
int in= 0;
boolean looper=true;
while (looper == true) {
System.out.println("Enter an integer");
in = key.nextInt();
/* check whether in has any leading zeroes, example of
wrong input: 09999, 0099*/
if (/*in has no leading zeroes*/)
looper = false;
}
key.close();
}
Maybe another answer would be to have a method that creates a brand new string every time the program loops, so maybe like a recursion that automatically creates strings, not sure if that's even a thing though.
You can make it cleaner by using a do-while loop instead of while(true). Note that an integer starting with 0 is an octal number e.g.
public class Main {
public static void main(String[] args) {
int x = 06;
System.out.println(x);
// x = 09; // Compilation error - out of range
}
}
Thus, 06 is a valid integer. For your requirement, you can input to a String variable and prompt the user to again if it starts with a zero. If the input does not start with a zero, try parsing it to an int and process it if it succeeds; otherwise, loopback e.g.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
String input = "";
int in = 0;
boolean valid = true;
do {
System.out.print("Enter an integer: ");
input = key.nextLine();
if (input.startsWith("0")) {
System.out.println("Invalid input");
valid = false;
} else {
try {
in = Integer.parseInt(input);
System.out.println("You entered " + in);
// ... process it
valid = true;
} catch (NumberFormatException e) {
System.out.println("Invalid input");
valid = false;
}
}
} while (!valid);
}
}
A sample run:
Enter an integer: 09999
Invalid input
Enter an integer: xyz
Invalid input
Enter an integer: 123
You entered 123
As an aside, never close a Scanner(System.in) because it also closes System.in and there is no way to open it without rebooting the JVM.
The basis of my problem is here: https://github.com/experiencethebridge1/primeGap
Bottom line, I want to create an array in which the output of a method will populate the elements of the new array.
This is not homework.
package primenumbermethod;
import java.util.Scanner;
public class PrimeNumberMethod {
public static void main(String[] args) {
System.out.print("How many prime numbers do you want to work with? ");
Scanner input = new Scanner(System.in);
int arraySize = input.nextInt();
// Invoke printPrimeNumbers method
System.out.println("If I can ever get it to work, the number of the "
+ "elements in the array I want to build will be " + arraySize +".");
System.out.println();
printPrimeNumbers(arraySize);
// How can I read parts of a method into elements of an array?
int[] myList = new int[arraySize];
}
public static int printPrimeNumbers(int numberOfPrimes) {
final int NUMBER_OF_PRIMES_PER_LINE = 10; // Display 10 per line
Scanner input = new Scanner(System.in);
System.out.print("What number do you want to start from? ");
int number = input.nextInt();
int count = 0; // Count the number of prime numbers
// Repeatedly find prime numbers
while (count < numberOfPrimes) {
// Print the prime number and increase the count
if (isPrime(number)) {
count++; // Increase the count
if (count % NUMBER_OF_PRIMES_PER_LINE == 0) {
// Print the number and advance to the new line
System.out.printf("%-15d\n", number);
} else {
System.out.printf("%-15d", number);
}
}
number++;
}
return 0;
}
// Method for checking if number is prime
public static boolean isPrime(int number) {
for (int divisor = 2; divisor <= number / 2; divisor++) {
if (number % divisor == 0) {// If true, number is not prime
return false; // Number is not a prime
}
}
return true; // Number is prime
}
}
Tried using global variables, abstraction does not apply (but could).
The main method initiates the program, then traces to method printPrimeNumbers, then into method boolean isPrime. I want to return the output of that method into a new array...
The array size will be defined by the user input <"How many prime numbers do you want to work with? ">, and then <"What number do you want to start with?>
Problem, I can't seem to pass the output of a method into the elements of an array.
Thoughts?
I would suggest you should restructure your code in the following way:
public static void main(String[] args) {
int numberOfPrimes = readIntFromCommandLine...;
int numberToStartWith = readIntFromCommandLine...;
int[] primeNumbers = getPrimeNumbers(numberOfPrimes, numberToStartWith);
// maybe extract this to another method as well
for (int prime : primeNumbers) {
// do whatever you want with prime, e.g. print it - or sum it, or multiply or whatever
}
}
public static int[] getPrimeNumbers(int amount, int from) {
int[] primes = new int[amount];
int count = 0;
/* now put your current prime logic here and whenever you
find a prime set primes[count] = newlyFoundPrime; */
}
public static boolean isPrime(int number) { /* stays the same */ }
It is generally a good idea to only ask for user input at a well defined point in your code, not all over the place. Therefore I placed the two inputs at the front. Another generally good idea is to make every method (maybe except for the main method) only do one thing. Your isPrime is a good example of that. Moving the printing logic out of getPrimeNumbers simplifies that method and lets you handle the printing at another, dedicated place.
I am trying to write a code where you sort a given list of numbers, and I'm trying to do so using ArrayList. I am using a while loop to allow for repeated inputs. This is my code:
import java.util.Scanner;
import java.util.ArrayList;
public class sortinggg {
public static Scanner keyboard = new Scanner(System.in);
public static ArrayList<Integer> number = new ArrayList<Integer>();
public static void main (String [] args) {
int count= 0;
System.out.println("Enter your numbers.");
while (keyboard.hasNextInt()); {
number.add(keyboard.nextInt());
}
The integer count is irrelevant right now, as I only use it when I am sorting the list.
The problem is that after I input my numbers, even if I type in a string (for example), the program doesn't move on to the next line of code. Am i missing anything here?
P.S. I tired looking up questions that have been asked previously on this topic, but none of the solutions suggested worked for me.Thank you for your help in advance!
Try this:
import java.util.ArrayList;
import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
Scanner keyboard = new Scanner(System.in);
ArrayList<Integer> number = new ArrayList<Integer>();
System.out.println("Enter your numbers:");
while (keyboard.hasNextInt()) {
number.add(keyboard.nextInt());
}
}
}
Modifications:
In while (keyboard.hasNextInt()); remove semicolon(;) at the end.
Here while loop will keep adding values to the arraylist until you provide int values.
In the first place the ; just after the while is wrong. It does not let you to execute the body. Then how are you going to skip the loop. You may ask the end user to enter some special value and use it to break the loop. The corrected version is given below.
public static void main(String[] args) {
int count = 0;
System.out.println("Enter your numbers or -1 to skip.");
while (keyboard.hasNextInt()) {
int num = keyboard.nextInt();
if (num == -1) {
break;
}
number.add(num);
}
System.out.println(number);
}
I am trying to read an integer from the user, then print even if that number is an even number or odd otherwise. I have been told I can assume that the user types a valid integer. The input/output should match the following example:
Type a number: 14
even
What am I missing? Any ideas on how I can get the desired inputs and expected outputs? Test1[3][Test4]4
import java.util.Scanner;
public class evenOdd {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int even = scan.nextInt();
int odd = scan.nextInt();
if ((even%2)==0){
System.out.println("Type a number:"+ even);
}
else {
System.out.println("Type a number:"+ odd);
}
}
}
The problem is that you have all your variables and order of the flow of your program mixed up. In English this is what you are doing
Prompt user for an integer, call that integer "even"
Prompt user for an integer, call that integer "odd"
If the integer called "even" is divisible by 2 without a remainder then print "type a number" and then the value of the integer called "even"
Otherwise print "type a number" and then the value of the integer called "odd"
You only need to read a value from the user once, then decide which message to print based on that value:
import java.util.Scanner;
public class evenOdd {
public static void main(String[] args) {
System.out.println("Type a number:");
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
if ((number%2)==0){
System.out.println("even");
}
else {
System.out.println("odd");
}
}
}
I have pointed out some issues in your code. Please correct them.
import java.util.Scanner;
//follow java naming convention and name class as "EvenOdd"
public class evenOdd {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int number = scan.nextInt(); //renamed to number
int odd = scan.nextInt(); //do not need this variable
if ((number %2)==0){
System.out.println("Even");
}
else {
System.out.println("Odd");
}
}
}
Ask the user the question first so that he knows he has to input a number
System.out.println("Type a number: ");
You can simply just get 1 input from the user and store on the same variable
int input = scan.nextInt();
Then you would just check that 1 input with the if/else and display the correct output
if ((input%2)==0){
System.out.println(input + " is even.");
}
else {
System.out.println(input + " is odd.");
}