Putting array with unknown variables into another array - arrays

The purpose of this code is is to define the root of the sum of the squares.
I cant figure out how to put i into j. Please help.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int input, som, i=0;
int j = 0;
double answer;
Boolean gaDoor= true;
int [] array = new int [24];
while (gaDoor)
{
Console.Write("Specify a positive integer");
input = Convert.ToInt32(Console.ReadLine());
if (input == -1)
{
gaDoor = false;
}
else
{
if (input >= 0)
{
array[i] = input;
i++;
}
else
{
Console.WriteLine("Specify a positive integer ");
}
}
}
while (j<i)
{
sum = array [j] ^ 2;
answer = Math.Sqrt(sum);
Console.Write(answer);
}
Console.ReadKey();
}
}
}

using System;
namespace Test
{
class MainClass
{
public static void Main (string[] args)
{
int[] invoer = new int[24];
double[] resultaat = new double[24];
double totaal = 0;
double wortel = 0;
int commando = 0;
int teller = -1;
try {
// Keep going until a negative integer is entered (or a 0)
while ((commando = Convert.ToInt32 (Console.ReadLine ())) > 0) {
teller++;
invoer [teller] = commando;
}
} catch (FormatException) {
// Not a number at all.
}
teller = -1;
foreach (int i in invoer) {
teller++;
resultaat [teller] = Math.Pow (invoer [teller], 2);
totaal += resultaat [teller];
if (invoer [teller] > 0) {
Console.WriteLine ("Invoer: {0}, Resultaat: {1}", invoer [teller], resultaat [teller]);
}
}
wortel = Math.Sqrt (totaal);
Console.WriteLine ("Totaal: {0}, Wortel: {1}", totaal, wortel);
}
}
}

Related

unable to initialize array size from parametrize constructor of class Stack1...but if i directly feed integer value to array code work fine

package the_JC;
public class Cls_01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Stack1 obj1 = new Stack1(20);
for(int i = 1; i<=obj1.len; i++) {
obj1.push(i*3+i);
}
for(int i=0; i < obj1.len; i++) {
System.out.println(obj1.pop());
}
}
}
class Stack1{
int len=0;
Stack1(int num){
len = num;
System.out.println(len);
}
int[] stck = new int[len]; // this array is not accepting len as value from constructor above ,taking len =0
int pos = -1;
void push(int value) {
System.out.println(stck.length);
if(pos==len-1) {
System.out.println("Overflowed");
} else {
stck[++pos] = value;
System.out.println("Pushed value :\t"+value);
}
}
int pop(){
if(pos<0) {
System.out.println("Underflow");
return 0;
} else {
return stck[pos--];
}
}
}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
at the_JC/the_JC.Stack1.push(Cls_01.java:33)
at the_JC/the_JC.Cls_01.main(Cls_01.java:10)**
class Stack1{
int len=0;
int[] stck;
int pos;
Stack1(int num){
len = num;
stck = new int[len];
pos = -1;
System.out.println(len);
}
void push(int value) {
System.out.println(stck.length);
if(pos==len-1) {
System.out.println("Overflowed");
} else {
stck[++pos] = value;
System.out.println("Pushed value :\t"+value);
}
}
int pop(){
if(pos<0) {
System.out.println("Underflow");
return 0;
} else {
return stck[pos--];
}
}
}

How to call runningSum function and print it?

package Package;
import java.util.Arrays;
class Cars {
public int[] runningSum(int[] nums) {
int sum = 0;
int[] res = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
sum = sum+nums[0];
res[i]=sum;
}
return res;
}
public static void main(String[] args) {
int[] a = {1,2,3,4};
Cars arr = new Cars();
System.out.println(arr.runningSum(a));
}
}
//output i'm getting is [I#e580929]
//output i want is [1,3,6,10]
Am not sure what you are trying to do by sum = sum+nums[0]; after the loop. But the solution below works!
public int[] runningSum(int[] nums) {
int sum = 0;
int[] res = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
sum = sum + nums[i];
res[i] = sum;
}
return res;
}
}

Is there any way to pass Observable<String> into AbstractInputStreamContent?

