How do I get user input into two separate arrays? - java

Hi I am having trouble with Scanner to get user input two separate ArrayList. When I run this code I get an IndexOutOfBounds exception after entering the two arrays.
The code adds two binary numbers together using logic of a ripple adder. An example of intended user input would be
Enter A array: 1 0 1 0
Enter B Array: 0 0 0 1
producing: 1 0 1 1
The code works when arrays are hard coded, how can I get the user to enter the arrays?
Code is shown below
import java.util.*;
public class AdderApp {
public static void main(String[] args) {
Scanner inputA = new Scanner(System.in);
ArrayList<Integer> aList = new ArrayList<Integer>();
ArrayList<Integer> bList = new ArrayList<Integer>();
int c = 0;
System.out.println("Enter A array");
aList.add(inputA.nextInt());
Scanner inputB = new Scanner(System.in);
System.out.println("Enter B array");
bList.add(inputB.nextInt());
Adder bit1 = new Adder(parseInput(aList.get(3)), parseInput(bList.get(3)), parseInput(c));
Adder bit2 = new Adder(parseInput(aList.get(2)), parseInput(bList.get(2)), bit1.getCout());
Adder bit3 = new Adder(parseInput(aList.get(1)), parseInput(bList.get(1)), bit2.getCout());
Adder bit4 = new Adder(parseInput(aList.get(0)), parseInput(bList.get(0)), bit3.getCout());
if (bit4.getCout() == false) {
System.out.println(bit4.toString() + " " + bit3.toString() + " " + bit2.toString() + " " + bit1.toString());
} else {
System.out.println("overflow!");
}
}
public static boolean parseInput(int i) {
if (i == 1) {
return true;
} else {
return false;
}
}
}
Code for Adder class:
public class Adder {
private boolean a, b, cin, cout, s;
/**
* Full Adder contructor
*/
public Adder(boolean a, boolean b, boolean cin) {
this.a = a;
this.b = b;
this.cin = cin;
s = nand(nand(a, b), cin); //sum bit
cout = or(and(nand(a, b), cin), and(a, b)); // - carry bit
}
/** Half adder constructor */
// public Adder (bloolean a, boolean b) {
//
// this.a = a;
// this.b = b;
//
// s =
//}
/**
* NAND gate
*/
public boolean nand(boolean a, boolean b) {
return a ^ b;
}
/**
* AND gate
*/
public boolean and(boolean a, boolean b) {
return a && b;
}
/**
* OR gate
*/
public boolean or(boolean a, boolean b) {
return a || b;
}
public boolean getCout() {
return cout;
}
public String toString() {
if (s == true) {
return "1";
} else {
return "0";
}
}
public String toStringCout() {
if (cout == true) {
return "1";
} else {
return "0";
}
}
}

Your entire AdderApp class can be simplified and improved to accept any bit length by accepting the input in a slightly different way and then using a for loop to add each bit. The parseInput function can be replaced with a simple boolean comparison:
import java.util.*;
public class AdderApp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter A array");
char[] aIn = input.nextLine().replace(" ", "").toCharArray();
System.out.println("Enter B array");
char[] bIn = input.nextLine().replace(" ", "").toCharArray();
StringBuilder result = new StringBuilder();
Adder bit = new Adder(false, false, false);
for (int i = aIn.length - 1; i >= 0; --i) {
bit = new Adder((aIn[i] == '1'), (bIn[i] == '1'), bit.getCout());
result.append(bit + " ");
}
System.out.println(bit.getCout() ? "overflow!" : result.reverse());
}
}

Scanner.nextInt gets the next integer in the input, and then stops. Each of your lists only contains 1 element.
Use something along these lines instead:
String[] input = inputA.nextLine().split(" ");
for (String s : input)
{
try { aList.add(Integer.parseInt(s)); }
catch(NumberFormatException nfe) { /* handle exception as desired */ }
}
Alternatively, you should be able to use something like:
while (inputA.hasNextInt())
{
aList.add(inputA.nextInt());
}

You should be having a for loop to have an input into your ArrayList.
System.out.println("Enter A array");
for (int i = 0; i < 4; i++) {
aList.add(inputA.nextInt());
}
Scanner inputB = new Scanner(System.in);
System.out.println("Enter B array");
for (int i = 0; i < 4; i++) {
bList.add(inputB.nextInt());
}

