// Line in Main Code
public class Assignment7 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input;
char userChoice;
int newVal, index;
IntegerList intList = null;
printMenu();
do {
System.out.print("Please enter a command or type? ");
input = scan.nextLine();
if (input.length() != 0)
userChoice = input.charAt(0);
else
userChoice = ' ';
switch (userChoice) {
case 'a':
System.out.print("How big should the list be? ");
intList = new IntegerList(scan.nextInt());
scan.nextLine();
System.out.print("What is range of the values for each random draw? ");
intList.randomize(scan.nextInt());
scan.nextLine();
break;
case 'b':
System.out.println(intList.toStrng());
break;
The above code is part of my main code, where I get user input and as them to set the boundary conditions of the array. case 'b' asks to print out the array by calling the function in the class which should return the array as a string with 10 elements per line.
// line in class
import java.util.Arrays;
import java.util.Random;
public class IntegerList {
private int arrSize;
public IntegerList(int size) {
size = arrSize;
}
private int[] IntArray = new int[arrSize];
public void randomize (int num) {
for(int i = 0;i<IntArray.length;i++) {
IntArray[i] =(int) (Math.random()*(num+1));
}
}
public void addElement(int newVal, int index) {
for(int i = index;i<IntArray.length;i++) {
int temp = IntArray[i];
IntArray[i]=newVal;
IntArray[i+1]=temp;
if(i == IntArray.length){
increaseSize(IntArray);
}
}
}
private static void increaseSize(int[] x) {
int[] temp = new int[2*x.length];
for(int i = 0; i<x.length;i++) {
temp[i]=x[i];
}
x = temp;
}
public void removeFirst(int nextInt) {
// TODO Auto-generated method stub
}
public String range() {
// TODO Auto-generated method stub
return null;
}
public String toStrng() {
String arrayOut = " ";
for(int i = 0; i<IntArray.length; i++ ) {
if(i%10 == 0 ) {
arrayOut+="\n";
}
arrayOut += IntArray[i] + " " ;
}
return arrayOut;
}
}
I'm trying to convert the array into a string and then return int and have it display 10 elements per line. I'm pretty sure I have the logic right, however, when I run the code, it does not display the array at all. How should I go about fixing this?
Look at how you are creating your array of integers through your current constructor...
public IntegerList(int size) {
size = arrSize;
}
private int[] IntArray = new int[arrSize];
When you call
intList = new IntegerList(scan.nextInt());
in your menu program, your array list won't magically know it needs to be re-initialized. It will be 0 since the value of arrSize is always 0 when you create your IntegerList object. Furthermore you have the assignment of the variables switched. Change your constructor to the following
private int[] IntArray = null;
public IntegerList(int size) {
arrSize = size;
IntArray = new int[arrSize];
}
Everything seems to work because the size of your array was always 0 and your methods just return.
You did not initialize your arrSize
You can modify your constructor to initialize arrSize
public IntegerList(int size) {
arrSize = size;
}
Also, in you toStrng method, you can just make use of arrSize instead of IntArray.length
Related
package dspermutation;
import java.util.Scanner;
public class DSPermutation {
String s;
char[] c;
int n;
public static void main(String[] args) {
DSPermutation ds=new DSPermutation();
ds.input();
}
private void input() {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string");
s=sc.next();
c=s.toCharArray();
n=c.length;
permutation(c,n-1,0);
}
private void permutation(char[] cc,int nn,int ii) {
if(ii==nn)
{
System.out.println(cc);
}
else
{
for(int j=ii;j<=nn;j++)
{
swap(cc[ii],cc[j]);
permutation(cc,nn,ii+1);
swap(cc[ii],cc[j]);
}
}
}
private void swap(char p, char c0) {
int x=s.indexOf(p);
int y=s.indexOf(c0);
/*1*/ char temp=c[x];
/*2*/c[x]=c[y];
/*3*/c[y]=temp;
/*c[x]=c0;
c[y]=p;*/
}
}
The above program is for printing all permutations of a given string.The result is coming true but in swap() method if i replace line 1,2,3(written in comment) by logic written in comment(after line 1,2,3) then answer comes wrong. Why could this be happening?
Your mistake is assuming c[x] == p and c[y] == c0. But the indexes x and y are derived from the immutable string s, which doesn't reflect the values in c in its shuffled state.
You are swapping values of character array using immutable string's position (i.e String always holds the same initial values). To make your commented code work you have to add this s = String.valueOf(c);at the end of swap function.
private void swap(char p, char c0) {
int x = s.indexOf(p);
int y = s.indexOf(c0);
// char temp = c[x];
// c[x] = c[y];
// c[y] = temp;
c[y] = p;
c[x] = c0;
s = String.valueOf(c);
}
I am working on a problem for 5 hours, and I searched in a book and on the Internet, but I still cannot solve this problem, so please help me to check what's wrong with the program. And the pic is the requirement for this program.
//imports
import java.util.Scanner;
import java.util.Random;
public class Lab09 // Class Defintion
{
public static void main(String[] arugs)// Begin Main Method
{
// Local variables
final int SIZE = 20; // Size of the array
int integers[] = new int[SIZE]; // Reserve memory locations to store
// integers
int RanNum;
Random generator = new Random();
final char FLAG = 'N';
char prompt;
prompt = 'Y';
Scanner scan = new Scanner(System.in);
// while (prompt != FLAG);
// {
// Get letters from User
for (int index = 0; index < SIZE; index++) // For loop to store letters
{
System.out.print("Please enter the number #" + (index + 1) + ": ");
integers[index] = RanNum(1, 10);
}
// call the printStars method to print out the stars
// printArray(int intergers, SIZE);
} // End Main method
/***** Method 1 Section ******/
public static int RanNum(int index, int SIZE);
{
RanNum = generator.nextInt(10) + 1;
return RanNum;
} // End RanNum
/***** Method 2 Section ******/
public static void printArray(int integers, int SIZE) {
// Print the result
for (int index = SIZE - 1; index >= 0; index--) {
System.out.print(integers[index] + " ");
}
} // End print integers
} // End Lab09
As Tim Biegeleisen and Kayaman said, you should put everything in the question and not just an external image.
You have a lot of errors in your code. Below the code will compile and run but I recommend you to take a look and understand what it has been done.
Errors:
If you are declaring a method, make sure you use { at the end of the declaration. You have:
public static int RanNum(int index, int SIZE);
Should be:
public static int RanNum(int index, int SIZE){
// Code here
}
You also should declare outside your main method so they can be accessed across the program.
If you are passing arrays as arguments, in your method the parameter should be an array type too.
You have:
public static void printArray(int integers, int SIZE) {
// Code her
}
Should be
public static void printArray(int[] integers, int SIZE) {
// Code her
}
Here is the complete code:
package test;
import java.util.Random;
import he java.util.Scanner;
public class Test {
//Local variables
public static final int SIZE = 20; //Size of the array
static int integers[] = new int[SIZE]; //Reserve memory locations to store integers
static int randomNumber;
static Random generator = new Random();
static String prompt;
static final String p = "yes";
static boolean repeat = true;
static Scanner input = new Scanner(System.in);
Test() {
}
/***** Method 1 Section ******/
public static int RanNum (int low, int high) {
randomNumber = generator.nextInt(high-low) + low;
return randomNumber;
} //End RanNum
/***** Method 2 Section ******/
public static void printArray(int[] intArray, int SIZE) {
//Print the result
for (int i = 0; i < SIZE; i++) {
System.out.print (intArray[i] + " ");
}
} //End print integers
public static void main (String [] arugs) {
do {
for (int i = 0; i < SIZE; i++) {
integers[i] = RanNum(1, 10);
}
printArray(integers, SIZE);
System.out.println("Do you want to generate another set of random numbers? Yes/No");
prompt = input.nextLine();
} while(prompt.equals(p));
}
}
I want to run a method that returns an array. Code such as this:
public static int[] getArray() {
int square[] = new int[5];
int input = 0;
System.out.println("Input a valid integer from 1-49");
System.out.println("for array input please \\(^-^)/");
System.out.println("Remember (^_'), don't repeat numbers");
Scanner reader = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.println(
"Please input the integer for position " + (i + 1) + " of the array");
input = reader.nextInt();
square[i] = input;
}
return square;
}
I have researched that you can make a variable like so int[] data = getArray();
How would I make it so that data can be accessible to other methods in the same class so I could do something like
public static int linearSearch(data) {
}
without having to constantly be re-entering the values for the array?
You can try out to introduce private variable of int[] and provide a lazy initialization for it, something like this:
class aClass {
int[] data; // default to the null
private int[] getArray() {
if (data == null) {
// your console logic for initialization
}
return data;
}
public static int linearSearch() {
int[] localData = getArray();
}
}
But in this case you can change the contents of data field in your methods across the class.
This can be done two ways:
- Either declaring the variable as class-level variable
- Or declaring it as local variable inside main method
public class ReturnIntArraysSO {
/**
* #param args
*/
public static void main(String[] args) {
int[] data = getArray();
for(int i : data){
System.out.print(i+" ");
}
linearSearch(data);
}
/**
*
* #return
*/
public static int[] getArray() {
int square[] = new int[5];
int input = 0;
System.out.println("Input a valid integer from 1-49");
System.out.println("for array input please \\(^-^)/");
System.out.println("Remember (^_'), don't repeat numbers");
Scanner reader = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.println("Please input the integer for position "
+ (i + 1) + " of the array");
input = reader.nextInt();
square[i] = input;
}
return square;
}
/**
*
* #param data
* #return
*/
public static void linearSearch(int[] data) {
for(int a : data){
if(a == 5){
System.out.println("\nFound 5!!");
}
}
}
}
You need to declare i your array like this:
public YourClass {
public static int[] square = new int[5];
}
This way you can access this array from any other class and it will remain with the exact array (that's what static for). Example:
From Class1 - YourClass.square
From Class2 - YourClass.square
Both are the same array instance
The code is close to correct, but I cannot see how I can move from System.out.println to a toString() method here, what am I missing?
import java.util.Scanner;
class Histogram
{
private int[] numCount;
int size=0;
public Histogram(String line)
{
setList(line);
}
public void setList(String line)
{
numCount = new int[20];
for(int i=0;i<10;i++)
numCount[i]=0;
Scanner chopper = new Scanner (line);
while (chopper.hasNextInt())
{
int num = chopper.nextInt();
numCount[num]++;
}
for(int i=0;i<10;i++)
System.out.println(i+"::"+numCount[i]);
System.out.println();
System.out.println();
}
}
First, in setList() the default value of the primitive int is 0. And if you're using decimal math you only need 10 digits. And remove the println(s);
public void setList(String line) {
numCount = new int[10]; // <-- base 10
Scanner chopper = new Scanner(line);
while (chopper.hasNextInt()) {
int num = chopper.nextInt();
numCount[num]++;
}
// once the loop is done, you can do
System.out.println(this); // <-- will call toString so
}
Next override toString(). You might use Arrays.toString(int[]) which Returns a string representation of the contents of the specified array like
#Override
public String toString() {
return Arrays.toString(numCount);
}
Finally, I personally would have preferred an implementation of setList(String) like
private int[] numCount = new int[10]; // <-- base 10
public void setList(String line) {
for (char ch : line.toCharArray()) {
numCount[Character.digit(ch, 10)]++;
}
}
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;
}
}