//Java nested loop, if the user input less than 1 and Great than 11 it must display error message. Implementing java nested for loops.
import java.util.Scanner;
class Main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the size: ");
int size = input.nextInt();
if (size < 1 && size > 11)
System.out.println("INVALID NUMBERS");
for (int rows = size; size > 0; rows++) {
for (int colums = size; colums < 11; colums++) {
System.out.print("#");
}
}
System.out.println();
}
}
Tags
if(size<1 && size>11)
size can not both be less than 1 AND greater than 11.
You'll need a logical OR here:
if(size<1 || size>11)
Not exactly sure what you mean, but to my understanding this is what you're looking for?
int size=input.nextInt();
if(size<1 || size>11) {
System.out.println("INVALID NUMBERS");
}
else{
for (int rows=size;size>0;rows++){
for(int colums=size;colums<11;colums++){
System.out.print("#");
}
}
}
First of all question is not very elaborative and does not mention what the end result should look like.
To my understanding, this code will result in infinite loop when size entered is greater than 0, because of the line:-
for (int rows = size; size > 0; rows++) , the loop will be infinite because the test condition is always greater than zero.
Related
The goal of my code: To be able to write a program where I can enter in any number int as a command-line argument and displays how many digits in the integer number are 7s.
My problem is that I don't understand why my code only runs through the for-loop once. I inserted the system.out.println(sevens); to see how many times this loop works when I compile with a random number like 456789.
I could only think of a for-loop to use for this one and fixed some simple mistakes in the beginning. I also checked my brackets
public class TestingSevens {
public static void main(String[] args) {
int sevens = Integer.parseInt(args[0]);
int count = 0;
for (int i = 0; i < args.length; i++) {
if (sevens%10 == 7) {
count += 1;
}
sevens = sevens/10;
System.out.println(sevens);
}
System.out.println(count);
}
}
The result of inputting a number like 456789 is "45678" for the first print and the second print is "0." I know the number for some reason only runs through the loop once since it cuts off the last number before jumping out of the loop to print the count...any advice?
I presume you want to iterate over each digit of sevens. Since sevens initialized from args[0], the loop limit should match and look at args[0].length() rather than args.length.
for (int i = 0; i < args[0].length(); i++)
An alternate way to write the loop is to iterate until sevens reaches 0. That lines up better with the loop body; both use the same variable.
while (sevens > 0) {
if (sevens%10 == 7) {
count += 1;
}
sevens /= 10;
System.out.println(sevens);
}
Your code has logic errors, so to check if the iterated number is number 7 you need to turn the number into a string and check if the character is the desired character using: numberString.charAt(index)
Below is the corrected code:
public static void main(String[] args) {
int sevens = Integer.parseInt(args[0]);
String numberString = String.valueOf(sevens);
int count = 0;
for (int i = 0; i < numberString.length(); i++) {
char c = numberString.charAt(i);
if (c == '7') {
count += 1;
}
System.out.println("Input number: " + sevens);
}
System.out.println("Count of 7 numbers: " + count);
}
First post here so I'm hoping I don't screw up.
My task is to have a user enter an array of 10 integers and then input another integer separately and have the program either retrieve that number if it's in the array, or give an error if not.
I'm having trouble comparing the inputted integer with those in the array.
Here's part of my code, with the rest found below:
try{
System.out.print("Please enter 10 integers to store in an array and then press enter: ");
for(int index = 0; index < numbers.length; index++)
numbers[index] = input.nextInt();
if(numbers.length==10){ //method doesnt work properly if you input over 10 integers, only if you input less
System.out.print("Thanks for entering 10 integers. Now input an integer to check: ");
int compare = input.nextInt();
if(numbers[index] == compare){ //this is where the error is I believe
System.out.print(compare); //here too
}
http://pastebin.com/U5PdJgr6
Thank you in advance!
If you're using java-8, you can perform that easily using an IntStream
boolean contained = IntStream.of(inputtedNumbers)
.anyMatch(x -> x == numberToSearch);
Turn
if (numbers[index] == compare) {
System.out.print(compare);
}
Into
boolean found;
for (int number : numbers) {
found = number == compare;
if (found) break;
}
if (found) System.out.print(compare);
else throw new Exception("Number Not Found");
P.S. You don't need to check to make sure numbers.length is still 10. The length of an array is always final and can't change.
package integerarrayexceptions;
import java.util.Scanner;
import java.util.InputMismatchException;
public class IntegerArrayExceptions {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numbers[] = new int[10];
try{
System.out.print("Please enter 10 integers to store in an array and then press enter: ");
for(int index = 0; index < numbers.length; index++)
numbers[index] = input.nextInt(); //The loop only applies to this statement.
if(numbers.length==10){
System.out.print("Thanks for entering 10 integers. Now input an integer to check: ");
int compare = input.nextInt();
for (int index2 = 0; index2 < numbers.length; index2++) {
if(numbers[index2] == compare){
System.out.print(compare);
}
}
}
}
catch (InputMismatchException MismatchException)
{
System.out.print("One or more values entered is not an integer.");
}
}
}
There's a loop missing after you entered the compare value:
for (index = 0; index < numbers.length; index++) {
if(numbers[index] == compare){
System.out.print(compare);
}
]
You try to use the variable "index" outside the "for" loop, where it does not exist...
I am supposed to make a program that takes 10 numbers from a user input, find the largest and smallest number and display all the inputs from the user. This program does use an array. Here is my code:
import java.util.Scanner; // program uses Scanner
public class ArrayTester {
// begin execution
public static void main(String[] args) {
// declare and create array object
// declare smallest and largest int variables
int[] numbers;
numbers = new int[10];
int smallest = numbers[0], largest = numbers[0];
// create Scanner object
Scanner input = new Scanner(System.in);
// prompt user
System.out.print("Please enter 10 numbers: \n");
// use for loop to obtain user input
for (int counter = 0; counter < numbers.length; counter++) {
numbers[counter] = input.nextInt();
} // end obtaining input
// enhanced for loop to find largest and smallest values
for (int i : numbers) {
if (numbers[i] < smallest) {
smallest = numbers[i];
} // end finding smallest
else if (numbers[i] > largest) {
largest = numbers[i];
} // end finding largest number
} // end finding largest and smallest values
// for loop to print user input
System.out.printf("%s%8s\n", "Index", "Input");
for (int counter = 0; counter <= numbers.length; counter++) {
System.out.printf("%5d%8d\n", counter, numbers[counter]);
} // end printing input values
// print smallest and largest numbers
System.out.printf("Smallest number: %d\nLargest number: %d\n", smallest, largest);
System.out.print("Programmed by Christian Lapinig");
} // end main
} // end ArrayTester
At this point I am able to obtain user inputs, but I run into this problem:
Please enter 10 numbers:
454
392
33
41
6
44
39
21
12
2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 454
at ArrayTester.main(ArrayTester.java:32)
Would I need a try and catch block to fix this?
Your problem is related to the way you use the for-loop as already stated in the other answers. A shorter approach in Java 8 though, would be using a stream:
IntStream.of(numbers).max() and IntStream.of(numbers).min()
A try-catch would just swallow the exception. Your problem is that the enhanced for loop is iterating over the values of the array, but you're treating it like it's the index, so you check numbers[454] and immediately blow up because you're outside the length of the array.
Either iterate over the indexes, or just work with the values directly:
for (int i : numbers) {
if (i < smallest) {
smallest = i;
} // end finding smallest
else if (i > largest) {
largest = i;
} // end finding largest number
} // end finding largest and smallest values
for (int counter = 0; counter <= numbers.length; counter++)
You put =<, instead you should put <. if counter equals to length, it tries to reach out of range because indexes start from zero.
CHange
for (int i : numbers) {
to
for (int i=0;i<numbers.length;i++) {
Your problem is in this loop:
for (int i : numbers) {
This loop means iterates over the elements of the array, not its indexes. So, you can say:
for (int a : numbers) {
if(a > ...) {
....
}
Alternatively you can use array index like the following"
for (int i = 0; i < numbers.lenth; i++) {
if(numbers[i] > ...) {
.....
}
Change it to :
for (int i=0 ;i< numbers.length; i++) {
if (numbers[i] < smallest) {
smallest = numbers[i];
} // end finding smallest
else if (numbers[i] > largest) {
largest = numbers[i];
} // end finding largest number
}
AND <= to <
for (int counter = 0; counter < numbers.length; counter++) {
System.out.printf("%5d%8d\n", counter, numbers[counter]);
}
Try catch block will simply handle your error in a graceful way . It won't solve your problem.
In java 8, you can obtain an IntStream and get the summary statistics.
final IntSummaryStatistics stats = IntStream.of(numbers).summaryStatistics();
As many people pointed out, you are using the values of your for-each loop as and index, meaning your code tries to access the position of whatever number your user inputs in your array.
So to fix it, you just need to do
smallest = i;
and
largest = i;
I have made a program that outputs the number of repeats in a 2D array. The problem is that it outputs the same number twice.
For example: I input the numbers in the 2D array through Scanner: 10 10 9 28 29 9 1 28.
The output I get is:
Number 10 repeats 2 times.
Number 10 repeats 2 times.
Number 9 repeats 2 times.
Number 28 repeats 2 times.
Number 29 repeats 1 times.
Number 9 repeats 2 times.
Number 1 repeats 1 times.
Number 28 repeats 2 times.
I want it so it skips the number if it has already found the number of repeats for it. The output should be:
Number 10 repeats 2 times.
Number 9 repeats 2 times.
Number 28 repeats 2 times.
Number 29 repeats 1 times.
Number 1 repeats 1 times.
Here is my code:
import java.util.Scanner;
public class Repeat
{
static Scanner leopard = new Scanner(System.in);
public static void main(String [] args)
{
final int ROW = 10; //Row size
final int COL = 10; //Column size
int [][] num = new int[ROW][COL];
int size;
//Get input
size = getData(num);
//Find repeat
findRepeats(num, size);
}
public static int getData(int [][] num)
{
int input = 0, actualSize = 0; //Hold input and actualSize of array
System.out.print("Enter positive integers (-999 to stop): ");
//Ask for input
for(int i = 0; i < num.length && input != -999; i++)
{
for(int j = 0; j < num[i].length && input != -999; j++)
{
input = leopard.nextInt();
//Check if end
if(input != -999)
{
num[i][j] = input;
actualSize++;
}
}
}
System.out.println();
return actualSize;
}
public static void findRepeats(int [][] num, int size)
{
int findNum;
int total = 0, row = 0, col = 0;
for(int x = 0; x < size; x++)
{
//Set to number
findNum = num[row][col];
//Loop through whole array to find repeats
for(int i = 0; i < num.length; i++)
{
for(int j = 0; j < num[i].length; j++)
{
if(num[i][j] == findNum)
total++;
}
}
//Cycle array to set next number
if(col < num[0].length-1)
col++;
else
{
row++; //Go to next row if no more columns
col = 0; //Reset column number
}
//Display total repeats
System.out.println("Number " + findNum + " appears " + total + " times.");
total = 0;
}
}
}
I know why it is doing it, but I cannot figure out how to check if the number has already been checked for it to skip that number and go to the next number. I cannot use any classes or code that is not used in the code.
Since you cannot use anything other than this, lets say, basic elements of Java consider this:
Make another temporary 2D array with two columns (or just two separate arrays, personally I prefer this one). On the start of the algorithm the new arrays are empty.
When you take a number (any number) from the source 2D structure, first check if it is present in the first temporary array. If it is, just increment the value (count) in the second temporary array for one (+1). If it is not present in the first tmp array, add it to it and increase the count (+1) in the second at the same index as the newly added number in the first (which should be the last item of the array, basically).
This way you are building pairs of numbers in two arrays. The first array holds all your distinct values found in the 2D array, and the second one the number of appearances of the respective number from the first.
At the and of the algorithm just iterate the both arrays in parallel and you should have your school task finished. I could (and anyone) code this out but we are not really doing you a favor since this is a very typical school assignment.
It's counting the number two times, first time it appears in the code and second time when it appears in the code.
To avoid that keep a system to check if you have already checked for that number. I see you use check int array but you haven't used it anywhere in the code.
Do this,
Put the number in the check list if you have already found the count of it.
int count = 0;
check[count] = findNum;
count++;
Note: You can prefill you array with negative numbers at first in order to avoid for having numbers that user already gave you in input.
Next time in your for loop skip checking that number which you have already found a count for
for(int x = 0; x < size; x++) {
findNum = num[row][col];
if(check.containsNumber(findNUm)) { //sorry there is no such thing as contains for array, write another function here which checks if a number exists in the array
//skip the your code till the end of the first for loop, or in other words then don't run the code inside the for loop at all.
}
}
Frankly speaking I think you have just started to learn coding. Good luck! with that but this code can be improved a lot better. A piece of advice never create a situation where you have to use 3 nested for loops.
I hope that you understood my solution and you know how to do it.
All answers gives you some insight about the problem. I try to stick to your code, and add a little trick of swap. With this code you don't need to check if the number is already outputted or not. I appreciate your comments, structured approach of coding, and ask a question as clear as possible.
public static void findRepeats(int [][] num, int size)
{
int findNum;
int total = 1, row = 0, col = 0;
int [] check = new int[size];
while(row < num.length && col < num[0].length)
{
//Set to number
findNum = num[row][col];
//Cycle array to set next number
if(col < num[0].length-1)
col++;
else
{
row++; //Go to next row if no more columns
col = 0; //Reset column number
}
//Loop through whole array to find repeats
for(int i = row; i < num.length; i++)
{
for(int j = col; j < num[i].length; j++)
{
if(num[i][j] == findNum) {
total++;
//Cycle array to set next number
if(col < num[0].length-1)
col++;
else
{
row++; //Go to next row if no more columns
col = 0; //Reset column number
}
if(row < num.length - 1 && col < num[0].length -1)
num[i][j] = num[row][col];
}
}
}
//Display total repeats
System.out.println("Number " + findNum + " appears " + total + " times.");
total = 1;
}
}
you can use a HashMap to store the result. It Goes like this:
// Create a hash map
HashMap arrayRepeat = new HashMap();
// Put elements to the map
arrayRepeat.put(Number, Repeated);
I'm brand new to Java and my first assignment was to implement a "for" loop. I wrote this program in C++ and it compiles in Java, but I got an error at runtime. Can anyone tell me what's wrong?
import java.util.Scanner;
import java.util.Vector;
public class GlobalMembersMain
{
public static Vector<Integer> get_prime_factors(int number)
{
Vector<Integer> primefactors = new Vector<Integer>();
for (int j = 2; j <= number; j++)
{
if (number % j == 0)
{
primefactors.add(j);
number = number / j;
j = 1;
}
}
return primefactors;
}
public static void main(String[] args)
{
int number;
int count = 1;
System.out.print("Enter integer to analyse:");
System.out.print("\n");
Scanner scan = new Scanner(System.in);
number = scan.nextInt();
Vector<Integer> primefactors = new Vector<Integer>();
primefactors = get_prime_factors(number);
System.out.print("Prime factors are ");
for (int a = 0; a < primefactors.size() + 1; a++)
{
if (primefactors.elementAt(a) == primefactors.elementAt(a+1))
{
count++;
}
else
{
System.out.print(primefactors.elementAt(a));
System.out.print(" (");
System.out.print(count);
System.out.print(") ");
count = 1;
}
}
System.out.print("\n");
}
}
The output:
Enter integer to analyse:
10
Prime factors are 2 (1) Exception in thread "main" java.lang.ArrayIndexOutOfBoun
dsException: 2 >= 2
at java.util.Vector.elementAt(Unknown Source)
at GlobalMembersMain.main(GlobalMembersMain.java:36)
for (int a = 0; a < primefactors.size() + 1; a++)
{
if (primefactors.elementAt(a) == primefactors.elementAt(a+1))
{
count++;
}
Is exceeding the size of the primefactors collection. By 2, in fact.
Change to primefactors.size() - 1 to avoid this error.
Arrays are zero based, which I imagine you are aware of. What you may not be aware of is that in Java a List is backed by an array as well. When you invoke primefactors.size() +1 you are getting one more than you would possibly want. For instance is pf is of size 1 your loop will do the following:
pf.get(0); //returns the only value in the list
pf.get(1); // element doesn't exist
Now the other thing is you do not want to use Vector, generally speaking in Java. It is a synchronized collection. What you want is List/ArrayList.
OTHER CODE ISSUES
public static Vector<Integer> get_prime_factors(int number)
this does not need to be static. Also naming convention is camel case in Java so your function name should be getPrimeFactors(int number)
GlobalMembersMain
Should most likely be named GlobalMember as classes are to be singular in nature and I believe you added Main to indicate it was the class that holds the main function.
In your main function you would do this:
GlobalMember member = new GlobalMember();
member.getPrimeFactors(number);
This is where the problem is:
for (int a = 0; a < primefactors.size() + 1; a++)
{
if (primefactors.elementAt(a) == primefactors.elementAt(a+1))
{
count++;
}
//...
primefactors.elementAt(a+1) for the last element in your collection will throw the exception (AIOB).
Remember that arrays, lists and vectors in Java are zero-based. In your case, the primefactors vector will consist of two elements, available at index 0 and 1 respectively.
The problem you are facing is that you try to access the element primefactors.elementAt(2) which does not exist.
One problem is the break condition in the loop:
for (int a = 0; a < primefactors.size() + 1; a++) {
// ...
}
The first time, a will be 0, the second time 1 which are both fine. However, the loop will not break the third time, because a will equal 2, which is less than primefactors.size() + 1. Consequently, there will be a call to primefactors.elementAt(2) which does not exist and the program will blow up.
There is also a second problem inside the loop since you increment the loop variable by one during the comparison:
if (primefactors.elementAt(a) == primefactors.elementAt(a+1)) {
// ...
}
Yet again, your program will fail if you pass 2 as an argument to primefactors.elementAt(...)