The user should input 4 numbers, your one just allow the user to enter 1 number:
int count = 0;
Scanner inputA = new Scanner(System.in);
System.out.println("Enter A array");
while(count < 4){
count++;
aList.add(inputA.nextInt());
}
count = 0;
Scanner inputB = new Scanner(System.in);
System.out.println("Enter B array");
while(count < 4){
count++;
bList.add(inputB.nextInt());
}
If you want to use hasNextInt():
while(inputA.hasNextInt()){
count ++;
aList.add(inputA.nextInt());
if(count == 4){
count = 0;
break;
}
}

Related

When compiling program I get the error 'void' type not allowed here

I'm trying to create a program that asks for 10 integers and puts those numbers into an array of negative, positive, and odd arrays. In the end, I want the program to print out 3 rows of numbers that separate the users 10 numbers into "odd", "even", and negative". When I run this I get "error: 'void' type not allowed here"
import java.util.Scanner;
public class ArrayPractice{
private static void showArray(int[] nums)
{
for (int i=0; i<nums.length;i++)
{
if(nums[i]!=0)
{
System.out.println(nums[i] + " ");
}
}
}
public static void main(String[] args){
int evenArray[] = new int[10];
int evenCount = 0;
int oddArray[] = new int[10];
int oddCount = 0;
int negArray[] = new int[10];
int negCount = 0;
Scanner input = new Scanner(System.in);
for(int i = 0; i<10; i++)
{
System.out.println("Number? " + (i + 1));
int answer = input.nextInt();
if(answer<0)
{
negArray[negCount++] = answer;
}
else
{
if (answer % 2 == 0)
{
evenArray[evenCount++] = answer;
}
else
{
oddArray[oddCount++] = answer;
}
}
}
System.out.println(showArray(evenArray));
System.out.println(showArray(oddArray));
System.out.println(showArray(negArray));
}
}
showArray is void, it does not return anything. And, on inspection, it prints in the method itself. So this
System.out.println(showArray(evenArray));
System.out.println(showArray(oddArray));
System.out.println(showArray(negArray));
should just be
showArray(evenArray);
showArray(oddArray);
showArray(negArray);

Find the given number is armstrong Number or not if Number is armstrong print 0 and if not a armstron print 1

Trying Code as follows But it not working as per requirement printing 0 if armstrong number and 1 if not armstrong number
Suggest correction for implementing this program
import java.util.Scanner;
class Example {
public static boolean solution(int N) {
boolean isNumber = false;
#SuppressWarnings("unused")
int i=1;
int c=0,a,temp;
temp=N;
while(N>0) {
a=N%10;
N=N/10;
c=c+(a*a*a);
}
if(temp==c) {
i = isNumber ? 1 : 0;
}
System.out.println(isNumber);
return isNumber;
}
}
class Arm {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner s = new Scanner(System.in);
int N = s.nextInt();
#SuppressWarnings("unused")
Example ex= new Example();
Example.solution(N);
}
}
#Sanjyukta you have not assigned isNumber=true if the number is armstrong, so everytime it will return false and 0 and It will not update the value of i and isNumber.
Below code will update the isNumber and i values.
if (temp == c) {
isNumber = true;
i = isNumber ? 0 : 1;
}
System.out.println(isNumber + "\t" + i);
Answer of my question: It is possible by using Ternary operator
public static void solution(int N)
{
int c=0,a,temp;
temp=N;
while(N>0)
{
a=N%10;
N=N/10;
c=c+(a*a*a);
}
if(temp == c)
{
boolean b = true;
c = (b) ? 1 : 0;
}
else
{
boolean b = false;
c = (b) ? 1 : 0;
}
System.out.println(c);
}
class Arm
{
public static void main(String[] args)
{
#SuppressWarnings("resource")
Scanner s = new Scanner(System.in);
int N = s.nextInt();
#SuppressWarnings("unused")
Example ex= new Example();
ex.solution(N);
}
}

How to create dynamic array in java with unclear and diffrent inpu INDEXes?

