Trying to compare an array item to a useres input - java

I am trying to replace an object in an array if the user inputs the letter E/e. For example the array can contain 2 objects the first object in the array the user entered a 3, the user now inputs a 5 e, they new array object [0] becomes the new user input 5. Here is my code so far:
import java.text.*;
import java.io.*;
public class Lab1a {
public static void main (String argv []) throws IOException {
BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));
NumberFormat nf = NumberFormat.getNumberInstance ();
nf.setMaximumFractionDigits (2);
nf.setMinimumFractionDigits (2);
String inputValue;
double [] doubleValues = new double [1];
char char1, char2, char3;
inputValue = stdin.readLine ();
String [] Values2 = inputValue.split ("\\s+");
for (int i = 0; i < Values2.length; ++i)
doubleValues [i] = Double.parseDouble (Values2[i]);
double old = doubleValues[0];
double newNum = doubleValues[1];
//Line 3: 3 characters separated by spaces
inputValue = stdin.readLine ();
String [] Values3 = inputValue.split ("\\s+");
for (int i = 0; i < Values3.length; ++i);
char1 = Values3[0].charAt(0);
char2 = Values3[1].charAt(0);
char3 = Values3[2].charAt(0);
if (inputValues == 'double' + "e") {
System.out.println(old);
}
}

so I whipped this up fairly quickly and it answers your posted question.
It initializes your array to a fixed SIZE=10 and asks user for input till 'q' is entered.
if user enters 'digit e/E' then the last entered value will be replaced.
Hope that helps!
cheers!
import java.util.Scanner;
public class Lab1a {
public static void main(String[] args) {
final int SIZE =10;//SIZE of array, you can change that if you want to
int availableIndex =0;//available element to change
double [] values = new double [SIZE];
Scanner kb = new Scanner (System.in);
while(availableIndex < values.length){
System.out.println("Please enter a value, if you wish to modify the last input value, then please enter your new value followed by an E/e");
System.out.println("enter q to exit");
String input = kb.nextLine().trim();
if (input.equalsIgnoreCase("q"))System.exit(0);
String [] arr = input.split("\\s+");
//for (String s : arr)System.out.println(s);
//validate input
if (arr.length == 1){//no change requested
values [availableIndex++] = Double.parseDouble(arr[0]);
}
else{
if (arr[1].equalsIgnoreCase("e")){
values[(availableIndex-1)] = Double.parseDouble(arr[0]);//availableIndex++;
}
else{//user inputed a char other than e/E
values[availableIndex++]= Double.parseDouble(arr[0]);
}
}
//print contents
for (int i=0; i < availableIndex; i++){
System.out.print(values[i]+"; ");
}
System.out.println();
}
}
}

Related

How do I store the user input that is indented by a space into the String array and convert the number into int array?

I'm not that new to programming, but I had a problem when storing the user input to the string array and store it into an int array. Does anybody know how to fix my code? Or is there any other way?
I want to store this input into a separate int array and a string array.
User input:
"T 3"
"V 4"
"Q 19"
Expected result:
num[0] = 3
num[1] = 4
num[2] = 19
store[0] = "T"
store[1] = "V"
store[2] = "Q"
This code creates an index out of bounds:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
import java.util.*;
public class Main
{
public static void main(String[] args)
{
// Variable Declarations & Initializations
Scanner input = new Scanner(System.in);
int k = input.nextInt();
int[] num = new int[k];
String[] store = new String[k];
for(int i = 0; i < k; i++)
{
String[] paint = input.next().split(" ");
store[i] = paint[0];
num[i] = Integer.parseInt(paint[1]);
}//end loop
}//end main
]//end class
input.next() will only work if you took String data type but here you had taken int as the data type so it won't work here.
The problem is that you're calling input.next() which returns the next token, delimited by spaces. Therefore, the token itself can't contain any spaces. So the .split(" ") method call will always return a one-element array, so there is only a paint[0] and there is no paint[1]. It's not clear what you're trying to achieve in your code; if you expand the question, you may get some more answers.
Update: now that you've shown us your input and expected results, I think what you need to do is:
store[i] = input.next();
num[i] = input.nextInt();
Try this out
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int k = sc.nextInt();
int[] num = new int[k];
String[] store = new String[k];
for(int i=0; i<k; i++){
String s = sc.nextLine();
String str = sc.next();
int number = Integer.parseInt(sc.next());
num[i]=number;
store[i]=str;
}
for(int i=0; i<k; i++){
System.out.println(store[i] +" "+num[i]);
}
}
}
Check this. Minor changes done in your code.
import java.util.*;
public class Main
{
public static void main(String[] args)
{
// Variable Declarations & Initializations
Scanner input = new Scanner(System.in);
int k = Integer.parseInt(input.next());
int[] num = new int[k];
String[] store = new String[k];
input.nextLine();
for(int i = 0; i < k; i++)
{
String paint[] = input.nextLine().split(" ");
store[i] = paint[0];
num[i] = Integer.parseInt(paint[1]);
}//end loop
}//end main
}//end class