I'm working on uploading a text file to Google Drive
ByteArrayContent content = new ByteArrayContent("text/csv", fileContent.getBytes(Charset.forName("UTF-8")));
Drive.Files.Insert request = drive.files().insert(file, content);
where type(fileContent) = String
I'd like to refactor and change type of fileContent to Observable<String>, is there any nice workaround to pass it to that insert() function (which takes AbstractInputStreamContent as a second argument)?
Thanks
Here is a general Flowable -> InputStream bridge you can delegate to:
import java.io.*;
import java.nio.charset.Charset;
import java.util.concurrent.atomic.AtomicReference;
import org.reactivestreams.*;
import io.reactivex.FlowableSubscriber;
import io.reactivex.internal.subscriptions.SubscriptionHelper;
public final class FlowableStringInputStream {
private FlowableStringInputStream() {
throw new IllegalStateException("No instances!");
}
public static InputStream createInputStream(
Publisher<String> source, Charset charset) {
StringInputStream parent = new StringInputStream(charset);
source.subscribe(parent);
return parent;
}
static final class StringInputStream extends InputStream
implements FlowableSubscriber<String> {
final AtomicReference<Subscription> upstream;
final Charset charset;
volatile byte[] bytes;
int index;
volatile boolean done;
Throwable error;
StringInputStream(Charset charset) {
this.charset = charset;
upstream = new AtomicReference<>();
}
#Override
public void onSubscribe(Subscription s) {
if (SubscriptionHelper.setOnce(upstream, s)) {
s.request(1);
}
}
#Override
public void onNext(String t) {
bytes = t.getBytes(charset);
synchronized (this) {
notifyAll();
}
}
#Override
public void onError(Throwable t) {
error = t;
done = true;
synchronized (this) {
notifyAll();
}
}
#Override
public void onComplete() {
done = true;
synchronized (this) {
notifyAll();
}
}
#Override
public int read() throws IOException {
for (;;) {
byte[] a = awaitBufferIfNecessary();
if (a == null) {
Throwable ex = error;
if (ex != null) {
if (ex instanceof IOException) {
throw (IOException)ex;
}
throw new IOException(ex);
}
return -1;
}
int idx = index;
if (idx == a.length) {
index = 0;
bytes = null;
upstream.get().request(1);
} else {
int result = a[idx] & 0xFF;
index = idx + 1;
return result;
}
}
}
byte[] awaitBufferIfNecessary() throws IOException {
byte[] a = bytes;
if (a == null) {
synchronized (this) {
for (;;) {
boolean d = done;
a = bytes;
if (a != null) {
break;
}
if (d || upstream.get() == SubscriptionHelper.CANCELLED) {
break;
}
try {
wait();
} catch (InterruptedException ex) {
if (upstream.get() != SubscriptionHelper.CANCELLED) {
InterruptedIOException exc = new InterruptedIOException();
exc.initCause(ex);
throw exc;
}
break;
}
}
}
}
return a;
}
#Override
public int read(byte[] b, int off, int len) throws IOException {
if (off < 0 || len < 0 || off >= b.length || off + len > b.length) {
throw new IndexOutOfBoundsException(
"b.length=" + b.length + ", off=" + off + ", len=" + len);
}
for (;;) {
byte[] a = awaitBufferIfNecessary();
if (a == null) {
Throwable ex = error;
if (ex != null) {
if (ex instanceof IOException) {
throw (IOException)ex;
}
throw new IOException(ex);
}
return -1;
}
int idx = index;
if (idx == a.length) {
index = 0;
bytes = null;
upstream.get().request(1);
} else {
int r = 0;
while (idx < a.length && len > 0) {
b[off] = a[idx];
idx++;
off++;
r++;
len--;
}
index = idx;
return r;
}
}
}
#Override
public int available() throws IOException {
byte[] a = bytes;
int idx = index;
return a != null ? Math.max(0, a.length - idx) : 0;
}
#Override
public void close() throws IOException {
SubscriptionHelper.cancel(upstream);
synchronized (this) {
notifyAll();
}
}
}
}
Usage:
#Test(timeout = 10000)
public void async() throws Exception {
AtomicInteger calls = new AtomicInteger();
Flowable<String> f = Flowable.range(100, 10).map(Object::toString)
.doOnCancel(() -> calls.incrementAndGet())
.subscribeOn(Schedulers.computation())
.delay(10, TimeUnit.MILLISECONDS);
try (InputStream is = FlowableStringInputStream.createInputStream(f, utf8)) {
assertEquals('1', is.read());
assertEquals('0', is.read());
assertEquals('0', is.read());
byte[] buf = new byte[3];
assertEquals(3, is.read(buf));
assertArrayEquals("101".getBytes(utf8), buf);
}
assertEquals(1, calls.get());
}