I am new to Java and I needed dynamic Array ... all of thing I found that's for dynamic Array we should use "Array List' that's ok but when I want the indexes to be the power of X that given from input , I face ERORR ! .. the indexes are unclear and the are not specified what is the first or 2th power ! .... can anyone help me how solve it?
public static void main(String[] args) throws Exception {
Scanner Reader = new Scanner(System.in);
ArrayList<Float> Zarayeb = new ArrayList<Float>();
Float s ;
int m;
System.out.print("Add Count of equation Sentences : ");
int N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(0 , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Add Count of equation Sentences : ");
N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(m , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Enter X: ");
float X = Reader.nextFloat();
float Sum = 0;
for (int i = 0; i < Zarayeb.size();i++) {
Sum += (Zarayeb.get(i) * Math.pow(X,i));
}
System.out.println("\nThe final answer is : " + Sum);
First I refactored your code a bit to make sense of it:
Main class with the top level logic:
import java.util.Scanner;
public class Main {
private Scanner scanner;
private final Totals totals = new Totals();
public static void main(final String[] args) {
final Main app = new Main();
app.run();
}
private void run() {
scanner = new Scanner(System.in);
try {
readAndProcessEquationSentences();
} finally {
scanner.close();
}
}
private void readAndProcessEquationSentences() {
readSentences(true);
readSentences(false);
System.out.println("The final answer is : " + totals.calculateSum(readBaseInput()));
}
private void readSentences(final boolean useInitialLogic) {
System.out.print("Enter number of equation sentences:");
final int numberOfSentences = scanner.nextInt();
if (numberOfSentences == 0) {
throw new RuntimeException("No sentences");
}
for (int i = 0; i < numberOfSentences; i++) {
Sentence sentence = Sentence.read(scanner);
if (useInitialLogic) {
totals.addInitialSentence(sentence);
} else {
totals.addNextSentence(sentence);
}
if (i < numberOfSentences - 1) {
System.out.print("\r+");
}
}
}
private float readBaseInput() {
System.out.print("Enter base: ");
return scanner.nextFloat();
}
}
Sentence class which represents one equation sentence entered by the user:
import java.util.Scanner;
public class Sentence {
private Float x;
private int y;
public static Sentence read(final Scanner scanner) {
final Sentence sentence = new Sentence();
System.out.println("Enter x^y");
System.out.print("x=");
sentence.x = scanner.nextFloat();
System.out.println();
System.out.print("y=");
sentence.y = scanner.nextInt();
System.out.println();
return sentence;
}
public Float getX() {
return x;
}
public int getY() {
return y;
}
}
Totals class which keeps track of the totals:
import java.util.ArrayList;
import java.util.List;
public class Totals {
private final List<Float> values = new ArrayList<Float>();
public void addInitialSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
addToStart(sentence);
} else {
addToValue(sentence);
}
}
private void addToStart(final Sentence sentence) {
values.add(0, sentence.getX());
}
public void addNextSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
values.add(sentence.getY(), sentence.getX());
} else {
addToValue(sentence);
}
}
private void addToValue(final Sentence sentence) {
Float total = values.get(sentence.getY());
total = total + sentence.getX();
values.add(sentence.getY(), total);
}
public float calculateSum(final float base) {
float sum = 0;
for (int i = 0; i < values.size(); i++) {
sum += (values.get(i) * Math.pow(base, i));
}
return sum;
}
}
I don't have the foggiest idea what this is supposed to do. I named the variables according to this foggy idea.
You are letting the user input values in two separate loops, with a slightly different logic I called 'initial' and 'next'.
In the initial loop you were doing this:
if (Zarayeb.get(m) == null)
Zarayeb.add(0 , s);
In the next loop this:
if (Zarayeb.get(m) == null)
Zarayeb.add(m , s);
There are problems with this because the ArrayList.get(m) will throw an IndexOutOfBoundException if m is out or range. So I changed that to the equivalent of:
if (Zarayeb.size() <= m) {
....
}
However, in the 'next' case this still does not solve it. What should happen in the second loop when an 'm' value is entered for which no element yet exists in the ArrayList?
Why do you need to enter sentences in two loops?
What is the logic supposed to achieve exactly?

How to implement a Multi Class Application