Java User Input array is only capturing 3 integers instead of five

This code is supposed to capture 5 user integers, print them out, then print them in reverse. It is capturing the first int only, and printing it 3 times, then printing the first integer again 5 more times without reversing. Test ends with "Process finished with exit code 0" which I think is says the program finished without errors -- which of course is not correct. I assume the issue is in how the user input array is stored. I have it assigning as userNum[i] with a limited array of 5, and int i =0 to begin array storage at userNum[0], so I'm not clear on why all the inputs are not captured up to userNum[4].
Thank you for any insight you can provide. I am very new to java and this is prework for my java class.
import java.util.Scanner;
public class ArrayReverse {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // scanner for input
final int NUM_VALS = 5; // number on int user able to enter
int[] userNum = new int[NUM_VALS]; // user integers storage
int j = 0;
int i = 0;
System.out.println("Enter integer values: ");
userNum[i] = scnr.nextInt(); // capture user input int
for (j = 0; j < NUM_VALS; j++) {
System.out.print("You entered: ");
System.out.println(userNum[i]);
++j;
}
System.out.print("\nNumbers in reverse: "); // statement to Print reversed array
for (j = NUM_VALS - 1; j >= 0; j--) {
System.out.print(userNum[i] + " ");
}
}
}
You need to work more about on for loops and study how to iterate values in for loop, the problem in your i,j variables.
Here I fix your code.
import java.util.Scanner;
public class ArrayReverse {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // scanner for input
final int NUM_VALS = 5; // number on int user able to enter
int[] userNum = new int[NUM_VALS]; // user integers storage
int j = 0;
int i = 0;
//for 5 inputs you need loop
for(;i<NUM_VALS;i++){
System.out.println("Enter integer values: ");
userNum[i] = scnr.nextInt(); // capture user input int
}
for (j = 0; j < NUM_VALS; j++) {
System.out.print("You entered: ");
System.out.println(userNum[j]);
//++j; //no need to increment as you already did in for loop
}
System.out.print("\nNumbers in reverse: "); // statement to Print reversed array
for (j = NUM_VALS - 1; j >= 0; j--) {
System.out.print(userNum[j] + " ");// userNum[0] = your last value which you reverse
}
}
}
Here is a solution using the collections framework:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class ArrayReverse {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // scanner for input
final List<Integer> numbers = new ArrayList<>();
System.out.println("Enter any number of integers. (whitespace delimited. enter a non-integer to quit.): ");
while (scnr.hasNextBigInteger()) {
final int n = scnr.nextInt();
System.out.println("Parsed: " + n);
numbers.add(n);
}
System.out.println("Done reading user input.");
System.out.println("Your input: " + numbers);
Collections.reverse(numbers);
System.out.println("Your input reversed: " + numbers);
}
}
I have provided you with a solution. This is a clean way of doing it.
nextInt() reads the next integer that the user inputs. Notice that this will throw a InputMismatchExceptionif the user does not input a integer as value.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Integer> input = new ArrayList<Integer>();
//Simple loop that will read 5 user inputs
//and add them to the input list
for(int i = 0; i < 5; i++){
input.add(scanner.nextInt());
}
//print the 5 values
for(Integer val : input){
System.out.println(val);
}
//reverse the 5 values
Collections.reverse(input);
//print the 5 values again, but they are now reversed
for(Integer val : input){
System.out.println(val);
}
}

Why do I always get to enter a-1 strings in this string array?

Why do I always get to enter a-1 strings in this string array?
public class Source {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// Declare the variable
int a;
// Read the variable from STDIN
a = in.nextInt();
String strs[]=new String[a];
for(int i=0;i<a;i++)
strs[i]=in.nextInt();
}
}
You can change condition in your loop, like this :
for (int i = 0; i < a - 1; i++) {
strs[i] = in.nextInt();
}
You are iterating correctly a number of times equal to a. Not a-1. So the question appears to be invalid:
public class Source {
public static void main(String[] args) {
try(Scanner in = new Scanner(System.in)) {
// Declare the variable
int a;
System.out.print("How many Strings would you like to enter? ");
// Read the variable from STDIN
a = in.nextInt();
String[] strs = new String[a]; // this will fail for certain values of `a`
for(int i=0; i<a; i++) {
System.out.format("Enter String number %d: ", i+1);
strs[i]= in.next();
}
System.out.println("Result: " + Arrays.toString(strs));
}
}
}
run:
How many Strings would you like to enter? 2
Enter String number 1: Apple
Enter String number 2: Pen
Result: [Apple, Pen]

