Java 7: An array as input - java

Alright, so I'm supposed to work with this as the beginning of my code:
public static int addOdds(int[] input){}
That would return the sum.
I have the add odds part finished with pre loaded arrays.
That was simple enough, but what is flustering my person is how to get this to take an array as input from user.
I know of Scanner from java.utils, but I'm not sure how to get it to run with my code to make it take an array (if it can).
I considered using:
public string void main(String [] args){}
And call Scanner with it, and use Integer.parseint(), but I don't think that could parse an array.
Then call the input the array from scanner to be handed off to the addOdds method.
An example would be {2,3,7,8,4,1} would be what the code must take as input.
Thanks in advance, I'm a bit stumped.
If it helps, here is an example query; inputTwo isn't relevant to the question:
public class Proj2Tester {
public static void main(String[] args){
int[] inputOne = {4,8,9,12,7};
int[] inputTwo = {41,38,19,112,705};
System.out.println("Problem 1 is correct on test input = " + (16 == Problem1.addOdds(inputOne)));
System.out.println("Problem 2 is correct on test input = " + (686== Problem2.getRange(inputTwo)));
}
Following T.J.'s advice I tried the following:
public class Problem1 {
public static void main(String args[]){
System.out.println("Your array is: "+input);
}
}
public static int addOdds(int[] input){
int[] input = new int[args.length]; //Begin T.J.'s segment
int n = 0;
for (String arg : args) {
input[n++] = Integer.parseInt(arg);
int sum =0; //Initializing sum as 0;
for(int i =0; i < inputOne.length; i++){
if(inputOne[i] % 2 !=0){
;
sum = sum + inputOne[i];
break;
}
if(inputOne[i] % 2 == 0){
i++;
break;
}
}
return sum; // placeholder for my answer, not zero should be returned
}

At least two options:
Have the user specify the array entries as individual command line arguments, e.g.:
java YourClass 2 3 7 8 4 1
...and then parse the entries in args into an int array:
int[] input = new int[args.length];
int n = 0;
for (String arg : args) {
input[n++] = Integer.parseInt(arg);
}
Have the user specify the array as a single command-line argument with commas:
java YourClass "2,3,7,8,4,1"
...and then split args[0] on comma and parse the entries in the resulting string array into an int array.
#1 seems simpler to me, as you start out with a string array.

You might want to consider splitting one String on a comma? See here : How to split a string in Java

Related

Accessing index values before and after symbol from input

I am trying to take the input and if there is an # symbol in the input then it finds the maximum of the integers before and after the # symbol. The maximum part I have no problem with but I do not know how to access and find the values before and after the # symbol.
import java.util.Scanner;
public class Max_Min {
public static void main(String[] args) {
//gets keyboard
Scanner keyboard = new Scanner(System.in);
//puts input into string
String inputString = keyboard.nextLine();
//splits string between characters
String[] splitInput = inputString.split("");
for (String s : splitInput) {
if(s.equals("#")){
//computes the maximum of the two integers before and after the #
}
}
//close keyboard
keyboard.close();
I did do a search to find something simliar (and im sure there is something) but could not find anything. If someone could help that would be great!
Try with this:
for (int i = 0; i < splitInput.length; i++){
if (splitInput[i].equals("#") && i != 0 && i != splitInput.length -1){
int max = Math.max(Integer.parseInt(splitInput[i - 1]), Integer.parseInt(splitInput[i + 1]));
}
//...
}
You could try:
String[] splitInput = inputString.split("#");
which would split your string at the #s.
Then you can do a iteration over your splitInput array and do a .length on each index.
You have written the simple for loop, with which you can only access the string, but not its index in the array. If you had the index, you could write:
int possibleMax = Integer.parseInt(splitInput[i - 1]) + Integer.parseInt(splitInput[i + 1]);
To get the index, there are two ways:
for (int i = 0; i < splitInput.length; i++) {
String s = splitInput[i];
...
}
Or:
int i = 0;
for (String s : splitInput) {
…
i++;
}
I don't like either version because both are more complicated than absolutely necessary, in terms of written code. If you would use Kotlin instead of Java, it would be:
splitInput.forEachIndexed { i, s ->
…
}
In Java this could be written:
forEachIndexed(
splitInput,
(i, s) -> …
);
The problem in Java is that the code inside the … cannot update the variables of the enclosing method. I'm not sure whether this will ever change. It would be possible but needs a lot of work by the language committee.
A simple way to do this would be
String input = "12#23";
String [] arr = input.split("#");
if (arr.length == 2) {
System.out.println("Max is "+Math.max(Integer.valueOf(arr[0]),Integer.valueOf(arr[1])));
}

"Method in class cannot be applied to given types" error when trying to call method

I'm new here so if my question is wrong somehow let me know and I apologize in advance.
I'm creating a program for taking user input, putting it into an array and then reverse the arrays and checking for palindromes. The program will then print the palindromes from 101 to the user input number. Right now I just want to check if the loop I created for reversing the arrays is working, but when I call on the method I get the error
"method reverseArray in class Palindrome cannot be applied to given types"
required: char[]
found: no arguments
reason: actual and formal arguments differ in length
Here is the code (bottom three methods are empty right now because I haven't gotten to writing them yet).
public static void main(String[] args)
{
Scanner promptUser = new Scanner(System.in);
System.out.print("Enter an Integer greater than 100: ");
Integer userInt = new Integer(promptUser.nextInt());
String userString = userInt.toString();
char[] charUser = userString.toCharArray();
if (userInt <= 100)
{
System.out.print("That integer is not greater than 100,"
+ " restart program and try again!");
}
System.out.println(reverseArray());
}
/**Takes the integer provided by the user and turns it into a string
* then takes that string and puts it into a char[], then there is a for loop
* to reverse that array.
* #param userArray array used to store the reversed string.
* #revArray char array used to store data from charChange array.
* #return returns charChange now with the reversed string.
*/
public static char[] reverseArray(char[] userArray)
{
char[] revArray = new char[userArray.length];
for(int i = 0; i < revArray.length; i++)
{
userArray[i] = revArray[revArray.length - 1 - i];
}
return userArray;
}
public static boolean arraysAreEqual(char[] arrayPal1, char[] arrayPal2)
{
}
public static boolean isPrime(int Primes)
{
}
public void printArray(char[] charChange)
{
}
You didn't pass any paramter to function, and it expect array as a paramter:
reverseArray(charUser);
and are you expecting to print the array through
System.out.println(reverseArray());
this will print the address for the array, you will have to loop over the array elements to print it, something like:
char[] resultArray = reverseArray(charUser);
for(int i = 0; i < resultArray.length; i++)
{
System.out.println(resultArray[i]);
}

Java Beginning Scanner

I am a novice programmer and I am trying to do projects that I find fun to help me learn more about the language then my school classes have been able to provide. I have wanted to try reversing a string but instead of having the string defined in a string I have added a scanner to be able to allow a user to input what they want. After searching for any help I haven't been able to find my issue that I am having. So far I have this:
import java.util.ArrayList;
import java.util.Scanner;
public class Reverse {
static ArrayList<String> newString = new ArrayList();
static int inputLength = 0;
static String PlaceHolder = null;
static String beReturned = null;
static int lengthArray = 0;
static String ToBeReversed;
static String hold = null;
public static void reversal(){
inputLength = ToBeReversed.length();
for (int e = 0; e <= inputLength; e++)
{
PlaceHolder = ToBeReversed.substring(inputLength -1, inputLength);
newString.add(PlaceHolder);
}
}
public static String putTogether()
{
int lengthcounter = 0;
lengthArray = newString.size();
for (int i = 0; i < lengthArray; i++)
{
beReturned = beReturned + newString.get(lengthcounter);
if (lengthcounter < lengthArray)
{
lengthcounter++;
}
}
return beReturned;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in); //create a new scanner
ToBeReversed = input.nextLine();
Reverse.reversal();
Reverse.putTogether();
}
}
For any input that I input there is no result. I don't get an Error Message or any form of return... The output is blank. I am just wondering if I made a mistake with the scanner or if it is how I am trying to store the characters/access them from the ArrayList I created. I am trying to not have others give me the answer completely with all the fixes, I hope I can just get a pointer or a hint to where I am messing up. Thank you for your time and help.
You need to print the output, for example
public static void main(String[] args) {
Scanner input = new Scanner(System.in); //create a new scanner
ToBeReversed = input.nextLine();
System.out.println("ToBeReversed = " + ToBeReversed);
Reverse.reversal();
System.out.println("newString = " + newString);
System.out.println(Reverse.putTogether());
}
I don't want to give a complete answer, as that would spoil your fun (and steal an opportunity for your to get started with using a debugger), but here are some hints...
You can use String#charAt to get an individual character from a String at a given index
Java is generally 0 indexed, that means that things like arrays, String, List start at index 0 and go through to length - 1
null + String = nullString ;)
You can run a loop backwards. for-loop doesn't have to run from 0-x in ascending order, they can run x-0 in descending order ;)

How to store numbers from a file into an array

I cannot figure out what is wrong with this.
I have to read in a file (the file has numbers) and store the numbers into an array.
Here is the file:
http://dl.dropboxusercontent.com/u/31878359/courses/15/scores1.txt
I understand the first number is a zero and I cannot change the numbers or the order of the numbers in the file.
File
0
10
20
30
40
50
60
70
80
90
Here is my code:
import java.util.*;
import java.io.*;
public class Check {
public static void main(String[] args)
throws FileNotFoundException {
Scanner input = new Scanner(new File("scores1.txt"));
process(input);
}
public static void process(Scanner input) {
int[] numbers = new int [input.nextInt()];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = input.nextInt();
}
Arrays.sort(numbers);
System.out.print("numbers: "+Arrays.toString(numbers));
}
}
This is the output:
numbers: []
I'm assuming it's a problem with declaring the array.
The problem is that, your first value of file is 0. So array size is 0. Change your first value so that, you can get rest of values into array.
The first value in the file is 0.
int[] numbers = new int [input.nextInt()]; // this input.nextInt() gets the first line
You're making an array of size 0
Since there are 10 numbers in the file. initialize with size 10;
int[] numbers = new int [10];
public static void process(Scanner input) {
List<Integer> number = new ArrayList<Integer>();
while(input.hasNext()) {
number.add(input.nextInt());//i hope all ints are there in the file
}
int[] numbers = number.toArray(new int[number.size])
//then do sort and all
}
hope this will help
My suggestion would be use ArrayList
public static void process(Scanner input) {
List list = new ArrayList();
while(input.hasNextInt()){
list.add(input.nextInt());
}
Collections.sort(list);
System.out.print("numbers: " + list);
}

How to find end of line and perform addition of two integer arrays in java?

How to find how many tokens are there in a line in the below program and then
I need to add two integer arrays using Java, since I am more familiar with php, this is a bit challenging for me . Also I am getting the input from a text file. Hence, here is how I have my program so far.
The input file would have multiple lines like this
3736 17234 29823 84478 123745 2371 34237 823712
import java.io.*;
import java.util.*;
public class Sum {
//must use a constant for the length of the array
static int[] total= new int[25];
static int[] val = new int[25];
static int line= 0;
static int word =0;
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("Input.txt"));
// System.out.println("0");
processFile(input);
}
public static void processFile(Scanner input) {
//in this method you need to read your input file
//. read one line at a time and call the method processLine to
while (input.hasNextLine())
{
line++;
String line = input.nextLine();
Scanner lineScan = new Scanner(line);
//System.out.println("1");
processLine(input);
//System.out.println(line);
}
}
public static void processLine(Scanner data) {
//in this method you read tokens from line that has been passed to
// this methd as the parameter. method transfer needs to be called to
// transfer each token into an array of length DIGITS. Note that in a
// line you might only have one token
while(data.hasNext())
{
String x = data.next();
//System.out.println("2");
transfer(x,val);
}
}
public static void transfer(String data, int[] digits) {
//This method transfer the string into array of integers value.
int len = data.length();
int n=24;
for(int i=0;i<=n;i++)
digits[i]=0;
//System.out.println("3");
while(len>0)
{
// System.out.println(data.charAt(len-1));
char z=data.charAt(len-1);
int d = Character.digit (z, 10);
digits[n]=d ;
len=len-1;
n=n-1;
}
for(int i=0;i<=n;i++)
digits[i]=0;
for(int i=0;i<25;i++)
{
//System.out.println(digits[i]);
}
System.out.println("\n");
add(digits);
}
public static void add(int[] digits) {
word++;
if (word>1)
{
for(int i=0; i<= 4; i++)
{
total= total[i]+digits[i];
}
}
if(word==0)
total=digits;
}
public static void print(int[] digits) {
//For printing
}
}
Use a for loop to go through the 2 arrays and add each element.
Quick example code below:
private int[] sumTwoArrays(int [] a, int [] b){
if(a.length!=b.length){
throw new IllegalArgumentException("Arrays are not of same length!");
}
int[] sum = new int[a.length];
for(int i=0;i<a.length;i++){
sum[i] = a[i]+b[i];
}
return sum;
}
UPDATE: After the comments below I added another method on how to add just the elements in one array.
private void readFile(){
long sum=0;
//do your FILE I/O here
//for each line you read into an array called input[] you call this method
sum += sumArray(input);
System.out.println(sum);
}
private long sumArray(long [] a){
long sum=0;
for(int i=0;i<a.length;i++){
sum += a[i];
}
return sum;
}
You complicated this far more than is necesary.
To begin with, you can remove the multiple function references, the scanner class can actually parse your file into integers, and can read multiple lines - so you don't need a new scanner for each line.
I think you can simply have one Scanner per file, and then constantly use the Scanner.nextInt() function to find the next integer value in that file.
Now depending on your definition of add, there are two things you could do.
If you're attempting to add corresponding elements of each array, to come with with a third array where x[i] = y[i] + z[i], then you simply need a for loop with the previous statement in it. Remember of course to substitute the real names of the variables.
If you're attempting to add up all the integers in both the arrays to get one integer (or long), you could use two for loops, one after another and constantly add the current element of the current array to a variable.

Categories