This is the zoo manager coding:
public class ZooManager {
public void feedAnimals(Animals a, Food[] arrayFood) {
Food temp = null;
for (int i = 0; i < arrayFood.length; i++) {
if (arrayFood[i].getFoodName().equals(a.getTypeOfFood())) {
arrayFood[i].setAmount(arrayFood[i].getAmount() - 1);
System.out.print("Animal is fed.");
}
}
System.out.print(temp);
}
public void isFoodEmpty(Food[] arrayFood) {
for (int i = 0; i < arrayFood.length; i++) {
if (arrayFood[i] == null) {
System.out.print("True");
} else {
System.out.print("False");
}
}
}
}
This is the code for the main application:
import java.util.Scanner;
public class ZooApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Animals[] a = new Animals[4];
for (int i = 0; i < 4; i++) {
System.out.print("Enter the animal name: ");
String an = in.nextLine();
System.out.print("What type of food do they eat: ");
String tof = in.nextLine();
a[i] = new Animals(an, tof);
}
Food[] b = new Food[3];
for (int i = 0; i < 3; i++) {
System.out.print("Enter the type of food: ");
String f = in.nextLine();
System.out.print("Enter the amount: ");
int am = in.nextInt();in.nextInt();
b[i] = new Food(f, am);
}
ZooManager z= new ZooManager();
System.out.print(z.feedAnimals(a[i], b));
System.out.print(z.isFoodEmpty(b[i]));
}
}
I have an error at the two final out prints on the main application. The first one is that "the void type is not allowed there." and "variable i can not be found." The second out put says that "isFoodEmpty cannot be given to the type: Food, required: Food[]." Thank you for any advice or help.
Your isFoodEmpty function is a void, so the first error is telling you that you can't print it because it doesn't return anything. Second, you are passing an individual instance of Food into a function that is looking for an array. That's the second error. Also note that variable i is only defined within the scope of the for loop, so you can't go using it outside of the loop.
Edit:
Currently your isFoodEmpty is a void. you have one of two options:
public void isFoodEmpty(Food[] arrayFood) {
for (int i = 0; i < arrayFood.length; i++) {
if (arrayFood[i] == null) {
System.out.print("True");
} else {
System.out.print("False");
}
}
}
}
[...]
isFoodEmpty(b); // it already prints within the function
or
public boolean isFoodEmpty(Food[] arrayFood) {
for (int i = 0; i < arrayFood.length; i++) {
if (arrayFood[i] == null) {
return true;
} else {
return false;
}
}
}
}
[...]
System.out.println(isFoodEmpty(b)); // print the boolean that it returns
Either way, you might want to check the logic on that function, since it will return empty if even one of the elements in the array is null. (You could have 20 food items, then one null value, and it would return true).

Uva's 3n+1 problem