Searching for an int in an array

I am trying to search for an int value in an array that has random numbers
this is what I have so far:
String names[]={"Peter","John","Rudy"};
int number[]=new int[3];
for(int z=0;z<3;z++)
{
number[z]=(int)(1+Math.random()*200);
}
int option=Integer.parseInt(JOptionPane.showInputDialog("choose and option:\n1.names\n2.sorting according to alphabet\n3.search number\n4.J"));
switch(option)
{
case 1:
{
for(int l=0;l<names.length;l++)
{
jTextArea1.append(""+names[l]+"\t"+number[l]+"\n");
}
}
break;
case 2:
{
String temp="";
for(int ii=0;ii<names.length;ii++)
{
for(int j=0;j<names.length;j++)
{
if(names[ii].compareToIgnoreCase(names[j])<0)
{
temp=names[ii];
names[ii]=names[j];
names[j]=temp;
}
}
}
for(int x=0;x<names.length;x++)
{
jTextArea1.append(""+names[x]+"\n");
}
}
break;
case 3:
{
boolean found=false;
int searchvalue=Integer.parseInt(JOptionPane.showInputDialog("number?"));
for(int i=0;i<number.length;i++)
{
if(number[i]==searchvalue)
{
found=true;
}
}
if(found==true)
{
jTextArea1.append("number is found"+"\n");
}
else
{
jTextArea1.append("number is not found"+"\n");
}
}
break;
case 4:
{
for(int q=0;q<names.length;q++)
{
if(names[q].startsWith("J"))
{
jTextArea1.append(names[q]);
}
}
}
}
Even when I type the correct answer it gives me the "number is not found" message.I'm dumbfounded on what to do.Any help will be greatly appreciated.
Try something like this. I am not sure if this is exactly what you are looking for...
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean found = false;
int searchvalue;
int[] lottoNumber = new int[6];
lottoNumber[0] = (int) ((56 * Math.random()) + 1);
lottoNumber[1] = (int) ((56 * Math.random()) + 1);
lottoNumber[2] = (int) ((56 * Math.random()) + 1);
lottoNumber[3] = (int) ((56 * Math.random()) + 1);
lottoNumber[4] = (int) ((56 * Math.random()) + 1);
lottoNumber[5] = (5);
System.out.print("number?");
searchvalue = input.nextInt();
for (int i = 0; i < lottoNumber.length; i++) {
if (lottoNumber[i] == searchvalue) {
found = true;
}
}
if (found == true) {
System.out.print("number is found" + "\n");
} else {
System.out.print("number is not found" + "\n");
}
}
}
This does not have GUI imports in this by the way.What exactly are you trying to do with this? Can you add the whole code?
Well the answer above works for me! So the answer is your :
int searchvalue=Integer.parseInt(JOptionPane.showInputDialog("number?"));
That line is probably causing the problem.
Try adding:
System.out.println("The number entered was:"+searchvalue);
and then compare it to the number you entered.

Null Pointer Exception using Object Arrays