Trouble understanding an InputMismatch Exception in a simple programme

I have to write a program that reads in a sequence of integers until 'stop' is entered, store the integers in an array and then display the average of the numbers entered. I'm getting an input mismatch exception when entering 'stop' so it doesn't really work, but I have no idea why. Help would be greatly appreciated.
import java.util.Scanner;
public class MeanUsingList {
public void mean() {
String s;
int n = 0;
int i = 1;
int[] array = { n };
do {
System.out.println("Enter an integer");
Scanner in = new Scanner(System.in);
n = in.nextInt();
s = in.nextLine();
} while (s != "stop");
{
System.out.println("Enter an integer");
Scanner in2 = new Scanner(System.in);
int x = in2.nextInt();
array[i] = x;
i++;
}
int av = 0;
for (int y = 0; y < array.length; y++) {
av += array[y];
}
System.out.println(av);
}
public static void main(String[] args) {
MeanUsingList obj = new MeanUsingList();
obj.mean();
}
}
First int[] array = { n }; just creates an array with 0 as the element in it.
the logic inside it will never execute while (s != "stop");
You want something like this
List list = new ArrayList();
//instead of array used arraylist because of dynamic size
do {
System.out.println("Enter an integer");
Scanner in = new Scanner(System.in);
n = in.nextInt(); //get the input
list.add(n); // add to the list
Scanner ina = new Scanner(System.in); // need new scanner object
s = ina.nextLine(); //ask if want to stop
} while (!s.equals("stop")); // if input matches stop exit the loop
System.out.println(list); // print the list
I recommend you to learn the basics

Wrong return type in method

I need to make a program that adds long integers without using the biginteger class.
I am working on the add method now and I think I have it correct but I am stuck on returning the correct data type for my method and I'm not sure how to correct it.
Here are my 2 classes so far:
Main Class:
import java.util.Scanner;
public class testLargeInteger
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String string1;
String string2;
int exp =0;
System.out.print("Enter the first integer: ");
//Store up the input string “string1” entered by the user from the keyboard.
string1 = input.next();
LargeInteger firstInt = new LargeInteger(string1);
System.out.print("Enter the second integer: ");
string2 = input.next();
//Store up the input string “string2” entered by the user from the keyboard.
LargeInteger secondInt = new LargeInteger(string2);
System.out.print("Enter the exponential integer: ");
//Store up the input integer “exp” entered by the user from the keyboard.
exp = input.nextInt();
LargeInteger sum = firstInt.add(secondInt);
System.out.printf ("First integer: %s \n", firstInt.display());
System.out.println("Second integer: " + secondInt.display());
System.out.println(" Exponent: " + exp);
System.out.printf (" Sum = %s \n", sum.display());
}
}
LargeInteger.class:
public class LargeInteger
{
private int[] intArray;
//convert the strings to array
public LargeInteger(String s)
{
intArray = new int[s.length()];
for (int i = 0; i < s.length(); i++)
intArray[i] = Character.digit(s.charAt(i), 10); // in base 10
}
//display the strings
public String display()
{
String result="";
for (int i = 0; i < intArray.length; i++)
result += intArray[i];
return result.toString();
}
//get first array
public int[] getIntArray()
{
return intArray;
}
public LargeInteger add(LargeInteger secondInt)
{
int[] otherValues = secondInt.getIntArray();
int maxIterations = Math.min(intArray.length, otherValues.length);
int currentResult; //to store result
int[] resultArray = new int[Math.max(intArray.length, otherValues.length) + 1];
int needToAdd = 0; //to store result should be added next step
for(int i = 0; i < maxIterations; i++)
{
currentResult = intArray[i] + otherValues[i];
resultArray[i] = currentResult % 10 + needToAdd; //if more than 9 its correct answer
needToAdd = currentResult / 10; //this is what you need to add on next step
}
resultArray[Math.max(intArray.length, otherValues.length) + 1] = needToAdd;
return resultArray;
}
}
You need a second LargeInteger constructor:
public LargeInteger( int[] array ) {
intArray = array
}
Then your method can return:
return new LargeInteger( resultArray );
Well first thing, your method add in LargeInteger is supposed to return a LargeInteger, but instead returns an array (int[]). You could fix this by adding a constructor for LargeInteger that takes in an int[] parameter (i.e. LargeInteger(int[] digitArray)). Then, in your add method you could simply do: return new LargeInteger(resultArray);.

Categories