I'm solving Uva's 3n+1 problem and I don't get why the judge is rejecting my answer. The time limit hasn't been exceeded and the all test cases I've tried have run correctly so far.
import java.io.*;
public class NewClass{
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
int maxCounter= 0;
int input;
int lowerBound;
int upperBound;
int counter;
int numberOfCycles;
int maxCycles= 0;
int lowerInt;
BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in));
String line = consoleInput.readLine();
String [] splitted = line.split(" ");
lowerBound = Integer.parseInt(splitted[0]);
upperBound = Integer.parseInt(splitted[1]);
int [] recentlyused = new int[1000001];
if (lowerBound > upperBound )
{
int h = upperBound;
upperBound = lowerBound;
lowerBound = h;
}
lowerInt = lowerBound;
while (lowerBound <= upperBound)
{
counter = lowerBound;
numberOfCycles = 0;
if (recentlyused[counter] == 0)
{
while ( counter != 1 )
{
if (recentlyused[counter] != 0)
{
numberOfCycles = recentlyused[counter] + numberOfCycles;
counter = 1;
}
else
{
if (counter % 2 == 0)
{
counter = counter /2;
}
else
{
counter = 3*counter + 1;
}
numberOfCycles++;
}
}
}
else
{
numberOfCycles = recentlyused[counter] + numberOfCycles;
counter = 1;
}
recentlyused[lowerBound] = numberOfCycles;
if (numberOfCycles > maxCycles)
{
maxCycles = numberOfCycles;
}
lowerBound++;
}
System.out.println(lowerInt +" "+ upperBound+ " "+ (maxCycles+1));
}
}
Are you making sure to accept the entire input? It looks like your program terminates after reading only one line, and then processing one line. You need to be able to accept the entire sample input at once.
I faced the same problem. The following changes worked for me:
Changed the class name to Main.
Removed the public modifier from the class name.
The following code gave a compilation error:
public class Optimal_Parking_11364 {
public static void main(String[] args) {
...
}
}
Whereas after the changes, the following code was accepted:
class Main {
public static void main(String[] args) {
...
}
}
This was a very very simple program. Hopefully, the same trick will also work for more complex programs.
If I understand correctly you are using a memoizing approach. You create a table where you store full results for all the elements you have already calculated so that you do not need to re-calculate results that you already know (calculated before).
The approach itself is not wrong, but there are a couple of things you must take into account. First, the input consists of a list of pairs, you are only processing the first pair. Then, you must take care of your memoizing table limits. You are assuming that all numbers you will hit fall in the range [1...1000001), but that is not true. For the input number 999999 (first odd number below the upper limit) the first operation will turn it into 3*n+1, which is way beyond the upper limit of the memoization table.
Some other things you may want to consider are halving the memoization table and only memorize odd numbers, since you can implement the divide by two operation almost free with bit operations (and checking for even-ness is also just one bit operation).
Did you make sure that the output was in the same order specified in the input. I see where you are swapping the input if the first input was higher than the second, but you also need to make sure that you don't alter the order it appears in the input when you print the results out.
ex.
Input
10 1
Output
10 1 20
If possible Please use this Java specification : to read input lines
http://online-judge.uva.es/problemset/data/p100.java.html
I think the most important thing in UVA judge is 1) Get the output Exactly same , No Extra Lines at the end or anywhere . 2) I am assuming , Never throw exception just return or break with No output for Outside boundary parameters.
3)Output is case sensitive 4)Output Parameters should Maintain Space as shown in problem
One possible solution based on above patterns is here
https://gist.github.com/4676999
/*
Problem URL: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=36
Home>Online Judge > submission Specifications
Sample code to read input is from : http://online-judge.uva.es/problemset/data/p100.java.html
Runtime : 1.068
*/
import java.io.*;
import java.util.*;
class Main
{
static String ReadLn (int maxLg) // utility function to read from stdin
{
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
public static void main (String args[]) // entry point from OS
{
Main myWork = new Main(); // create a dinamic instance
myWork.Begin(); // the true entry point
}
void Begin()
{
String input;
StringTokenizer idata;
int a, b,max;
while ((input = Main.ReadLn (255)) != null)
{
idata = new StringTokenizer (input);
a = Integer.parseInt (idata.nextToken());
b = Integer.parseInt (idata.nextToken());
if (a<b){
max=work(a,b);
}else{
max=work(b,a);
}
System.out.println (a + " " + b + " " +max);
}
}
int work( int a , int b){
int max=0;
for ( int i=a;i<=b;i++){
int temp=process(i);
if (temp>max) max=temp;
}
return max;
}
int process (long n){
int count=1;
while(n!=1){
count++;
if (n%2==1){
n=n*3+1;
}else{
n=n>>1;
}
}
return count;
}
}
Please consider that the integers i and j must appear in the output in the same order in which they appeared in the input, so for:
10 1
You should print
10 1 20
package pandarium.java.preparing2topcoder;/*
* Main.java
* java program model for www.programming-challenges.com
*/
import java.io.*;
import java.util.*;
class Main implements Runnable{
static String ReadLn(int maxLg){ // utility function to read from stdin,
// Provided by Programming-challenges, edit for style only
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
public static void main(String args[]) // entry point from OS
{
Main myWork = new Main(); // Construct the bootloader
myWork.run(); // execute
}
public void run() {
new myStuff().run();
}
}
class myStuff implements Runnable{
private String input;
private StringTokenizer idata;
private List<Integer> maxes;
public void run(){
String input;
StringTokenizer idata;
int a, b,max=Integer.MIN_VALUE;
while ((input = Main.ReadLn (255)) != null)
{
max=Integer.MIN_VALUE;
maxes=new ArrayList<Integer>();
idata = new StringTokenizer (input);
a = Integer.parseInt (idata.nextToken());
b = Integer.parseInt (idata.nextToken());
System.out.println(a + " " + b + " "+max);
}
}
private static int getCyclesCount(long counter){
int cyclesCount=0;
while (counter!=1)
{
if(counter%2==0)
counter=counter>>1;
else
counter=counter*3+1;
cyclesCount++;
}
cyclesCount++;
return cyclesCount;
}
// You can insert more classes here if you want.
}
This solution gets accepted within 0.5s. I had to remove the package modifier.
import java.util.*;
public class Main {
static Map<Integer, Integer> map = new HashMap<>();
private static int f(int N) {
if (N == 1) {
return 1;
}
if (map.containsKey(N)) {
return map.get(N);
}
if (N % 2 == 0) {
N >>= 1;
map.put(N, f(N));
return 1 + map.get(N);
} else {
N = 3*N + 1;
map.put(N, f(N) );
return 1 + map.get(N);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
while(scanner.hasNextLine()) {
int i = scanner.nextInt();
int j = scanner.nextInt();
int maxx = 0;
if (i <= j) {
for(int m = i; m <= j; m++) {
maxx = Math.max(Main.f(m), maxx);
}
} else {
for(int m = j; m <= i; m++) {
maxx = Math.max(Main.f(m), maxx);
}
}
System.out.println(i + " " + j + " " + maxx);
}
System.exit(0);
} catch (Exception e) {
}
}
}

Categories

Resources