Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
It keeps throwing the exception array index out of bounds for the multiply method, but dimensions are correct. The error appears at this line:
mm[r][c]+=multiplier[i][j]*multiplicand[j][i];
and at this line:
k.multiply_matrix(temp1,temp2,i1,h,i2);
I want to know why the exception is thrown and possible modification for my code to run correctly.
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class matrixmultiplication
{
public static void main(String args[])
{
matrixmultiplication k=new matrixmultiplication();
System.out.println("enter how many rows and how many columns");
Scanner c=new Scanner(System.in);
String f=c.next();
String[] x=f.split(",");
int i1=Integer.parseInt(x[0]);
int i2=Integer.parseInt(x[1]);
int[][] temp1=k.enter_thematrix(i1,i2);
System.out.println("how many columns in the second matrix");
int h=c.nextInt();
int[][] temp2=k.enter_thematrix(i2,h);
k.multiply_matrix(temp1,temp2,i1,h,i2);
}
public int[][] enter_thematrix(int d1,int d2)
{
Scanner c1=new Scanner(System.in);
int the_matrix[][]=new int[d1][d2];
for (int col=0;col<d2;col++)
{
for(int row=0;row<d1;row++)
{
the_matrix[row][col]=c1.nextInt();
}
}
return the_matrix;
}
public void print_matrix(int [][]mm,int a,int s)
{
for (int col=0;col<s;col++)
{
for(int row=0;row<a;row++)
{
System.out.print(mm[a][s]+"\t");
}
System.out.println();
}
}
public void multiply_matrix(int [][]multiplier,int [][]multiplicand,int r,int c,int innerd)
{
int [][]mm=new int[r][c];
for(int c1=0;c1<c;c1++)
{
for(int r1=0;r1<r;r1++)
{
for(int i=0;i<innerd;i++)
{
for(int j=0;j<innerd;j++)
{
mm[r][c]+=multiplier[i][j]*multiplicand[j][i];
}
}
}
}
print_matrix(mm,r,c);
}
}
The problem is that you pass i1 and i2 to the method, multiply_matrix. However i1 and i2 are the amount of rows and columns. Arrays start at zero. So if you have a 2d array with two rows and two columns it will have a max index of 1. (0 and 1 are the two positions in the array) So when you call the line:
mm[r][c]+=multiplier[i][j]*multiplicand[j][i];
You will always have an indexoutofboundsexception because (in this example of a 2 by 2 array) you will be calling the index (2,2) which does not exist. You need to pass that arguments i1-1 and i2-1 to the method.
Also a side note I would not have the user enter the rows and columns on the same line and then split it. This is error prone. If a user enters a number, comma, space, and then another number, this will cause an error. Or if the user doesn't type a comma this will also cause an error. It would be better to call nextInt on two separate lines. Like this:
System.out.println("enter how many rows: ");
Scanner c=new Scanner(System.in);
int i1 = c.nextInt();
System.out.println("Enter how many columns: ");
int i2 = c.nextInt();
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to print out a sequence of numbers using this formula
Enter a number
if number is even divide number by 2.
But if number is odd multiply number by 3 and add 1
continue doing this until number becomes 1
sample input=3
Sample output=10 5 16 8 4 2
this is what I tried but still not getting it
package victor;
import java.util.Scanner;
public class proj {
public static void main(String[] args) {
Scanner put=new Scanner(System.in);
int temp=0;
boolean notOne=true;
System.out.println("input::: ");
int num=put.nextInt();
while(temp!=1){
if (num%2==0){
temp=num;
System.out.println(temp/2);
break ;
}
else {
temp=num;
System.out.println(temp*3+1);
break;
}
}
if(temp!=1){
notOne=false;
}
}
}
It's not working because you keep re-assigining the variable temp to the initially scanned num.
You keep checking if the initially scanned num is odd or even, when you should check if temp is odd or even.
You also break out of the loop for no reason.
And finally, you're not saving the result of the operations, you're only printing out the result.
Try to understand the points I mentioned above by noticing the differences between your code and the following:
while(temp!=1){
if (temp%2==0){
temp = temp/2;
}
else {
temp = temp*3+1;
}
System.out.println(temp);
}
You are not updating the value of temp. You are just printing it. Take the following statement
if (num%2==0){
temp=num;
System.out.println(temp/2);
break ;
}
Here you are setting temp to num and just printing temp/2 and never setting a value.
I wrote my version of it which is a bit more simpler. I hope this will help you. You can create a string to get a better output of course.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number:");
int number = scan.nextInt();
while (number != 1) {
number = number % 2 == 0 ? number / 2 : ((number * 3) + 1);
System.out.println("Number became " + number);
}
}
}
Try this:
public class Main
{
public static void main(String[] args) throws Exception
{
System.out.println("Starting...");
//Lets start the program, first we need
//the Scanner class to access to the input
Scanner stdin = new Scanner(System.in);
System.out.print("Type a num: ");
//I dont use: nextInt() because when asking for another input, will scan only
//the rest of the line (Maybe just \n - line break )
int num = Integer.parseInt(stdin.nextLine());
//Optional
int loops = 0;
while(num!=1){
//Pair, so num/2
if ( num %2 == 0){
num/=2;
}
else{
//num*3 +1
num=num*3 +1;
//Note that:
//1 + num*3
//Doesnt alter the result
}
System.out.println("num: "+num);
loops++;
}
System.out.println("total loops: "+loops);
}
}
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);
}
the question I've asked isn't too clear but essentially I have been tasked to:
Write a program to read in 5 integer numbers from the user. You
should store the numbers in an array.
Use loops for efficiency.
I would know how to do this if it weren't for loops, however I am unsure how to use loops for this certain task.
What I have is this (I know this is completely wrong I was just trying to base it on the example from the book).
import java.util.Arrays;
import java.util.Scanner;
public class fivenumbersloops {
public static void main(String[] args)throws Exception {
Scanner aids = new Scanner(System.in);
int[] numbers = new int[5];
do
{
System.out.println("Enter a whole number: ");
numbers[0] = aids.nextInt();
numbers[0]++;
}while (numbers[0]==numbers[5]);
}
}
I know it's the bottom bit which is completely wrong, but if someone could help point me in the right direction I would appreciate it.
What you want is a for loop. This for loop initializes the variable i to 0, continues while i is less than 5 and increments i for each iteration. The variable i is used to specify the position to place the input number into the array.
public static void main(String[] args) throws Exception {
Scanner aids = new Scanner(System.in);
int[] numbers = new int[5];
for (int i = 0; i < 5; i++) {
System.out.println("Enter a whole number: ");
numbers[i] = aids.nextInt();
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
public class decisionMaker {
public static void main(String args[]) {
String option[] = new String[10];
// Output
for (int i = 0; i <= 9; i++) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the next option:");
option[i] = input.next();
System.out.println(" ");
}
for (int i = 0; i <= 9; i++) {
System.out.println("option: ");
System.out.println("option[i]+" ");
}
// Output
}
I'm trying to figure out how to add a count to the options, exit and end the program after entering a certain letter or number, and how to create a random output from the user input. I want it to give me one option that I had input at random. Can anyone help me with one or a few of these things. I'm trying to learn to code on my own, and I'm stuck on these.
Randomness
You can generate random numbers using java.util.Random;:
import java.util.Random;
public class SomeClass{
static Random rand = new Random();
public static void main(String args[]){
System.out.println(rand.nextInt());
}
}
About some broken code:
If you want to print out the value of a variable with System.out.println() then you need only type the variable without any quotation marks. The code you've written below will not compile:
System.out.println("option: ");
System.out.println("option[i]+" ");
Assuming that's what you want to do, it should instead be written as:
System.out.println("option: ");
System.out.println(option[i]);
Or even System.out.println("option: \n"+option[i]);
(The escape sequence \n when placed inside of quotation marks just indicates to the console to add a new line.)
Scanner:
Additionally, as nick zoum pointed out, your Scanner object should be initialized outside of the for loop, such as right underneath of the main() method.
Please comment below if you need clarification or if I misunderstood what you were looking for. It was very hard to understand your question.
You could try something like this:
public class DecisionMaker {
public static void main(String[] args) {
// output
Scanner scanner = new Scanner(System.in);
int size = getInt(scanner);
String option[] = new String[size];
for (int index = 0; index < size; index++) {
System.out.print("Enter the next option:");
option[index] = scanner.next();
}
int index = (int) (Math.random() * size);
System.out.println(option[index]);
scanner.close();
// output
}
public static int getInt(Scanner scanner) {
int size = 0;
while (size <= 0) {
if (scanner.hasNext()) {
if (scanner.hasNextInt()) {
size = scanner.nextInt();
}
}
if (size <= 0) {
System.out.println("The input: " + scanner.next() + " is not a valid value.");
}
}
return size;
}
}
How the program works:
The Scanner is initialized in the beginning and there is only
one instance of it.
Then the program will wait until the user inserts a valid number for
the size of options.
The next 5 lines were essentially copied from your code.
Finally we get a random Integer in the range of 0 - (size - 1) and print
the String of the array with that index.
Question: Write a method that takes as input a variable number of integers. The method should return the average of the integers as a double. Write a full program to test the method.
That code below creates an array of 10 integers and finds their average. However, I need it to create a variable number of arguments (int...a) where any number of integers entered can be averaged. Can someone help me.Thanks.
My code:
package average.pkgint;
import java.util.Scanner;
public class AverageInt {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int [] number = new int [10];
Scanner b = new Scanner(System.in);
System.out.println("Enter your 10 numbers:");
for (int i = 0; i < number.length; i++) {
number[i] = b.nextInt() ;
}
System.out.println("The average is:"+Avnt(number));
}
public static int Avnt(int [] a){//declare arrays of ints
int result = 1;
int sum = 0;
//iterate through array
for (int num : a) {
sum += num;
}
double average = ( sum / a.length);//calculate average of elements in array
result = (int)average;
return result;
}
}
This is a way of getting as many variables as you want to a method and going through them all:
public static void testVarArgs(int... numbers){
for(double u: numbers) {
System.out.println(u);
}
}
If you don't want to read the number of integers as the first input you can declare a stack in stead of an array
Stack<Integer> numbers=new Stack<>()
and then you can add the numbers with the add method.
Just change your method declaration to a variable length parameter:
public static int Avnt(int ... a){//declare variable int arguments
When you use a variable length parameter, you supply the values in the method invocation. For example,
System.out.println(Avnt(1,2,3));
System.out.println(Avnt(1,2,3,4,5,6,9,9,9,10,10));
Actually, this looks like it meets your requirements. Just add method calls in your main() similar to these.