I am new at java programming and am working on an exercise where the user is to input ints into an array and then stop the user input by entering a negative int value. All works well except the array prints 0 beyond the user input. So if a user enters 5 values and then one negative value only the five values should print not the user input values and 95 0s.
Any assistance would be greatly appreciated.
Here is my code:
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner (System.in);
int array[] = new int [100];
System.out.println ("Enter values up to 100 values, " +
"enter a negative number to quit");
for (int i=0; i< array.length; i++)
{
array[i] = scan.nextInt();
if (array [i] < 0)
{
break;
}
}
for (int i =0; i<array.length; i++)
{
System.out.println(array[i]);
}
}
When you declare an int in Java, it will default to 0 if you do not specify a value for it. When you declare your array,
int array[] = new int [100];
You are essentially making an array of 100 0's. You can see a small example of this by running the following code:
public static void main(String[] args) throws Exception {
int array[] = new int [1];
System.out.println("The value of i is: " + array[0]);
}
What you could do, is store the negative value into your array, and then stop printing if you reach that value.
for (int i =0; i<array.length; i++){
if(array[i]<0){
break;
}
System.out.println(array[i]);
}
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner (System.in);
int array[] = new int [100];
int totalValuesEntered = 0;
System.out.println ("Enter values up to 100 values, " +
"enter a negative number to quit");
for (int i=0; i< array.length; i++)
{
array[i] = scan.nextInt();
if (array[i] < 0)
{
totalValuesEntered = i;
break;
}
}
System.out.println("Your entries are:");
for (int i =0; i<totalValuesEntered; i++)
{
System.out.println(array[i]);
}
}
You are looping 100 times no matter what on the last loop, and you are saving the userinput no matter what they enter.
In order to achieve what you want. Declare a new integer enteredValues to count how many values the user entered before exiting.
public static void main(String str[]) throws IOException {
Scanner scan = new Scanner(System. in );
int array[] = new int[100];
System.out.println("Enter values up to 100 values, " +
"enter a negative number to quit");
int enteredValues = 0;
for (int i = 0; i < array.length; i++) {
int userInput = scan.nextInt(); //save nextInt to a variable
if (userInput >= 0) {
array[i] = userInput;
enteredValues++;
} else{
break;
}
}
for (int i = 0; i < enteredValues; i++) {
System.out.println(array[i]);
}
}
Related
Create 8 randomly generated integer values between 1 to 50. DONE
Display the series of values on screen. DONE
Users has to enter value. Find index & display.
if value cannot be found, display -none.
This is pretty easy. As you already completed step 1 and 2 you just have to ask the user for an input, search your array and output the index, if the input matches a value in the array.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int[] numbers = new int[8];
for(int i = 0; i < 8; i++) {
numbers[i] = random.nextInt(50) + 1;
System.out.print(numbers[i] + ", ");
}
System.out.print("\nInput value: ");
int input = scanner.nextInt();
boolean found = false;
for(int i = 0; i < numbers.length; i++) {
if(input == numbers[i]) {
System.out.println("Index: " + i);
found = true;
}
}
if(!found) {
System.out.println("none");
}
}
I am looking to input an integer between 10 and 100 into a one dimensional array, and if the value already exists anywhere in the array, do not insert it into the array, but notify user and resume input until 5 unique numbers are added.
Here is my code. I know it's not right, but you can see that what I am trying to do is use simple for loops and a search method to get the numbers, store them into the array and search for a duplicate. My problem in my code is that I can't seem to set the number I just entered as the variable 'key' which I need to send to the method 'search'.
// input an integer between 10 and 100, add to array and print results. if value is already in array, notify user, print array. keep adding to array until 5 unique values have been entered
import java.util.Scanner;
public class ArraySearch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] list = new int[5];
for (int i = 0; i < list.length; i++) {
System.out.println("Enter number: ");
list[i] = input.nextInt();
}
int count = search(list, key);
System.out.println("It has been entered.");
}
public static int search(int[] list, int key) {
int count = 0;
for (int i = 0; i < list.length; i++) {
if (list[i].equals(key)) {
;
}
count++;
}
return (count);
}
}
Simple example with array. Could improve with alternate data structure list set.
The search() method is essentially included within the while() loop, namely the for() loop examples the search for a target number already being included.
int c = 0; is declared before the loops and makes sure to find 5 unique numbers.
import java.util.Arrays;
import java.util.Scanner;
public class ArraySearch {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[] list = new int[5];
int c = 0;
System.out.println("Enter number: ");
while (c < 5 && s.hasNext()) {
int n = s.nextInt();
boolean has = n >= 10 && n <= 100;
for (int i = 0; i <= c && !has; ++i)
if (list[i] == n)
has = true;
if (!has) {
System.out.println("It has been entered.");
list[c++] = n;
}
}
System.out.println("Result = " + Arrays.toString(list));
s.close();
}
}
Alternate version:
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class ArraySearch {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Set<Integer> set = new HashSet<Integer>(5);
int c = 0;
System.out.println("Enter number: ");
while (c < 5 && s.hasNext()) {
int n = s.nextInt();
if ((n < 10) || (n > 100) || !set.add(n))
continue;
else {
System.out.println("It has been entered.");
c++;
}
}
System.out.println("Result = " + set);
s.close();
}
}
additionally, using search()
public class App {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[] list = new int[5];
for (int i = 0; i < 5; i++) {
System.out.println("Enter number: ");
int n = s.nextInt();
if ((n >= 10 && n <= 100) && search(list, n) == 0) {
list[i] = n;
System.out.println("It has been entered.");
} else
i--;
}
System.out.println("Result = " + Arrays.toString(list));
s.close();
}
public static int search(int[] list, int key) {
int count = 0;
for (int i = 0; i < list.length; i++) {
if (list[i] == key) {
count++;
}
}
return count;
}
}
Edit: also added the 10-100 spec
edit2: using your approach with search() method
You are saving the input directly in the array.
Save the input in a temporal variable which you'll pass to search. And based on result of search you add to the array or prompt for another input.
int[] list = new int[5];
for (int i = 0; i < list.length; i++) {
System.out.println("Enter number: ");
int temp = input.nextInt();
if(search(list,temp) == 0)
list[i] = temp;
}else{
System.out.println("It has been entered.");
i--;
}
}
I am tasked with several objectives in my assignment, I am to read a file, which i believe I did correctly, and from that file of integers, put it into an array. It wont let me compile the code, it comes up with an error at smallest. So, how do I printout the method of the min?
public class jlrogers2 {
public static void reader(int[] arr) throws FileNotFoundException {
Scanner scanner = new Scanner(new FileReader("numbers.txt"));
int i = 0;
while(scanner.hasNextInt())
{
arr[i++] = scanner.nextInt();
}
}
public static int minnimum(int[] arr){
int smallest =arr[0];
for (int i = 1; i>arr.length; i++){
if (arr[i] > smallest)
{
smallest= arr[i];
System.out.println(smallest);
}
}
return smallest;
}
public static void main(String [] args) throws FileNotFoundException
{
Scanner in = new Scanner (System.in);
System.out.println("Enter 1 for max index value.\nEnter 2 for min index value.\nEnter 3 to search for an index value.\n"
+ "Enter 4 for display all index's\nEnter 5 for numbers in a range.\nEnter 6 to exit menu. ");
int number = in.nextInt();
if(number==6){
System.out.println("Thank you for being awesome");
}
if (number==5){
System.out.println(minnimum(smallest)) // here is my issue }
}
}
Change for (int i = 1; i>arr.length; i++) to for (int i = 0; i<arr.length; i++)
And also your logic to find smallest is wrong. Actually you are finding the largest.
To find smallest put it as
if(arr[i] < smallest ) inside for loop
Change the main as
public static void main(String [] args) throws FileNotFoundException
{
Scanner in = new Scanner (System.in);
System.out.println("Enter 1 for max index value.\nEnter 2 for min index value.\nEnter 3 to search for an index value.\n"
+ "Enter 4 for display all index's\nEnter 5 for numbers in a range.\nEnter 6 to exit menu. ");
int number = in.nextInt();
int arr[] = new int [200];//change this according to the requirement
if(number==6){
System.out.println("Thank you for being awesome");
}
if (number==5){
reader(arr);
System.out.println(minnimum(arr));
}
}
There seem to be many problems with your code:-
->First as others have pointed change for (int i = 1; i>arr.length; i++) to for (int i = 1; i<arr.length; i++)
-> variable int smallest used, is not a class level variable and also is never locally declared in main()
-> method minimum() is never called from main, also method reader() seems to be not called
-> close the scanners after use, call scanner.close() at method end
Make some changes hence:-
-> main() would now look like:-
public static void main(String [] args) throws FileNotFoundException
{
int[] arr=new int[100];
reader(arr);//call this to populate arr[]
Scanner in = new Scanner (System.in);
System.out.println("Enter 1 for max index value.\nEnter 2 for min index value.\nEnter 3 to search for an index value.\n"
+ "Enter 4 for display all index's\nEnter 5 for numbers in a range.\nEnter 6 to exit menu. ");
int number = in.nextInt();
if(number==6){
System.out.println("Thank you for being awesome");
}
if (number==5){
System.out.println(minnimum(arr));
}
in.close();
}
To find smallest element you need to change your loop like this:
for (int i = 1; i < arr.length; i++)
{
if (arr[i] < smallest)
{
smallest = arr[i];
}
}
The problem I'm trying to solve is given an integer N find the digits in this number that exactly divide N(division that leaves 0 as remainder) and display their count. For N=24, there are 2 digits − 2 & 4. Both of these digits exactly divide 24. So our answer is 2. The input format is The first line contains T (number of test cases) followed by T lines (each containing an integer N).
Here's my code
public static void main(String[] args) throws IOException {
System.out.println("Please enter your inputs");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
ArrayList<String> arr = new ArrayList<String>();
int i=0;
while ((line = br.readLine()) != null && line.length() != 0){
arr.add(line);
i++;
}
if(Integer.parseInt(args[0]) != (args.length -1)){
System.out.println("Wrong number of inputs");
}else{
for(int j = 1; j< args.length; j++){
System.out.println(findDivisor(Integer.parseInt(args[j])));
}
}
}
public static int findDivisor(int n){
int count = 0;
String s = Integer.toString(n);
char[] c= s.toCharArray();
for(int i = 0; i< c.length; i++){
String temp = Character.toString(c[i]);
int num = Integer.parseInt(s);
if(num == 0)
count += 0;
else if(n%num == 0){
count +=1;
}
}
return count;
}
On adding an Arraylist to read to inputs, the program goes into an infinite loop it seems. As in based on the first input I need to take the number of inputs and then process. As in if the first input is 2, my program should await 2 more command line inputs and on the third press of enter run. How do I invoke that functionality into this code.
Try using the Scanner class:
import java.util.Scanner;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
// Read in T.
int T = sc.nextInt();
// Read in T integers, for each print the number of digit divisors.
for (int i = 0; i < T; i++){
int n = sc.nextInt()
System.out.println(findDivisor(n));
}
}
If you want to wait until all input is in first, create an array of size T to keep track of your integers:
import java.util.Scanner;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
// Read in T.
int T = sc.nextInt();
int[] myNumbers = new int[T];
// Read in all input, and calculate the number of digit divisors.
for (int i = 0; i < T; i++){
int n = sc.nextInt()
myNumbers[i] = findDivisor(n);
}
// For each input, print out the number of digit divisors.
System.out.println("Number of digit divisors:");
for (int i = 0; i < T; i++){
System.out.println(myNumbers[i]);
}
}
A link to the assignment:
http://i.imgur.com/fc86hG9.png
I'm having a bit of trouble discerning how to take a series of numbers and apply them to an array without a loop. Not only that, but I'm having a bit of trouble comparing them. What I have written so far is:
import java.util.Scanner;
public class Lottery {
public static void main(String[] args) {
int userInputs[] = new int[5];
int lotteryNumbers [] = new int[5];
int matchedNumbers =0;
char repeatLottery = '\0';
Scanner in = new Scanner (System.in);
do{
System.out.println("Enter your 5 single-digit lottery numbers.\n (Use the spacebar to separate digits): ");
for(int i = 0; i <5; i++ )
userInputs[i] = in.nextInt();
System.out.println("Your inputs: ");
printArray(userInputs);
System.out.println("\nLottery Numbers: ");
readIn(lotteryNumbers);
for(int i=0; i<5; i++) {
System.out.print(lotteryNumbers[i] + " ");
}
matchedNumbers = compareArr(userInputs, lotteryNumbers);
System.out.println("\n\nYou matched " + matchedNumbers + " numbers");
System.out.println("\nDo you wish to play again?(Enter Y or N): ");
repeatLottery = in.next().charAt(0);
}
while (repeatLottery == 'Y' || repeatLottery == 'y');
}
public static void printArray(int arr[]){
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
public static void readIn(int[] List) {
for(int j=0; j<List.length; j++) {
List[j] = (int) (Math.random()*10);
}
}
public static int compareArr (int[] list1, int[] list2) {
int same = 0;
for (int i = 0; i <= list1.length-1; i++) {
for(int j = 0; j <= list2.length-1; j++) {
if (list1[i] == list2[j]) {
same++;
}
}
}
return same;
}
}
As you'll notice, I commented out the input line because I'm not quite sure how to handle it. If I have them in an array, I should be able to compare them fairly easily I think. This is our first assignment handling arrays, and I think it seems a bit in-depth for only having one class-period on it; So, please forgive my ignorance. :P
Edit:
I added a new method at the end to compare the digits, but the problem is it compares them in-general and not from position to position. That seems to be the major issue now.
your question isn't 100% clear but i will try my best.
1- i don't see any problems with reading input from user
int[] userInput = new int[5]; // maybe here you had a mistake
int[] lotterryArray = new int[5]; // and here you were declaring your arrays in a wrong way
Scanner scanner = new Scanner(system.in);
for ( int i = 0 ; i < 5 ; i++)
{
userInput[i] = scanner.nextInt();
} // this will populate your array try to print it to make sure
Edit : important in the link you shared about the assignment the compare need to check the value and location so if there are two 5 one in input one in loterry array they need to be in the same location check the assignment again
// to compare
int result = 0 ; // this will be the number of matched digits
for ( int i = 0 ; i < 5 ; i++)
{
if ( userInput[i] == loterryArray[i] )
result++
}
// in this comparsion if the digits are equale in value and location result will be incremented