So here's what i'm trying to do. Have user input numbers, store them in an array, then print all those numbers out on one line. I must use a method/function as well. I think i have done quite well so far, it shows no errors in eclipse. What im stuck on is storing their input into an array. i want them to keep inputting numbers one at a time until they're satisifed and type 'quit'. i just havent read about how to store things in an array despite looking around, particularly storing more than one thing, progressively. here is my code so far, and thank you in advance for any help!
import java.util.Scanner;
public class intarray {
public static void main(String[] args) {
System.out.println("Enter a number then hit enter. You may then enter another number or end by typing quit.");
String x;
Scanner input = new Scanner(System.in);
while (true) {
x=input.next();
if (x.equalsIgnoreCase("quit")) {break;}
if (x.equals(null)) throw new Error("You entered nothing. Try again.");
int stringLength = x.trim().length();
if (stringLength == 0) throw new Error("Seems you only entered spaces. Try again.");
isNum(x);
int goingintoarray = Integer.parseInt(x);
int array[];
}
}
public static String isNum(String t) {
int user=Integer.parseInt(t);
String convertback = Integer.toString(user);
return convertback;
}
}
Since you don't know how many elements there will be an array is a bad idea since you will have to resize it quite often as new elements appear (copying arrays is expensive!) or instantiate a large enough array at the beginning (which is a waste and still doesn't protect you in 100% from having to resize it eventually).
Instead using Java's List (preferably LinkedList) sounds like a good idea since you can add elements dynamically without resizing the data structure.
List<Integer> numbers = new LinkedList<>();
while(true) {
// something
numbers.add(goingintoarray);
// something
}
Be careful of other implementations - for instance ArrayList uses an array (d'uh ;-) ) to store the elements so you would have the same problem but the resizing part would be taken care of for you by the implementation.
#Edit: by convention classes in Java are written using CamelCase starting with an uppercase letter.
ArrayList<Integer> inputs = new ArrayList<Integer>();
while (true) {
Scanner input = new Scanner(System.in);
x=input.next();
if (x.equalsIgnoreCase("quit")) {break;}
if (x.equals(null)) throw new Error("You entered nothing. Try again.");
int stringLength = x.trim().length();
if (stringLength == 0) throw new Error("Seems you only entered spaces. Try again.");
inputs.add(Integer.parseInt(x));
}
You don't want the isNum method since it gives same exception here if it gets wrong input for x.
import java.util.Scanner;
public class intarray {
public static int initSize = 5;
public static void main(String[] args) {
System.out.println("Enter a number then hit enter. You may then enter another number or end by typing quit.");
int array[] = new int[initSize];
int pos = 0;
int maxSize = initSize;
String x = null;
Scanner input = new Scanner(System.in);
while (true) {
x = input.next();
if (x.equalsIgnoreCase("quit")) {
break;
}
//input empty string, java io can filter. So , x impossible "null" or null.
//if (x.equals(null))
// throw new Error("You entered nothing. Try again.");
int stringLength = x.trim().length();
if (stringLength == 0)
throw new Error("Seems you only entered spaces. Try again.");
Integer numX = isNum(x);
// if the array is full, extend it
if(pos == maxSize){
int[] newArray = new int[2 * maxSize];
System.arraycopy(array, 0, newArray, 0, maxSize);
array = newArray;
maxSize = array.length;
}
if(null == numX)
System.out.println(x + " isn't a number."); //choose notify or throw error
else
array[pos++] = numX;
}
printArray(array, pos);
}
public static Integer isNum(String t) {
try {
return Integer.parseInt(t);
} catch (NumberFormatException e) {
return null;
}
}
public static void printArray(int[] array, int pos) {
if(null == array || array.length == 0 || pos <= 0)
return ;
for(int i = 0 ; i < pos; i++)
System.out.print(array[i] + " ");
}
}
Related
I had this code where after reading the first three lines of input, it would just terminate the program and would not let me enter the next line. Here's the code:
import java.util.Arrays;
import java.util.Scanner;
public class cycle {
public static void main(String[] arg)
{
System.out.println("Put in numbers");
Scanner in=new Scanner(System.in);
int indicator=Integer.parseInt(in.nextLine());
if(indicator==1)
{
mission1();
}
else if(indicator==2)
{
mission2();
}
in.close();
}
static void mission1()
{
Scanner miss1=new Scanner(System.in);
int citizens=Integer.valueOf(miss1.nextLine());
String lines=miss1.nextLine();
lines=lines.replaceAll("\\s", "");
int length=lines.length();
String lines2=miss1.nextLine();
lines2=lines.replaceAll("\\s", "");
int length2=lines.length();
while(citizens!=length||citizens!=length2)
{
System.out.println("Citizens number do not match, try again" );
miss1=new Scanner(System.in);
citizens=Integer.valueOf(miss1.nextLine());
lines=miss1.nextLine();
lines=lines.replaceAll("\\s", "");
length=lines.length();
lines2=miss1.nextLine();
lines2=lines.replaceAll("\\s", "");
length2=lines.length();
miss1.close();
if(citizens!=length||citizens!=length2)
{
throw new IndexOutOfBoundsException("Numebr of citizens do not match. Please enter numbers again");
}
else if(citizens==length&&citizens==length2)
{
String[] strs=lines.trim().split("\\s");
length=lines.length();
int[] dspeed = new int[length];
for(int i=0; i<length;i++)
{
dspeed[i]=Integer.parseInt(strs[i]);
}
String[] strs2=lines2.trim().split("\\s+");
int[] pspeed = new int[length2];
for(int i=0; i<length2;i++)
{
pspeed[i]=Integer.parseInt(strs2[i]);
}
Arrays.sort(dspeed);
break;
}
}
}
static void mission2()
{
}
}
For example, with an input like this:
Put in numbers
1
3
1 3 5
1 3 5
It would just terminate the program and it is ok, but with an input like this:
Put in numbers
1
3
1 3
1 3
Citizens number does not match, try again
1
3
1 3 5
The program would terminate before I can't put in the fourth line.
As a test I put in
for(int n=0;n<length;n+=1)
{
System.out.println(dspeed[n]);
}
in between Arrays.sort(dspeed[n]) and break, and the result is like this
Put in numbers
1
3
1 3
1 3
Citizens number do not match, try again
1
3
1 3 5
3
It makes no sense since it is giving me an output of 3 while not letting me enter the second line. So it is like part of the code is being skipped. Why is this happening and how do I fix this?
Edit: For mission1 it suppose to get a number(let's say x), and then get x numbers of different numbers from the next line. Then, it should put those numbers in an array and sort them
As of writing my answer I realized what the actual cause of your error is; look at this piece of code:
lines=miss1.nextLine();
lines=lines.replaceAll("\\s", "");
length=lines.length();
lines2=miss1.nextLine();
/*Should be lines2!*/
lines2=lines.replaceAll("\\s", "");
/*Should be lines2!*/
length2=lines.length();
You're using linesfor all your variables. Changing lines to lines2 for the lines2 = ... and length2 variables fixed the issue that you posted. I also replaced
if (citizens != length || citizens != length2) {
/*If you decide to keep this, it should not be a "IndexOutOfBoundsException
(since no index was out of bounds) but should perhaps be a "IllegalArgumentException"
since you supplied it illegal arguments.*/
throw new IndexOutOfBoundsException("Numebr of citizens do not match. Please enter numbers again");
} else if (citizens == length && citizens == length2) { ... }
with
if (citizens == length && citizens == length2) { ... }
Since otherwise this would cause the program to crash if you gave it an invalid input twice in a row.
This part of the answer should be considered code-review and is here to (try to) help improve your code structure. Actual answer is above.
This is the entire class code. This seems to have resolved your error and I've also re-structured some of the code and added comments explaining what I edited and why I restructured it. Please leave a comment if anything is unclear or if it didn't actually resolve your error. Please note that the imports are left out of this answer for clarity.
public class Cycle {
/* Important! We can re-use the same scanner for all inputs. */
final Scanner in;
public Cycle() {
in = new Scanner(System.in);
run();
in.close();
}
private void run() {
System.out.println("Input mission number.");
final int indicator = Integer.parseInt(in.nextLine());
if (indicator == 1) {
mission1();
} else if (indicator == 2) {
// etc
}
}
private void mission1() {
while (true) {
System.out.println("Input number of citizens.");
final int citizens = Integer.valueOf(in.nextLine());
/* We don't edit these two first inputs just yet since we
* have to use the un-edited inputs later in our if-else
* statement. */
System.out.println("Input first number(s).");
final String inputOne = in.nextLine();
System.out.println("Input second number(s).");
final String inputTwo = in.nextLine();
final String lines = inputOne.replaceAll("\\s", "");
final int length = lines.length();
final String lines2 = inputTwo.replaceAll("\\s", "");
final int length2 = lines2.length();
if (citizens != length || citizens != length2) {
/* If the number of citizens doesn't match it just
* continues the while-loop and does it all over
* again. */
System.out.println("Citizens number do not match, try again");
} else {
/* Here we use the unedited inputs from before - which
* is why we didn't edit them. */
final int[] dspeed = createArrayFromInput(inputOne);
final int[] pspeed = createArrayFromInput(inputTwo);
break;
}
}
}
/* We shouldn't have duplicated code - use a method instead. */
private int[] createArrayFromInput(final String input) {
final String[] strs = input.trim().split("\\s+");
/* The arrays should be the same size so use 'strs.length' as
* length */
final int[] speed = new int[strs.length];
for (int i = 0; i < strs.length; i++) {
speed[i] = Integer.parseInt(strs[i]);
}
Arrays.sort(speed);
return speed;
}
public static void main(final String[] arg) {
/*We should use a class instance instead of static methods and variables.*/
new Cycle();
}
}
public class Sort {
public static void main(String[] args) {
int i = 1;
Scanner input = new Scanner(System.in);
// prompts the user to get how many numbers need to be sorted
System.out.print("Please enter the number of data points: ");
int data = input.nextInt();
// this creates the new array and data sets how large it is
int [] userArray = new int[data];
// this clarifies that the value is above 0 or else it will not run
if (data < 0) {
System.out.println("The number should be positive. Exiting.");
}
// once a value over 0 is in, the loop will start to get in all user data
else {
System.out.println("Enter the data:");
}
while (i <= data) {
int userInput = input.nextInt();
userArray[i] = userInput;
i++;
}
// this calls the sortArray method to sort the values entered
sortArray(userArray);
// this will print the sorted array
System.out.println(Arrays.toString(userArray));
}
}
I have set the array size equal to what the user inputs for how many variables they will be entering to be sorted. For some reason, Java only wants a set number instead of the number that is entered by the user. Is there a way to make this work?
First of all, there are a few mistakes in your code. You are checking if(data < 0) after you create your array with int[] userArray = new int[data];. You should check it before.
Furthermore, you will get ArrayIndexOutOfBoundsException because userArray[data] does not exist. Array indices start at 0, so the last index is data-1. You need to change your while-loop to while(i < data) instead of while(i <= data).
The problem is not that you have data instead of 10 as the length of the array. The problem is as I stated above: your while-loop.
Your issue is the while loop. Because arrays are 0 based and you need to only check if i < data. By setting it to <=, you are exceeding the array length and generating and ArrayIndexOutOfBoundsException
while (i < data) {
int userInput = input.nextInt();
userArray[i] = userInput;
i++;
}
You are over-indexing the array. A more standard way for inputting the data would be
for ( int i=0; i < data; i++ ) {
userArray[i] = input.nextInt();
}
not the whole program but what this program does is that it takes a bunch of numbers and separates the even and odds.
public static void main(String [] args)
{
Scanner stdin = new Scanner(System.in);//for user input
int[] evenNum = new int [100];//Even Array up too 100
int[] oddNum = new int[100];//Odd Array up too 100
int evenIndex=0;//even numbers
int input=0;//user input
int i=0;//incrementer for arrays
int k=0;
int j=0;
String name;
System.out.println("Type In Your Name");//Type in name
name = stdin.nextLine();
try{
while ((i < oddNum.length && i < evenNum.length) && input != -1)
//Makes sure no more than 100 numbers can be placed.
{
System.out.println(name+" Enter a positive number, Enter -1 For results");
input= stdin.nextInt();
oddNum[i]=input;
i++;//Increments array
}
}
catch(Exception d)
{
System.out.println("Only Numbers Please");//Makes sure only numbers can be displayed
}
I have tried using return but this is a type void so I cant.Is their a pass reference i can use? .
Put the try catch inside the while loop
while ((i < oddNum.length && i < evenNum.length) && input != -1)
//Makes sure no more than 100 numbers can be placed.
{
try {
System.out.println(name+" Enter a positive number, Enter -1 For results");
input= stdin.nextInt();
oddNum[i]=input;
i++;//Increments array
}
catch(Exception d)
{
System.out.println("Only Numbers Please");//Makes sure only numbers can be displayed
}
}
Catch the exception where you actually want to handle it.
Consider your structure:
try {
while {
//...
}
} catch {
//...
}
When you're in the catch block, the while block is finished. The flow has exited that block, and thus there's no return path to it. Basically, the loop is over.
On the other hand, consider this:
while {
try {
//...
} catch {
//...
}
}
In this case, when you exit the catch block, you're still in the while block. So the loop can continue.
I am writing a program that would help me find whether the number entered is a palindrome or not but i am trying it using arrays. And i would like to know if that is even possible?? And if it is possible then what am i doing wrong.
I have marked the code where i think the problem lies but feel free to suggest anything.!!!!
Thanks!!!
import java.util.Scanner;
public class palindrome
{
public static void main(String args[])
{
int size = 10,i,j,flag=0;
int num[] = new int[size];
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the number ");
size = sc.nextInt();
System.out.println("Enter the number ");
for(i=0;i<size;i++)
{
num[i]=sc.nextInt();
}
i=size-1;
for(j=0;j<(size/2);j++,i--)
{
if(i>(size/2))
{
if(num[i]==num[j])
{
flag = 1;
}
}
}
if(flag==1)
{
System.out.println("The number is a palindrome");
}
else
System.out.println("The number is not a palindrome ");
}
}
Edit: Guys the problem is actually solved because i was doing a blunder mistake i.e. i was asking the user to enter the number in the form of an arry but i was not actually entering the digits in the number one by one instead i was entering the whole number in the first iteration.
But still a lot of thanks for the replies. I would still try your ideas and let you guys know. Thanks
:)
Try
public boolean isPalindrome(int[] num){
for(int i = 0 ; i < num.length/2 ; i++) {
if(num[i]!=num[num.length-(i+1)]) return false;
}
return true;
}
Yes it's possible, moreover, it's possible by using ArrayList, String - whatever you like. In order to write down a correct implementation, first decompose your current solution:
// Extract a method, do not cram all code into main()
// note: all you need is array, to get size of the array, put value.length
private static boolean isPalindrome(int[] value) {
...
}
public static void main(String args[]) {
int userInput[];
...
if (isPalindrome(userInput)) {
System.out.println("The number is a palindrome");
}
else {
System.out.println("The number is not a palindrome");
}
}
Now, let's implement isPalindrome():
private static boolean isPalindrome(int[] value) {
if (null == value)
return true; //TODO: or false, or throw exception
for (int i = 0; i < value.length / 2; ++i)
if (value[i] != value[value.length - 1 - i])
return false;
return true;
}
The easiest and most intuitive way (imo) to check for palindromes is through recursion. The idea is simple:
Is the first and last char the same?
YES Remove first and last char and check first and last char of the new String
NO There is no palindrome.
When the input is only 1 char then it's trivial.
Have a look at this code:
private void isPalindrome(String number){
if(number.length() == 1){
System.out.println("yes");
}else if(number.charAt(0) == number.charAt(number.length()-1)){
isPalindrome(number.substring(1, number.length()-1));
}else{
System.out.println("no");
}
}
Testing with:
isPalindrome(String.valueOf(232)) Returns "yes"
isPalindrome(String.valueOf(23)) Return "no"
Of course this also works with Arrays just as easily. Replace the parameter with an array and search through the indices the same way. When cutting down the array just create a new smaller array without first and last index of the previous array.
Your class has several issues:
First you're not checking if a number is a palindrome or not. Your algorithm is flawed
Second, you're asking to enter a size but in the end, the user inputs it but you don't use it yourself. Instead, you're using that introduced value in the number array.
Here's how you should do it.
public class Palindrome {
private static boolean isPalindrome(int[] array) {
for (int i = 0, j = array.length-1; i < j; i++, j--) {
if (array[i] != array[j]) {
return false;
}
}
return true;
}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("How many numbers do you want to enter? ");
int size = scanner.nextInt();
int[] numbers = new int[size];
for (int i = 0; i < size; i++) {
System.out.printf("Enter number %s: ", i+1);
numbers[i] = scanner.nextInt();
}
if (isPalindrome(numbers)) {
System.out.println("The number is a palindrome");
} else {
System.out.println("The number is not a palindrome");
}
}
}
I am trying to write code to have users input positive integers and have them sent to a linked list. The users input should end after entering a negative number. Furthermore, I am having issues writing an isSorted boolean method that will return true if the linked list is sorted in increasing order and false otherwise.
Here is the only code I have so far
import java.util.*;
public class List {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please type positive integers one by one separated by a space.");
System.out.println("When you are done, please type a negative integer.");
int num = input.nextInt();
}
public boolean isSorted(){
if(){
return true;
}
else{
return false;
}
}
}
public void input() {
System.out.println("Please type positive integers one by one separated by a space.");
System.out.println("When you are done, please type a negative integer.");
LinkedList<Integer> ll = new LinkedList<>();
//System.in.available()
Scanner input = new Scanner(System.in);
int num;
while ( input.hasNextInt() ) {
int i = input.nextInt();
if (i >= 0) {
ll.add(i);
}
}
System.out.println(ll+" <-- ll"); //TODO remove debugging code
System.out.println(isSortedAccending(ll)+" <-- isSortedAccending(ll)");//TODO
}
This works by returning false the moment something is found out of order.
public static boolean isSortedAccending(List<Integer> list){
if (list.size() < 2) {
return true;
}
Integer previous = list.get(0);
for (Integer next : list) {
if (previous > next) {
return false;
}
}
return true;
}
Outputs:
Please type positive integers one by one separated by a space.
When you are done, please type a negative integer.
1
2
3
-1
[1, 2, 3] <-- ll
true <-- isSortedAccending(ll)
isSortedDecending() looks exactly the same except it uses <.
import java.util.LinkedList;
import java.util.Scanner;
public class NumberListing {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please type positive integers one by one separated by a space.");
System.out.println("When you are done, please type a negative integer.");
int num = input.nextInt();
LinkedList<Integer> list = new LinkedList<Integer>();
while(num > 0){
list.add(num);
num = input.nextInt();
}
if(isSorted(list)){
System.out.println("The list is sorted");
} else{
System.out.println("The list is not sorted");
}
}
public static boolean isSorted(LinkedList<Integer> list){
boolean done = false;
boolean sorted = true;
for(int i = 1; i < list.size() && !done ; i++){
if(list.get(i) < list.get(i-1)){
done = true;
sorted = false;
}
}
return sorted;
}
}
Should be fairly simple. While the number you intake is greater than 0, store the number in a list and get the next one from the console.
After that, loop through the list starting with index 1 to check that each current number is greater than the previous number. I added an early exit so the loop quits anytime a number that is less than the previous number. this means it is unordered and we don't care about the rest.
However, if you're trying to create your own linked list that creates a lot more code and I would suggest looking in a text book or something of the sort to help.
You can put your int's in a container(LinkedList) by using the wrapper class Integer for int. The normal int is a standard primitive type and can not be used by containers, as containers can only work with objects of a class.
LinkedList<Integer> list = new LinkedList();
As for the isSorted method, you could iterate through the list and check if the current value is higher or equal to the previous value.
int prevValue = 0;
for(int i = 0; i < list.size(); i++){
if(!list.get(i) >= prevValue){
return false;
}
prevValue = list.get(i);
}
return true;
You'll want to read the next line as a String, split that line, and walk through the list of elements of that line, adding the positive elements to a LinkedList as you go. Make sure you store your scanner. You'll want to use nextLine, not nextInt.
import java.util.*;
public class List {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please type positive integers one by one separated by a space.");
System.out.println("When you are done, please type a negative integer.");
String line = input.nextLine();
String[] integers = line.split(" ");
LinkedList ll = new LinkedList<Integer>();
for (int i = 0; i < integers.length; i++)
{
if (Integer.parseInt(integers[i]) > 0)
ll.add(integers[i]);
}
System.out.println(isSorted(ll));
input.close();
}
Then, just use a simple comparison function for LinkedList to check if it's sorted:
public static <T extends Comparable<T>> boolean isSorted(LinkedList<T> iterable)
{
Iterator<T> iter = iterable.iterator();
if (!iter.hasNext()) {
return true;
}
T t = iter.next();
while (iter.hasNext()) {
T t2 = iter.next();
if (t.compareTo(t2) > 0) {
return false;
}
t = t2;
}
return true;
}