I am planning to make an airline system. I have initialized the array using initSeats but it still throws back the NPE error. It happens when i call the seatChecker() from bookMenu.
public void initSeats(){
for(int b = 0; b < seatList.length; b++)
{
initC.setName("null");
initC.setEmail("null");
initC.setCreditNo(0);
initC.setAddress("null");
initC.setPassportNo("null");
seatList[b] = new Seat('A', 0, "null", 0.0, "Available", initC);
}
for(int d = 0; d <= 24; d++)
{
seatList[d].setSeatLetter('A');
seatList[d].setSeatNo(d);
}
for(int n = 25; n <= 48; n++)
{
seatList[n].setSeatLetter('B');
seatList[n].setSeatNo(n);
}
for(int m = 49; m <= 72; m++)
{
seatList[m].setSeatLetter('C');
seatList[m].setSeatNo(m);
}
for(int t = 73; t <= 96; t++)
{
seatList[t].setSeatLetter('D');
seatList[t].setSeatNo(t);
}
for(int q = 97; q <= 120; q++)
{
seatList[q].setSeatLetter('E');
seatList[q].setSeatNo(q);
}
for(int v = 121; v < 144; v++)
{
seatList[v].setSeatLetter('F');
seatList[v].setSeatNo(v);
}
for(int x = 0; x <= 48; x++)
{
seatList[x].setSection("Front");
seatList[x].setPrice(500);
}
for(int j = 49; j <= 96; j++)
{
seatList[j].setSection("Middle");
seatList[j].setPrice(250);
}
for(int u = 97; u < 144; u++)
{
seatList[u].setSection("Back");
seatList[u].setPrice(100);
}
}
public void seatChecker(int index)
{
String status = seatList[index].getStatus();
if(status.equalsIgnoreCase("Available")){
System.out.println("Seat is Available.");
}else{
System.out.println("Seat is not Available. Please Pick Another Seat.");
bookMenu();
}
}
public void bookMenu()
{
int choice1 = 0;
int index;
System.out.println("Where do you want to be seated?");
System.out.println("[1] Front");
System.out.println("[2] Middle");
System.out.println("[3] Back");
choice1 = sc.nextInt();
sc.nextLine();
if(choice1 == 1){
System.out.print("Choose a seat number (0 - 48): ");
index = sc.nextInt();
sc.nextLine();
seatChecker(index);
}else if(choice1 == 2){
System.out.println("Choose a seat number (49 - 96): ");
index = sc.nextInt();
sc.nextLine();
seatChecker(index);
}else if(choice1 == 3){
System.out.println("Choose a seat number (97 - 144): ");
index = sc.nextInt();
sc.nextLine();
seatChecker(index);
}else
{
System.out.println("Invalid Choice. Going back to Menu.");
MainMenu();
}
}
Null Pointer Exception Code
Exception in thread "main" java.lang.NullPointerException
at pkg.Airlines.AirlineUI.seatChecker(AirlineUI.java:132)
Seat Class
public class Seat{
private char seatLetter;
private int seatNo;
private String section;
private double price;
private String status;
private Customer customerDetails;
public Seat(char seatLetter, int seatNo, String section, double price, String status, Customer details)
{
this.seatLetter = seatLetter;
this.seatNo = seatNo;
this.section = section;
this.price = price;
this.status = status;
this.customerDetails = details;
}
public Customer getCustomerDetails() {
return customerDetails;
}
public void setCustomerDetails(Customer customerDetails) {
this.customerDetails = customerDetails;
}
public char getSeatLetter() {
return seatLetter;
}
public void setSeatLetter(char seatLetter) {
this.seatLetter = seatLetter;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getSeatNo() {
return seatNo;
}
public void setSeatNo(int seatNo) {
this.seatNo = seatNo;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
}
Probably the problems are this two line :
String status = seatList[index].getStatus();
if(status.equalsIgnoreCase("Available"))
First thing could be seatList[index] is not initialized . Once you declare an array of references as :
Seat[] array = new Seat[10];
The array contains 10 null references for Seat object . You need to instantiate them before using them :
Seat[0] = new Seat();
Second potential problem will be, this check :
if(status.equalsIgnoreCase("Available"))
Replace it to :
if("Available".equalsIgnoreCase(status))
to avoid any NullPointerException in case status is null.
P.S. Please show us the Seat class to understand your problem better.
Well is quite simple resolve a Null Pointer Exception.
Probably in one of the index of seatList there isn't a value.

Resources